Mission event file for Imperial Guard Stronghold mission
Руководства
/
Mission event file for Imperial Guard Stronghold mission
Обновлено 4 years ago от Merric

-- IMPORTS -- import("ScarUtil.scar") : has most of the scar function -- import("WXPScarUtil.scar") : more scar functions from DC and/or WA (I honestly not sure)

import("ScarUtil.scar") import("WXPScarUtil.scar")

-- TODO: -- Random Taunts IEs -- Change Mech Command IE


-- ONGAMESETUP -- OnGameSetup() : Mandatory Function that sets up the mission & sets up the players that are in the mission (Including AI Players). -- This function is run first and starts the entire mission and than starts OnInit( ) -- Also has list of the Global varibles defined in it ( g_ ) -- OnGameRestore() : Mandatory Function called after loading a saved game. -- Used to redefine some varibles after loading a save game -- Restores IE Arrays & sets up varible so games knows it has been restored

function OnGameSetup() -- Global varibles

-- Used to Track if the player is loading a save game
g_restoring = false

-- What Race based intel event to use
g_intelEvent_raceId = 0

-- Place to store the player Race, so I dont have to keep calling the functions to get them
g_raceName = "default_race"

-- Place to store the player Faction (Example: "Blood Ravens")
g_factionName = "default_factionName"

-- Place to store the Color Scheme being used for player race (Example: "default_1")
g_colorScheme = "default_colorScheme"

-- Place to stores the Type of HQ based on each players race (Example: "chaos_hq")
g_HQ_blueprint = " "

-- Place to stores the Type of Builder used based on each players race (Example: "chaos_squad_slave")
g_Builder_blueprint = " "

-- Number of each type of turret	
g_number_turret_heavy_bolter 		=	30
g_number_turret_missile				=	17

-- number of each type of heavy weapons teams
g_number_heavyWeapons_AntiInfantry		=	14
g_number_heavyWeapons_AntiVehicle		=	13

-- Tier to determine difficulty level of mission based on stronghold strength
	-- 1 = low, 2 = medium, 3 = high
g_strongholdStrengthTier	=	0	

-- Which Convoy Locations can we currently spawn convoys from
g_convoy_locationsToUse	=	6

-- Timer for Counting Down until next convoy spawns
g_convoy_Timer	=	0

-- Tracks how many convoys were destroyed, so the mission can react to the fact
g_number_convoys_destroyed	=	0

-- So Race based IE is played the first time
g_firstSpotterCaught = false

-- So Spotter Spawn IE doesn't play the first time (objective one covers it)
g_firstSpotter_Spawned = false

-- Checks if we can still spawn a new convoy in (does a mechanized command still exsist)
g_convoy_canSpawnNewOne	=	true

-- Checks if a convoy is currently spawned from each location
g_convoy_Spawned_table		=	{	false, false, false, false, false, false, false}

-- Stores the Ping Locations for the Stop the Convoys Objective
g_convoySpawnPings_Objective_Table = { 0,0,0,0,0,0,0}

-- what is the maximum number of extra weapons (grenade launchers and Plasma Guns in a squad (number increase based on research))
g_number_WeaponsPerSquad		=	3

-- are the special weapons enabled
g_grenadeLauncher_enabled	=	false
g_plasmaGun_enabled			=	false

-- are leaders (& Skills) enabled for guardsmen, kaskrin, & orgyn squads
g_leaders_enabled					=	false

-- What is the Current Alert Status of the Base
g_currentAlertStatus	=	0

-- Tracks if a Spotter is currently trying to fire
g_Spotter_Firing = false

-- Number of each type of idle unit
g_number_idle_baneBlade								=	4
g_number_idle_mainBase_lemanRussTank		=	7
g_number_idle_chimera									=	6
g_number_idle_lemanRussTank						=	10
g_number_idle_sentinel									=	16
g_number_idle_valkyrie									=	3

-- Controls if a idle vehicle has gone active
g_idle_baneBlade_table = 			{	false, false, false, false}
g_idle_chimera_table = 				{	false, false, false, false, false, false}
g_idle_lemanRussTank_table =	{	false, false, false, false, false,
														false, false, false, false, false}
g_idle_sentinel_table =				{	false, false, false, false, false, false, false, false,
														false, false, false, false, false, false, false, false}

-- Checks if each base has gone active yet
g_base_activated_CenterNorth	=	false
g_base_activated_CenterSouth	=	false
g_base_activated_Chimera			=	false
g_base_activated_Main				=	false
g_base_activated_North				=	false
g_base_activated_West				=	false
g_base_activated_West_Patrol	=	false
g_base_activated_Sentinel			=	false	
g_base_activated_Tank				=	false

-- Have we played the IE for the first time Enemy Attacks an Idle Base
g_IE_Fired_Attack_ChimeraBase	=	false
g_IE_Fired_Attack_SentinelBase		=	false
g_IE_Fired_Attack_TankBase			=	false

-- Have we played the IE for the Attacking Base/Gun after it goes active
g_IE_Fired_Attack_AirBase				=	true
g_IE_Fired_Attack_BigGun				=	true

-- How many mechanized commands must the player destroy to raise the Alert Levels (out of 6)
g_increase_AlertToOne_Bases		=	1
g_increase_AlertToTwo_Bases		=	2
g_increase_AlertToThree_Bases		=	3	--4
g_increase_AlertToFour_Bases		=	4	--5
g_increase_AlertToFive_Bases		=	6

-- Handles Highlightlighting of Objectives
g_PrimaryObjectives 		= -1
g_SecondaryObjectives 	= -1

------------------------------------------BALANCE VARIBLES----------------------------------
	--------------------- Starting Resources ----------------------------------------
	
	-- Amount of Initial Resource to give each of the AI Players
		-- Does Nothing For this Scenario
	g_amountRequisitionToGiveAI = 10000
	g_amountPowerToGiveAI = 5000
	
	-- Amount of Extra Resources to Give Player (Non Necron Races)
	g_amountRequisitionToGivePlayer = 1500
	g_amountPowerToGivePlayer = 500
	
	-- Amount of Extra Power Resource to Give to Necron Player
	g_amountPowerToGiveNecron = 1500
	
	-- Forward Base Code:
	-- generator markers start at 0
	g_bonus_gen_counter = 0
	-- turrer markers start at 6
	g_bonus_turret_counter = 6
	
	--------------------- Ai Troop Production ---------------------------------------
	
	-- Time a base takes to produce units once it goes active
		-- Once a unit produces, it will attack
	g_timer_centerNorthBase	=	330	--360
	g_timer_centerSouthBase	=	330	--360
	g_timer_initialLP					=	45
	g_timer_mainBase				=	420	--480
	g_timer_northBase				=	330	--360
	g_timer_westBase				=	210	--240
	
	--Idle Bases: Player Has to Attack to Activate
	g_timer_chimeraBase			=	60	--90
	g_timer_sentinelBase			=	60	--90
	g_timer_tankBase				=	60	--90
	
	--------------------- Mega Basilisk & Spotters  ---------------------------------
	
	-- Time from Alert Level Two until the Mega Basililsk & Spotters Start Producting (MOVED FROM GAME START DELAY)
	g_timeUntilBasilisk 	= 30
	
	-- Time a spotter has to be spotting for before the basilisk attack arrives: Delay is actually built into skill now -- 7 seconds
	g_basilisk_delay = 10
	
	-- Time it takes to produce a Spotter if one is needed
	g_productionTimer_Spotters = 150	--180
	
	-- Is the Spotter Activly Targeting Player Army (not always base)
	g_spotter_TargetArmy = false
	
	--------------------- Alert Level Increasing  -----------------------------------
	
	-- Time until Bases Upgrade Units, Get Better Research, & Begin Attacks
		-- Alerts also increase via Player Progress (destroying Convoys, Bases, etc)
		-- Timers just a backup for ramping up difficulty level of scenario
		-- 3 sec difference is so production can occur on the next second
		
		-- Time From Game Start Until Upgrade to Alert One (10 minutes)
		g_time_until_alertOne		=	597
		-- Time From Game Start Until Upgrade to Alert Two (20 minutes)
		g_time_until_alertTwo		=	1157
		-- Time From Game Start Until Upgrade to Alert Three (25 minutes)
		g_time_until_alertThree	=	1457	--1757
		-- Time From Game Start Until Upgrade to Alert Four (40 minutes)
		g_time_until_alertFour	=	2357	--2657
		-- Time From Game Start Until Upgrade to Alert Five (50 minutes)
		g_time_until_alertFive		=	2957
	
	-- How many convoys must the player destroy to raise the Alert Levels
	g_increase_AlertToOne_Convoy		=	3
	g_increase_AlertToTwo_Convoy		=	6
	g_increase_AlertToThree_Convoy	=	8
	g_increase_AlertToFour_Convoy		=	10
	g_increase_AlertToFive_Convoy		=	14
	
	--------------------- Base Activation  ------------------------------------------
	
	-- How Many Player Units attacking at once does it take for a base to go active early
	g_num_PlayerUnits_ActivateBase	=	2
	
	-- how long from game start before west base goes active
		-- Troop Production & Sentinel / Hellhound Patrols (Base has a 210 Production Cycle)
	g_time_before_westBase_activates				=	200	-- so first production will be at 210
	g_time_before_westBase_patrol_activates	=	600	-- so first production will be at 630
	
	-- how many major bases must be destroyed before main base activates (also activates if player attacks it or at Alert Level 5)
		-- Center North, Center South, North, West Base
	g_bases_before_mainBase_activates		=	4
	g_bases_count_mainBase_activates		=	0
	
	--------------------- Convoy to Produce Baneblades ------------------------------
	
	-- How Much time between convoys
	g_timeUntilNextConvoy	=	75
	g_timeUntilFirstConvoy	=	180
	
	-- Max Amount of Time a convoy can spend at each checkpoint
		-- basically how often checks to see if the convoy made a checkpoint and then sends to next
	g_convoy_MaxTime_SpentCheckpoint = 1
	
	-- How Many convoys have to reach mars command to make baneblade (set via stronghold strength)
	g_convoy_maxNumberForBaneBlade 			=	6
	g_convoy_currentNumberForBaneBlade 		=	0
	
	--does it start producing one baneblade or two
	g_spawnTwoBaneBlades = false
	
---------------------------------------------END BALANCE VARIBLES------------------------------

-- Can Squads Retreat?
g_retreating_enabled =	true

--What Percentage of the Squad do troops reinforce up to... (Changes Via Alert Levels)
g_reinforce_percent	=	0.70

-- Can Squad Capture?
g_canCaptureStrat	=	false
g_canCaptureRelic	=	true
g_canCaptureCrit	=	true

-- Check for Basic Strategic Point, Relic, Critical Point
g_blueprintRelic = Util_MakeBlueprintTable("relic_struct")
g_blueprintCritPoint = Util_MakeBlueprintTable("strategic_objective_struct")
g_blueprintStratPoint = Util_MakeBlueprintTable("strategic_point_flag")

-- Squad Skills & AI Stuff:
g_squad_attacking				=	0
g_squad_retreating			=	1		-- also covers normal moving (non-attack move)
g_squad_reinforcing			=	2
g_squad_loading					=	3
g_squad_usingSkill				=	4
g_squad_produced				=	5

-- Troops
g_initialLP_troops_status					=	{0}
g_centerNorthBase_troops_status		=	{0}
g_centerSouthBase_troops_status		=	{0,0,0}
g_chimeraBase_troops_status			=	{0}
g_mainBase_assassin_status				=	{0}
g_mainBase_troops_status				=	{0,0,0}
g_northBase_troops_status				=	{0,0}
g_sentinelBase_troops_status			=	{0,0}
g_westBase_troops_status				=	{0,0}

-- Vehicles
g_chimeraBase_chimera_status			=	{0}
g_centerSouthBase_chimera_status	=	{0}
g_centerNorthBase_basilisk_status	=	{0}
g_mainBase_basilisk_status				=	{0}
g_mainBase_hellhound_status			=	{0}
g_mainBase_lemanRuss_status			=	{0,0}	-- only 1 is used
g_northBase_marauder_status			=	{0,0}
g_tankBase_tank_status					=	{0,0}
g_sentinelBase_sentinel_status			=	{0,0}

-- Max Number of Troops the CenterSouth Base can produce / load into chimera
	-- Increase Via Alert Levels
g_num_chimera_troops	=	1

--------------------------------------------- INTEL EVENT ARRAYS ---------------------------------
-- CloakDetectTaunt: Random Taunts for when IG uses Comsat on a enemy unit
g_ie_CloakDetect_Taunt_Array = {
	EVENTS.IE_CloakDetectTaunt_One,
	EVENTS.IE_CloakDetectTaunt_Two, 
	EVENTS.IE_CloakDetectTaunt_Three}

-- ValkyrieDrop: Random IEs Taunts for when IG uses Valkyries to drop off units
g_ie_ValkyrieDrop_Array = {
	EVENTS.IE_ValkyrieDrop_One,
	EVENTS.IE_ValkyrieDrop_Two, 
	EVENTS.IE_ValkyrieDrop_Three}

-- AlertLevel: IEs for when Alert Levels Increase
g_ie_AlertLevel_Array = {
	EVENTS.IE_AlertLevel_One,
	EVENTS.IE_AlertLevel_Two,
	EVENTS.IE_AlertLevel_Three, 
	EVENTS.IE_AlertLevel_Four, 
	EVENTS.IE_AlertLevel_Five}

-- Spotter Caught: Random IEs for when Spotter is caught
g_ie_Spotter_Caught_Array = {
	EVENTS.IE_Spotter_Caught_One,
	EVENTS.IE_Spotter_Caught_Two,
	EVENTS.IE_Spotter_Caught_Three, 
	EVENTS.IE_Spotter_Caught_Four}

-- Spotter Ready To Fire: IEs for when Spotter is in position to fire the mega artillary
g_ie_Spotter_ReadyToFire_Array = {
	EVENTS.IE_Spotter_ReadyToFire_One,
	EVENTS.IE_Spotter_ReadyToFire_Two,
	EVENTS.IE_Spotter_ReadyToFire_Three, 
	EVENTS.IE_Spotter_ReadyToFire_Four, 
	EVENTS.IE_Spotter_ReadyToFire_Five}

-- Artillary FirstSpotter Found: (Race Based) IEs for first time a spotter is found
g_ie_Artillary_FirstSpotter_Found_Array = {
	EVENTS.IE_Artillary_FirstSpotter_Found_Chaos,
	EVENTS.IE_Artillary_FirstSpotter_Found_DarkEldar,
	EVENTS.IE_Artillary_FirstSpotter_Found_Eldar,
	EVENTS.IE_Artillary_FirstSpotter_Found_Guard,	-- not used since this is guard mission (is used though for array consistency)
	EVENTS.IE_Artillary_FirstSpotter_Found_Necron,
	EVENTS.IE_Artillary_FirstSpotter_Found_Ork,
	EVENTS.IE_Artillary_FirstSpotter_Found_Sisters, 
	EVENTS.IE_Artillary_FirstSpotter_Found_Space, 
	EVENTS.IE_Artillary_FirstSpotter_Found_Tau}

--------------------------------------------- END INTEL EVENT ARRAYS --------------------------------

-- Get the player race & store for later access
g_raceName = MetaMap_GetPlayerNRaceName(0)

-- Create the Human Player
g_Player1 = Setup_Player(0, g_factionName, g_raceName, 0)

-- Sets up HQ, Builder, Faction Name, Color Scheme, Exception Lists, etc...
Rule_Player_Race_Dependant_Stuff()

-- NOW THAT HUMAN IS SET UP, NEED TO SET UP THE AI PLAYERS AND TEAMS	
-- Imperial Guard AI Players
g_Player2 = Setup_Player (1, "$3950218", "guard_race", 1)

-- Only Used in the NIS
g_Player3 = Setup_Player (2, "$3950218", "guard_race", 1)

-- Only the Convoy Unit is part of this team
g_Player4 = Setup_Player (3, "$3950218", "guard_race", 1)

-- Spotters for the Mega-Basilisk
g_Player5 = Setup_Player (4, "$3950218", "guard_race", 1)

-- Only the produced Baneblades is part of this team
g_Player7 = Setup_Player (6, "$3950218", "guard_race", 1)

-- Set IG Color Scheme
Misc_PlayerTeamColor(g_Player2, "default_4")
Misc_PlayerTeamColor(g_Player3, "default_4")
Misc_PlayerTeamColor(g_Player4, "default_4")
Misc_PlayerTeamColor(g_Player5, "default_4")
Misc_PlayerTeamColor(g_Player7, "default_4")	

end

-- Used to redefine some varibles after loading a save game -- Restores IE Arrays & sets up varible so games knows it has been restored function OnGameRestore() -- So game knows to run Rule_RestoreSupport() since the player has reloaded a save game g_restoring = true

--------------------------------------------- INTEL EVENT ARRAYS ---------------------------------
-- CloakDetectTaunt: Random Taunts for when IG uses Comsat on a enemy unit
g_ie_CloakDetect_Taunt_Array = {
	EVENTS.IE_CloakDetectTaunt_One,
	EVENTS.IE_CloakDetectTaunt_Two, 
	EVENTS.IE_CloakDetectTaunt_Three}

-- ValkyrieDrop: Random IEs Taunts for when IG uses Valkyries to drop off units
g_ie_ValkyrieDrop_Array = {
	EVENTS.IE_ValkyrieDrop_One,
	EVENTS.IE_ValkyrieDrop_Two, 
	EVENTS.IE_ValkyrieDrop_Three}

-- AlertLevel: IEs for when Alert Levels Increase
g_ie_AlertLevel_Array = {
	EVENTS.IE_AlertLevel_One,
	EVENTS.IE_AlertLevel_Two,
	EVENTS.IE_AlertLevel_Three, 
	EVENTS.IE_AlertLevel_Four, 
	EVENTS.IE_AlertLevel_Five}

-- Spotter Caught: Random IEs for when Spotter is caught
g_ie_Spotter_Caught_Array = {
	EVENTS.IE_Spotter_Caught_One,
	EVENTS.IE_Spotter_Caught_Two,
	EVENTS.IE_Spotter_Caught_Three, 
	EVENTS.IE_Spotter_Caught_Four}

-- Spotter Ready To Fire: IEs for when Spotter is in position to fire the mega artillary
g_ie_Spotter_ReadyToFire_Array = {
	EVENTS.IE_Spotter_ReadyToFire_One,
	EVENTS.IE_Spotter_ReadyToFire_Two,
	EVENTS.IE_Spotter_ReadyToFire_Three, 
	EVENTS.IE_Spotter_ReadyToFire_Four, 
	EVENTS.IE_Spotter_ReadyToFire_Five}

-- Artillary FirstSpotter Found: (Race Based) IEs for first time a spotter is found
g_ie_Artillary_FirstSpotter_Found_Array = {
	EVENTS.IE_Artillary_FirstSpotter_Found_Chaos,
	EVENTS.IE_Artillary_FirstSpotter_Found_DarkEldar,
	EVENTS.IE_Artillary_FirstSpotter_Found_Eldar,
	EVENTS.IE_Artillary_FirstSpotter_Found_Guard,	-- not used since this is guard mission (is used though for array consistency)
	EVENTS.IE_Artillary_FirstSpotter_Found_Necron,
	EVENTS.IE_Artillary_FirstSpotter_Found_Ork,
	EVENTS.IE_Artillary_FirstSpotter_Found_Sisters, 
	EVENTS.IE_Artillary_FirstSpotter_Found_Space, 
	EVENTS.IE_Artillary_FirstSpotter_Found_Tau}
--------------------------------------------- END INTEL EVENT ARRAYS --------------------------------

end

-- Restore some stuff in case a player saves & loads a game function Rule_RestoreSupport() -- Replay the Idle Animations for the Remaining Idle Vehicles: if g_restoring == true then -- Sentinels: for i = 1,g_number_idle_sentinel do -- if the sentinel still exsists (and hasn't gone active yet) if SGroup_Count("sg_idle_sentinel_"..i) == 1 and g_idle_sentinel_table[i] == false then -- Play the Shutdown Animation: Anim_PlaySGroupAnim( "sg_idle_sentinel_"..i, "sp_shutdown" ) end end

	-- Chimeras:
	for i = 1,g_number_idle_chimera do
		-- if the chimera still exsists (and hasn't gone active yet)
		if SGroup_Count("sg_idle_chimera_"..i) == 1 and
			g_idle_chimera_table[i] == false
		then
			-- Play the Shutdown Animation:
			Anim_PlaySGroupAnim("sg_idle_chimera_"..i, "sp_shutdown" )
		end
	end
	
	-- Leman Russ Tanks: Main Base: Never Go Active
	for i=1,g_number_idle_mainBase_lemanRussTank do
		-- if the Leman Russ still exsists
		if SGroup_Count("sg_mainBase_lemanRussTankActivator"..i) == 1
		then
			-- Play the Shutdown Animation:
			Anim_PlaySGroupAnim("sg_idle_mainBase_lemanRussTank_"..i, "sp_shutdown" )
		end		
	end
	
	-- Leman Russ Tanks: Tank Base:
	for i = 1,g_number_idle_lemanRussTank do
		-- if the leman russ tank still exsists (and hasn't gone active yet)
		if SGroup_Count("sg_idle_lemanRussTank_"..i) == 1 and
			g_idle_lemanRussTank_table[i] == false
		then
			-- Play the Shutdown Animation:
			Anim_PlaySGroupAnim("sg_idle_lemanRussTank_"..i, "sp_shutdown" )
		end
	end
	
	-- Valkries: North base -- Never Go Active
	for i=1,g_number_idle_valkyrie do
		-- if the Valkrie still exsists
		if SGroup_Count("sg_idle_valkyrie_"..i) == 1
		then
			-- Play the Shutdown Animation:
			Anim_PlaySGroupAnim( "sg_idle_valkyrie_"..i, "sp_shutdown" )
		end		
	end
end

g_restoring = false	

end

-- END OF " GAME SETUP & RESTORE " RULES


-- INITALIZATION -- OnInit() : Mandatory Function that sets up the mission -- Called after OnGameSetup() : Not Sure if possible for something to come between the two of them -- Used for pregame functions, things that should happen before the player officially enters the world -- Scar_AddInit(OnInit) : Mandatory Function that registers OnInit function with scar.

function OnInit() -- Set up stuff based on the difficulty level of the stronghold Rule_Stronghold_Difficulty_Strength_Stuff()

--Function Used to set the pregame state of the AI (basically disables all the AI)
Rule_PresetAI()

-- Function used to create all the Ai Controlled Buildings on the Map
Rule_Create_All_Ai_Initial_Buildings( )

-- Function used to create all the Initial Ai Units on the Map
Rule_Create_All_Ai_Initial_Units( )

-- Sets up & Plays the Opening NIS:
WXP_OpeningNISPreset( )
Util_StartNIS( EVENTS.NIS_Intro )	

-- Rule_GameStart : Function used to Start the Actual Mission
Rule_Add( Rule_GameStart )	

end

-- This registers your init function with scar. Scar_AddInit(OnInit)

-- END OF ALL "INITALIZATION" RULES


-- EXTRA INITIAL SETUP -- Rule_SetupMusicPlaylist() : Used to Setup the music & ambient soundtracks -- Rule_Stronghold_Difficulty_Strength_Stuff() : Used to Set up stuff based on the difficulty level of the stronghold (10-17) -- Rule_PresetAI() : Used to Disable AI Players

-- Used to Setup the music & ambient soundtracks function Rule_SetupMusicPlaylist() -- MUSIC TRACKS

-- clear the music playlist
Sound_PlaylistClear( PC_Music )

-- Add tracks to the playlist
Sound_PlaylistAddTrack( PC_Music, "MU_IG_STR_ImpGd" )
Sound_PlaylistAddTrack( PC_Music, "MU_IG_STR_ImpGd_perc" )
Sound_PlaylistAddTrack( PC_Music, "MU_IG_STR_ImpGd_perc_str" )
Sound_PlaylistAddTrack( PC_Music, "MU_IG_STR_ImpGd_perc_brass" )
Sound_PlaylistAddTrack( PC_Music, "MU_IG_STR_ImpGd_perc_voice" )

-- Mark these tracks to play in order or random (True is in order) 
Sound_PlaylistSetorder( PC_Music, true )
-- add silence between tracks in seconds (Randomly chooses time between the two numbers)
Sound_PlaylistSetSilence( PC_Music, 5, 10 )

--Silvey Polish 10/10/07:  I had to add this to get the music to play after moving this function after the opening NIS.	
Sound_SetVolumeModifierMusic(1.0)
Sound_PlaylistStart(PC_Music)

-- AMBIENT TRACKS

-- clear the ambient playlist
Sound_PlaylistClear( PC_Ambient )
--add tracks to the playlist
Sound_PlaylistAddTrack( PC_Ambient, "Ambience_Imperial_City" )
Sound_PlaylistAddTrack( PC_Ambient, "Ambience_Imperial_City" )
-- Mark these tracks to play in order or random (True is in order) 
Sound_PlaylistSetorder( PC_Ambient, true )
-- add silence between tracks in seconds (Randomly chooses time between the two numbers)
Sound_PlaylistSetSilence( PC_Ambient, 5, 10 )

end

-- Used to Set up stuff based on the difficulty level of the stronghold (10-17) function Rule_Stronghold_Difficulty_Strength_Stuff() -- Get the strength of the stronghold from the MetaMap g_strongholdStrength = MetaMap_GetTerritoryMilitaryStrength(MetaMap_GetDefendingTerritoryIndex())

--print("Stronghold Strength is: "..g_strongholdStrength)

-- Set the difficulty tier based on stronghold strength: (10,11,12)
if g_strongholdStrength <= 12
then
	g_strongholdStrengthTier = 1

-- Set the difficulty tier based on stronghold strength: (13,14,15)
elseif g_strongholdStrength <= 15
then
	g_strongholdStrengthTier = 2

-- Set the difficulty tier based on stronghold strength: (16,17)
else
	g_strongholdStrengthTier = 3
end

end

-- Used to Disable AI Players function Rule_PresetAI() Cpu_Enable(g_Player2, false) Cpu_Enable(g_Player4, false) Cpu_Enable(g_Player5, false) Cpu_Enable(g_Player7, false) end

-- END OF ALL "EXTRA INITIAL SETUP" RULES


-- INITIAL PLAYER SETUP RULES -- Rule_Player_Race_Dependant_Stuff() : Handles setting everything in scenario that changes based on the player race -- Rule_Create_All_Player_Initial_Units() : Creates all the Players Initial Units on the Map (including Honor Guard) -- Rule_Create_All_Player_Initial_Buildings() : Creates all the Players Initial Buildings on the Map ( & give resources) -- ForwardBases() : Forward Base Special Ability that the Sisters start with

-- Handles setting everything in scenario that changes based on the player race function Rule_Player_Race_Dependant_Stuff() if g_raceName == "chaos_marine_race" then -- Faction name that Race is using g_factionName = "$3950214"

	-- What Intel Events race is using
	g_intelEvent_raceId = 1
	
	-- Color Scheme that Race is using
	g_colorScheme = "default_0"

	-- HQ that Race uses
	g_HQ_blueprint = "chaos_hq"
	
	-- Builder that Race uses
	g_Builder_blueprint = "chaos_squad_slave"
	
	-- used for forward base ability
	g_bonus_generator	= "chaos_plasma_generator"
	g_bonus_turret			= "chaos_turret_bolter"
	g_bonus_barracks		= "chaos_temple"
	g_bonus_barracks2		= 0 --value on used for tau kroot nest, dummy value for all other races, like the Tau turret.
	g_bonus_research		= "chaos_armoury"
	
	-- Used for Defeat Checks
	t_building_exceptions = {
		"chaos_thermo_plasma_generator",
		"chaos_plasma_generator",
		"chaos_turret_bolter",
		"chaos_mine_field",
		"chaos_listening_post"}
	
	-- Used for Defeat Checks
	t_unit_exceptions = {}
	
elseif g_raceName == "dark_eldar_race"
then
	-- Faction name that Race is using
	g_factionName = "$3950220"
	
	-- What Intel Events race is using
	g_intelEvent_raceId = 2
	
	-- Color Scheme that Race is using
	g_colorScheme = "default_1"
	
	-- HQ that Race uses
	g_HQ_blueprint = "dark_eldar_hq"
	
	-- Builder that Race uses
	g_Builder_blueprint = "dark_eldar_squad_slave"
	
	-- used for forward base ability
	g_bonus_generator	= "dark_eldar_plasma_generator"
	g_bonus_turret			= "dark_eldar_slave_caravel"
	g_bonus_barracks		= "dark_eldar_hall_of_blood"
	g_bonus_barracks2		= "dark_eldar_skimmer_shop"
	g_bonus_research		= "dark_eldar_haemonculus_laboratory"
	
	-- Used for Defeat Checks
	t_building_exceptions = {
		"dark_eldar_plasma_generator",
		"dark_eldar_thermo_plasma",
		"dark_eldar_slave_caravel",
		"dark_eldar_listening_post"}
	
	-- Used for Defeat Checks
	t_unit_exceptions = {}

elseif g_raceName == "eldar_race"
then
	-- Faction name that Race is using
	g_factionName = "$3950217"
	
	-- What Intel Events race is using
	g_intelEvent_raceId = 3
	
	-- Color Scheme that Race is using
	g_colorScheme = "default_5"
	
	-- HQ that Race uses
	g_HQ_blueprint = "eldar_hq"
	
	-- Builder that Race uses
	g_Builder_blueprint = "eldar_squad_bonesinger"
	
	-- used for forward base ability
	g_bonus_generator	= "eldar_warp_generator"
	g_bonus_turret			= "eldar_support_platform_scatterlaser"
	g_bonus_barracks		= "eldar_aspect_portal"
	g_bonus_barracks2		= 0 --value on used for tau kroot nest, dummy value for all other races, like the Tau turret.
	g_bonus_research		= "eldar_soul_shrine"
	
	-- Used for Defeat Checks
	t_building_exceptions = {
		"eldar_advanced_warp_generator",
		"eldar_warp_generator",
		"eldar_support_platform_scatterlaser",
		"eldar_mine_field",
		"eldar_listening_post"}
	
	-- Used for Defeat Checks
	t_unit_exceptions = {}	

-- Should not be possible to be this race on this map
elseif g_raceName == "guard_race"
then
	-- Faction name that Race is using
	g_factionName = "$3950219"
	
	-- What Intel Events race is using
	g_intelEvent_raceId = 4
	
	-- Color Scheme that Race is using
	g_colorScheme = "default_4"
	
	-- HQ that Race uses
	g_HQ_blueprint = "guard_hq"
	
	-- Builder that Race uses
	g_Builder_blueprint = "guard_squad_enginseer"
	
	-- used for forward base ability
	g_bonus_generator	= "guard_plasma_generator"
	g_bonus_turret			= "guard_turret_heavy_bolter"
	g_bonus_barracks		= "guard_infantry"
	g_bonus_barracks2		= 0 --value on used for tau kroot nest, dummy value for all other races, like the Tau turret.
	g_bonus_research		= "guard_tactica"
	
	-- Used for Defeat Checks
	t_building_exceptions = {
		"guard_thermo_plasma",
		"guard_plasma_generator",
		"guard_turret_heavy_bolter",
		"guard_mines",
		"guard_listening_post"}
		
	-- Used for Defeat Checks
	t_unit_exceptions = {}

elseif g_raceName == "necron_race"
then
	-- Faction name that Race is using
	g_factionName = "$3950223"
	
	-- What Intel Events race is using
	g_intelEvent_raceId = 5
	
	-- Color Scheme that Race is using
	g_colorScheme = "default_0"
	
	-- HQ that Race uses
	g_HQ_blueprint =	"monolith"
	
	-- Builder that Race uses
	g_Builder_blueprint = "necron_builder_scarab_squad"
	
	-- used for forward base ability
	g_bonus_generator	= "necron_plasma_generator"
	g_bonus_turret			= "necron_turret"
	g_bonus_barracks		= "necron_summoning_core"
	g_bonus_barracks2		= 0 --value on used for tau kroot nest, dummy value for all other races, like the Tau turret.
	g_bonus_research		= "necron_forbidden_archive"
	
	-- Used for Defeat Checks
	t_building_exceptions = {
		"necron_thermoplasma_generator",
		"necron_plasma_generator",
		"necron_turret",
		"necron_listening_post"}
	
	-- Used for Defeat Checks
	t_unit_exceptions = {}

elseif g_raceName == "ork_race"
then
	-- Faction name that Race is using
	g_factionName = "$3950215"
	
	-- What Intel Events race is using
	g_intelEvent_raceId = 6
	
	-- Color Scheme that Race is using
	g_colorScheme = "default_3"
	
	-- HQ that Race uses
	g_HQ_blueprint = "ork_hq"
	
	-- Builder that Race uses
	g_Builder_blueprint = "ork_squad_grot"
	
	-- used for forward base ability
	g_bonus_generator	= "ork_generator"
	g_bonus_turret			= "ork_waagh_banner"
	g_bonus_barracks		= "ork_boy_hut"
	g_bonus_barracks2		= 0 --value on used for tau kroot nest, dummy value for all other races, like the Tau turret.
	g_bonus_research		= "ork_pile_o_guns"
	
	-- Used for Defeat Checks
	t_building_exceptions = {
		"ork_bigger_generator",
		"ork_generator",
		"ork_waagh_banner",
		"ork_mine_field",
		"ork_listening_post"}
	
	-- Used for Defeat Checks
	t_unit_exceptions = {}		

elseif g_raceName == "sisters_race"
then
	-- Faction name that Race is using
	g_factionName = "$3900048"
	
	-- What Intel Events race is using
	g_intelEvent_raceId = 7
	
	-- Color Scheme that Race is using
	g_colorScheme = "default_2"
	
	-- HQ that Race uses
	g_HQ_blueprint = "sisters_hq"
	
	-- Builder that Race uses
	g_Builder_blueprint = "sisters_squad_servitor"
	
	-- used for forward base ability
	g_bonus_generator	= "sisters_plasma_generator"
	g_bonus_turret			= "sisters_turret_flamer"
	g_bonus_barracks		= "sisters_infantry"
	g_bonus_barracks2		= 0 --value on used for tau kroot nest, dummy value for all other races, like the Tau turret.
	g_bonus_research		= "sisters_sanctuary"
	
	-- Used for Defeat Checks
	t_building_exceptions = {
		"sisters_plasma_generator",
		"sisters_thermo_plasma",
		"sisters_turret_flamer",
		"sisters_mines",
		"sisters_listening_post"}
	
	-- Used for Defeat Checks
	t_unit_exceptions = {}

elseif g_raceName == "space_marine_race"
then
	-- Faction name that Race is using
	g_factionName = "$3950213"
	
	-- What Intel Events race is using
	g_intelEvent_raceId = 8
	
	-- Color Scheme that Race is using
	g_colorScheme = "default_0"
	
	-- HQ that Race uses
	g_HQ_blueprint = "space_marine_hq"
	
	-- Builder that Race uses
	g_Builder_blueprint = "space_marine_squad_servitor"
	
	-- used for forward base ability
	g_bonus_generator	= "space_marine_generator"
	g_bonus_turret			= "space_marine_turret_bolter"
	g_bonus_barracks		= "space_marine_barracks"
	g_bonus_barracks2		= 0 --value on used for tau kroot nest, dummy value for all other races, like the Tau turret.
	g_bonus_research		= "space_marine_armoury"
	
	-- Used for Defeat Checks
	t_building_exceptions = {
		"space_marine_thermo_generator",
		"space_marine_generator",
		"space_marine_turret_bolter",
		"space_marine_mine_field",
		"space_marine_listening_post"}
	
	-- Used for Defeat Checks
	t_unit_exceptions = {}

elseif g_raceName == "tau_race"
then
	-- Faction name that Race is using
	g_factionName = "$3950224"
	
	-- What Intel Events race is using
	g_intelEvent_raceId = 9
	
	-- Color Scheme that Race is using
	g_colorScheme = "default_4"
	
	-- HQ that Race uses
	g_HQ_blueprint = "tau_hq"
	
	-- Builder that Race uses
	g_Builder_blueprint = "tau_builder_squad"
	
	-- used for forward base ability
	g_bonus_generator	= "tau_plasma_generator"
	g_bonus_turret			= 0  --tau have no turrets, so zero is simply a filler value to establish the variable instead of writting cutom checks for tau later.  0 will never be a value fed in by code, so it simply allows the algorithm to function in a standadrd manner for all races.
	g_bonus_barracks		= "tau_barracks"
	g_bonus_barracks2		= "tau_kroot_nest"
	g_bonus_research		= "tau_research_building"
	
	-- Used for Defeat Checks
	t_building_exceptions = {
		"tau_thermoplasma_generator",
		"tau_plasma_generator",
		"tau_listening_post"}
	
	-- Used for Defeat Checks
	t_unit_exceptions = {}
end

-- Set the Faction Name of the player
Setup_SetPlayerName(g_Player1, g_factionName)

-- Set the Color Schemes Here 
Misc_PlayerTeamColor(g_Player1, g_colorScheme)

end

-- Creates all the Players Initial Units on the Map (including Honor Guard) function Rule_Create_All_Player_Initial_Units() -- Clear the Honor Guard List t_honorGuardUnits = {}

--Set up the Unlocked wargear upgrades
MetaMap_UpdatePlayerWargear(g_Player1)

--Set up the List of the Honor Guard units
MetaMap_GetRaceStartingSquadsList(g_raceName, t_honorGuardUnits)

-- Create the Honor Guard Units on the Map
for j = 1,  table.getn(t_honorGuardUnits) do
	Util_CreateSquadsAtMarker(g_Player1, "sg_honorGuard", t_honorGuardUnits[j], "mkr_honorGuard_Location", 1)
end

-- Create Player Builders
Util_CreateSquadsAtMarker(g_Player1 , "sg_player_mainBase_builder", g_Builder_blueprint, "mkr_player_mainBase_builder", 1)

end

-- Creates all the Players Initial Buildings on the Map ( & give resources) -- Also Handles Forward Bases function Rule_Create_All_Player_Initial_Buildings( ) -- Create the player buildings: HQ User_CreateBuilding(g_Player1,"eg_player_mainBase_HQ", g_HQ_blueprint,"mkr_player_mainBase_HQ", 1)

-- Handle the Forward Base Special Ability
ForwardBases()

-- Sets the Initial Player Resources (RT_Requisition, RT_Power)
if g_raceName == "necron_race"
then
	-- If Necron, only give power
	Player_SetResource(g_Player1, RT_Power, g_amountPowerToGiveNecron)
else
	-- Otherwise give both resources
	Player_SetResource(g_Player1, RT_Requisition, g_amountRequisitionToGivePlayer)
	Player_SetResource(g_Player1, RT_Power, g_amountPowerToGivePlayer)
end

end

-- Forward Base Special Ability that the Sisters start with function ForwardBases() --Add in any bonus buildings made availible if the player has purchased them via owning Hyperion peaks province t_blueprintEntitybonus = {}

MetaMap_GetAttackingRaceStartingEntitiesList(t_blueprintEntitybonus)

for j=1,table.getn(t_blueprintEntitybonus) do
	if t_blueprintEntitybonus[j] == g_bonus_generator
	then
		User_CreateBuilding(g_Player1, "eg_Bonus"..j, t_blueprintEntitybonus[j], "MM_Reinforcement"..g_bonus_gen_counter, 1)
		
		--increase by one, the next generator will then spawn at the correct marker after this one
		g_bonus_gen_counter = g_bonus_gen_counter + 1
	
	elseif t_blueprintEntitybonus[j] == g_bonus_turret
	then
		User_CreateBuilding(g_Player1, "eg_Bonus"..j, t_blueprintEntitybonus[j], "MM_Reinforcement"..g_bonus_turret_counter, 1)
		
		--increase by one, the next turret will then spawn at the correct marker after this one
		g_bonus_turret_counter = g_bonus_turret_counter + 1
	
	elseif t_blueprintEntitybonus[j] == g_bonus_barracks
	then
		User_CreateBuilding(g_Player1, "eg_Bonus"..j, t_blueprintEntitybonus[j], "MM_Reinforcement10", 1)
	
	elseif t_blueprintEntitybonus[j] == g_bonus_research
	then
		User_CreateBuilding(g_Player1, "eg_Bonus"..j, t_blueprintEntitybonus[j], "MM_Reinforcement11", 1)
	
	elseif t_blueprintEntitybonus[j] == g_bonus_barracks2
	then
		User_CreateBuilding(g_Player1, "eg_Bonus"..j, t_blueprintEntitybonus[j], "MM_Reinforcement13", 1)
	end
end

end

-- Code to Always Builds the building (prevents crashes & makes sure the buildings spawned) function User_CreateBuilding(p_PlayerID, p_EGroupID, p_Blueprint, p_MarkerName, complete)

-- This will force the building to spawn at a position (Ignores Units in the way)
	-- This could have been placed where User_CreateBuilding() was but this new tech function was added later since old Silvey Methods Didn't work well with percentage buildings 
Entity_CreateBuildingPositionForce(p_PlayerID, p_EGroupID, p_Blueprint, Marker_GetPosition(Marker_FromName(p_MarkerName, "basic_marker" )), complete)

-- l_EntityID = Entity_Create(p_Blueprint, p_PlayerID, Marker_GetPosition(Marker_FromName(p_MarkerName, "basic_marker" ))) -- EGroup_Add(EGroup_CreateIfNotFound(p_EGroupID), l_EntityID)

-- Entity_Spawn(l_EntityID)

-- I added this part so it can build at a percentage

-- if complete == 0 -- then -- Entity_SetBuildingProgress( l_EntityID, 0 ) -- end end

-- END OF ALL "INITIAL PLAYER SETUP" RULES


-- CREATE AI BUILDINGS RULES -- Rule_Create_All_Ai_Initial_Buildings() : Create all AI Bases & give them initial resources & strategic points : Called from OnInit( ) -- Rule_Create_CenterBase_Buildings() : Create Buildings for Center Bases (also creates the HQs for the Mega Basilisk Spotter Objective & the MegaBasilisk) -- Rule_Create_ConvoyBase_Buildings( ) : Create Buildings for Convoy Bases -- Rule_Create_MainBase_Buildings( ) : Create Buildings for the Main Base (also creates the Mars Patterns for the Destroy Mars Pattern Command Objective) -- Rule_Setup_AI_StrategicPoints( ) : Setup the Strategic Points, Critical Points, & Relics to AI Control -- Rule_Create_Turrets( ) : Create and upgrade all the turrets on the map

-- Create all AI Bases & give them initial resources & strategic points : Called from OnInit( ) function Rule_Create_All_Ai_Initial_Buildings() -- Create Buildings for Center Base Rule_Create_CenterBase_Buildings( )

-- Create Buildings for Convoy Bases
Rule_Create_ConvoyBase_Buildings( )

-- Create Buildings for the Main Base
Rule_Create_MainBase_Buildings( )

-- Create and upgrade all the turrets on the map
Rule_Create_Turrets( )

-- Setup the Strategic Points, Critical Points,  & Relics to AI Control
Rule_Setup_AI_StrategicPoints( )

-- Set AI Starting Resources
Player_SetAllResources(g_Player2, g_amountRequisitionToGiveAI, g_amountPowerToGiveAI, 0)
Player_SetAllResources(g_Player3, g_amountRequisitionToGiveAI, g_amountPowerToGiveAI, 0)
Player_SetAllResources(g_Player4, g_amountRequisitionToGiveAI, g_amountPowerToGiveAI, 0)
Player_SetAllResources(g_Player5, g_amountRequisitionToGiveAI, g_amountPowerToGiveAI, 0)
Player_SetAllResources(g_Player7, g_amountRequisitionToGiveAI, g_amountPowerToGiveAI, 0)

end

-- Create Buildings for Center Bases (also creates the HQs for the Mega Basilisk Spotter Objective & the MegaBasilisk) function Rule_Create_CenterBase_Buildings() -- Used to track the Completion of StopSpotterProduction_Objective EGroup_Create("eg_centerBase_Spotters_Production_Objective")

-- Create the mega basilisk
Entity_CreateBuildingMarker(g_Player2,"eg_MegaBasilisk_Objective", "mega_basilisk_dxp3","mkr_centerBase_bigGun", 1)

-- Create the Field Command HQ & Add to Spotter Production Objective EGroup
	-- These are used for the Production of Spotters
for i = 1, 2 do
	Entity_CreateBuildingMarker(g_Player2,"eg_centerBase_HQ"..i, "guard_hq","mkr_centerBase_HQ"..i, 1)
	EGroup_AddGroup("eg_centerBase_Spotters_Production_Objective", "eg_centerBase_HQ"..i)
end

-- Create the Infantry Command
for i = 1, 4 do
	Entity_CreateBuildingMarker(g_Player2,"eg_centerBase_infantryCommand"..i, "guard_infantry","mkr_centerBase_infantryCommand"..i, 1)
end

-- Create the Mechanized Command
for i = 1, 2 do
	Entity_CreateBuildingMarker(g_Player2,"eg_centerBase_mechanizedCommand"..i, "guard_mechanized","mkr_centerBase_mechanizedCommand"..i, 1)
end

-- Visually Add Basilisk Depot to the CenterNorth Mech Command (Mech Command 2 produces chimeras which have no depot)
EGroup_ForceAddOn("eg_centerBase_mechanizedCommand1", "addon_guard_basilisk_depot" )

-- Create the Plasma generators
for i = 1, 6 do
	Entity_CreateBuildingMarker(g_Player2,"eg_centerBase_power"..i, "guard_plasma_generator","mkr_centerBase_power"..i, 1)
end

-- Create the Tactica Control
for i = 1, 2 do
	Entity_CreateBuildingMarker(g_Player2,"eg_centerBase_tacticaControl"..i, "guard_tactica","mkr_centerBase_tacticaControl"..i, 1)
end

end

-- Create Buildings for Convoy Bases function Rule_Create_ConvoyBase_Buildings() -- Used to track the Completion of StopSpotterProduction_Objective EGroup_Create("eg_StopBomberProduction_Objective")

-- Create the Field Command HQ
for i = 1, 2 do
	Entity_CreateBuildingMarker(g_Player2,"eg_convoyBase_HQ"..i, "guard_hq","mkr_convoyBase_HQ"..i, 1)
end

-- Create the Infantry Command
for i = 2, 8 do
	Entity_CreateBuildingMarker(g_Player2,"eg_convoyBase_infantryCommand"..i, "guard_infantry","mkr_convoyBase_infantryCommand"..i, 1)
end

-- Visually Add the Quarters to the North Base Infantry Commands
for i =6,7 do
	EGroup_ForceAddOn("eg_convoyBase_infantryCommand"..i, "addon_guard_kasrkin_quarters" )
	EGroup_ForceAddOn("eg_convoyBase_infantryCommand"..i, "addon_guard_ogryn_quarters" )
end

-- Create the Mechanized Command
for i = 1, 8 do
	Entity_CreateBuildingMarker(g_Player2,"eg_convoyBase_mechanizedCommand"..i, "guard_mechanized","mkr_convoyBase_mechanizedCommand"..i, 1)
end

--Visually Add the Depots to the Mech Commands
	--North Base: Marauders
	EGroup_ForceAddOn("eg_convoyBase_mechanizedCommand5", "addon_guard_marauder_depot" )
	EGroup_ForceAddOn("eg_convoyBase_mechanizedCommand6", "addon_guard_marauder_depot" )

	--Tank Base: LemanRuss
	EGroup_ForceAddOn("eg_convoyBase_mechanizedCommand4", "addon_guard_lemanruss_depot" )

	--Sentinel Base: Sentinels
	EGroup_ForceAddOn("eg_convoyBase_mechanizedCommand2", "addon_guard_sentinel_depot" )
	EGroup_ForceAddOn("eg_convoyBase_mechanizedCommand3", "addon_guard_sentinel_depot" )

	-- WestBase: Hellhounds & Sentinels
	EGroup_ForceAddOn("eg_convoyBase_mechanizedCommand7", "addon_guard_sentinel_depot" )
	EGroup_ForceAddOn("eg_convoyBase_mechanizedCommand8", "addon_guard_sentinel_depot" )
	EGroup_ForceAddOn("eg_convoyBase_mechanizedCommand7", "addon_guard_hellhound_depot" )
	EGroup_ForceAddOn("eg_convoyBase_mechanizedCommand8", "addon_guard_hellhound_depot" )

-- Add Mech Commands that Produce Bombers to the Objective EGroup
EGroup_AddGroup("eg_StopBomberProduction_Objective", "eg_convoyBase_mechanizedCommand5")
EGroup_AddGroup("eg_StopBomberProduction_Objective", "eg_convoyBase_mechanizedCommand6")

-- Create the Plasma generators
for i = 1, 6 do
	Entity_CreateBuildingMarker(g_Player2,"eg_convoyBase_power"..i, "guard_plasma_generator","mkr_convoyBase_power"..i, 1)
end

-- Create the Tactica Control
for i = 1, 1 do
	Entity_CreateBuildingMarker(g_Player2,"eg_convoyBase_tacticaControl"..i, "guard_tactica","mkr_convoyBase_tacticaControl"..i, 1)
end

end

-- Create Buildings for Main Base (also creates the Mars Patterns for the Destroy Mars Pattern Command Objective) function Rule_Create_MainBase_Buildings() -- used to track when the mars pattern command buildings are destroyed for the Destroy Mars Pattern Command Objective EGroup_Create("eg_mainBase_marsPattern_Objective")

-- Create the Field Command HQ (used for objective)
Entity_CreateBuildingMarker(g_Player2,"eg_HQInMainBase_Objective", "guard_hq","mkr_mainBase_HQ1", 1)

-- Create the Infantry Command
	-- also upgrade with quarters (although real unit construction is faked)
for i = 1, 6 do
	Entity_CreateBuildingMarker(g_Player2,"eg_mainBase_infantryCommand"..i, "guard_infantry","mkr_mainBase_infantryCommand"..i, 1)
end

-- Create the Mars Pattern Command
for i = 1, 2 do
	Entity_CreateBuildingMarker(g_Player2,"eg_mainBase_marsPattern"..i, "guard_mars_pattern","mkr_mainBase_marsPattern"..i, 1)
	EGroup_AddGroup("eg_mainBase_marsPattern_Objective", "eg_mainBase_marsPattern"..i)
end

-- Create the Mechanized Command
	-- also visually upgrade with depots
for i = 1, 2 do
	Entity_CreateBuildingMarker(g_Player2,"eg_mainBase_mechanizedCommand"..i, "guard_mechanized","mkr_mainBase_mechanizedCommand"..i, 1)
	EGroup_ForceAddOn("eg_mainBase_mechanizedCommand"..i, "addon_guard_basilisk_depot" )
	EGroup_ForceAddOn("eg_mainBase_mechanizedCommand"..i, "addon_guard_hellhound_depot" )
	EGroup_ForceAddOn("eg_mainBase_mechanizedCommand"..i, "addon_guard_lemanruss_depot" )
end

-- Create the Plasma generators
for i = 1, 6 do
	Entity_CreateBuildingMarker(g_Player2,"eg_mainBase_power"..i, "guard_plasma_generator","mkr_mainBase_power"..i, 1)
end

-- Create the Tactica Control
for i = 1, 2 do
	Entity_CreateBuildingMarker(g_Player2,"eg_mainBase_tacticaControl"..i, "guard_tactica","mkr_mainBase_tacticaControl"..i, 1)
end

end

-- Setup the Strategic Points, Critical Points, & Relics to AI Control -- All EGroups are set in the editor function Rule_Setup_AI_StrategicPoints( ) ------------------------------------------------------------------------------------------------------------------------------------------------- -- Strategic Point Ownership & Upgrades to Listening Posts ------------------------------------------------------------------------------------------------------------------------------------------------- -- Strategic Points by the Main Base -- Upgrade to Tier 2 for i=1, 5 do EGroup_SetPlayerOwner("eg_mainBase_stratPoint"..i, g_Player2) Entity_CreateBuildingPosition(g_Player2, "eg_mainBase_listeningPost"..i, "guard_listening_post", EGroup_GetPosition("eg_mainBase_stratPoint"..i), 1) EGroup_ForceAddOn("eg_mainBase_listeningPost"..i, "addon_guard_list_post_2" ) end

-- Strategic Points by the Convoy Base
	-- Upgrade to Tier 1
for i=1, 6 do
	EGroup_SetPlayerOwner("eg_convoyBase_stratPoint"..i, g_Player2)
	Entity_CreateBuildingPosition(g_Player2, "eg_convoyBase_listeningPost"..i, "guard_listening_post", EGroup_GetPosition("eg_convoyBase_stratPoint"..i), 1)
	EGroup_ForceAddOn("eg_convoyBase_listeningPost"..i, "addon_guard_list_post_1" )
end

-- LP by the Player Base (One that Has Guardsmen attack from it) -- No Weapon Upgrade, just the Listening Post
EGroup_SetPlayerOwner("eg_convoyBase_stratPoint7", g_Player2)
Entity_CreateBuildingPosition(g_Player2, "eg_convoyBase_listeningPost7", "guard_listening_post", EGroup_GetPosition("eg_convoyBase_stratPoint7"), 1)

-------------------------------------------------------------------------------------------------------------------------------------------------
-- Critical Point Ownership
-------------------------------------------------------------------------------------------------------------------------------------------------
EGroup_SetPlayerOwner("eg_centerBase_critPoint2", g_Player2)
EGroup_SetPlayerOwner("eg_centerBase_critPoint4", g_Player2)

-------------------------------------------------------------------------------------------------------------------------------------------------
-- Relic Ownership  & Upgrades to Listening Posts
-------------------------------------------------------------------------------------------------------------------------------------------------
-- Relic by the Main Base (& add LP to upgrade 2)
EGroup_SetPlayerOwner("eg_mainBase_relic1", g_Player2)
Entity_CreateBuildingPosition(g_Player2, "eg_mainBase_listeningPostRelic1", "guard_listening_post", EGroup_GetPosition("eg_mainBase_relic1"), 1)
EGroup_ForceAddOn("eg_mainBase_listeningPostRelic1", "addon_guard_list_post_2" )

-- Relic by the Mega Basilisk (No LP on it so the player can locate it on mini-map)
EGroup_SetPlayerOwner("eg_centerBase_relic1", g_Player2)

end

-- Create and upgrade all the turrets on the map function Rule_Create_Turrets( ) -- Create all the Heavy Bolter Turrets for i = 1, g_number_turret_heavy_bolter do Entity_CreateBuildingMarker(g_Player2,"eg_turret_heavyBolter"..i, "guard_turret_heavy_bolter","mkr_turret_heavyBolter"..i, 1) end

-- Create (& upgrade)  all the Missile Turrets
for i = 1, g_number_turret_missile do
	Entity_CreateBuildingMarker(g_Player2,"eg_turret_missile"..i, "guard_turret_heavy_bolter","mkr_turret_missile"..i, 1)
	EGroup_ForceAddOn("eg_turret_missile"..i, "addon_guard_turret")
end

end


-- END OF ALL " CREATE AI BUILDINGS " RULES


-- CREATE AI INITIAL UNIT RULES -- Rule_Create_All_Ai_Initial_Units() : Create all AI Initial Units : Called from OnInit( ) -- Rule_Create_Defending_Troops() : Create a few squads of troops to protect some of the bases from early attacks -- These Troops never attack the player base -- Rule_Create_HeavyWeaponsTeams() : Create & Entrench all the Original Heavy Weapons Teams -- Rule_Regroup_Entrenched_HeavyWeaponsTeams(): Regroups the Heavy Weapon Teams SGroups since they are lost when a squad entrenchs -- Rule_Garrision_Troops_In_Buildings() : Garrisons Troops in the HQs, Infantry Commands, & Mechanized Commands based on Stronghold Strength -- Rule_Create_All_Ai_Idle_Units : Create all the Idle Vehicles that become active via drivers as the Player nears them -- Rule_Face_All_Ai_Idle_Units() : Makes it so all the Idle Chimeras & Sentinels are Facing the Correct Direction

-- Create all AI Initial Units : Called from OnInit( ) function Rule_Create_All_Ai_Initial_Units() -- Create & Entrench all the Original Heavy Weapons Teams Rule_Create_HeavyWeaponsTeams()

-- Garrisons Troops in the HQs, Infantry Commands, & Mechanized Commands  based on Stronghold Strength
Rule_Garrision_Troops_In_Buildings()

-- Create all the Idle Vehicles that become active via drivers as the Player nears them
Rule_Create_All_Ai_Idle_Units()

-- Makes it so all the Idle  Chimeras & Sentinels are Facing the Correct Direction
Rule_Face_All_Ai_Idle_Units()

end

-- Create a few squads of troops to protect some of the bases from early attacks -- These Troops never attack the player base function Rule_Create_Defending_Troops() -- Temp Enable Grenade Launchers so the defending troops have them g_grenadeLauncher_enabled = true

-- Produce Some Defending Guardsmen for CenterNorth Base
Rule_Produce_Guardsmen_Full("sg_centerNorthBase_defender1", "eg_HQInMainBase_Objective", "mkr_centerNorthBase_underAttack")
Rule_Produce_Guardsmen_Full("sg_centerNorthBase_defender2", "eg_HQInMainBase_Objective", "mkr_centerNorthBase_underAttack")
Rule_Produce_Sentinel("sg_centerNorthBase_defender3", "eg_HQInMainBase_Objective", "mkr_centerNorthBase_underAttack")

-- Produce Some Defending Guardsmen for CenterSouth Base
Rule_Produce_Guardsmen_Full("sg_centerSouthBase_defender1", "eg_HQInMainBase_Objective", "mkr_centerSouthBase_underAttack")
Rule_Produce_Guardsmen_Full("sg_centerSouthBase_defender2", "eg_HQInMainBase_Objective", "mkr_centerSouthBase_underAttack")

-- Produce Some defending Kaskrin, Guardsmen, & Sentinels for the Big Gun
Rule_Produce_Kasrkin_Full("sg_centerSouthBase_defender3", "eg_HQInMainBase_Objective", "mkr_bigGun_underAttack")
Rule_Produce_Guardsmen_Full("sg_centerSouthBase_defender4", "eg_HQInMainBase_Objective", "mkr_bigGun_underAttack")
Rule_Produce_Sentinel("sg_centerSouthBase_defender5", "eg_HQInMainBase_Objective", "mkr_bigGun_underAttack")
Rule_Produce_Sentinel("sg_centerSouthBase_defender6", "eg_HQInMainBase_Objective", "mkr_bigGun_underAttack")

-- Produce Some Defending Troops & Vehicles for Main Base
Rule_Produce_Kasrkin_Full("sg_mainBase_defender1", "eg_HQInMainBase_Objective", "mkr_mainBase_underAttack")
Rule_Produce_Guardsmen_Full("sg_mainBase_defender2", "eg_HQInMainBase_Objective", "mkr_mainBase_underAttack")
Rule_Produce_Basilisk("sg_mainBase_defender3", "eg_HQInMainBase_Objective", "mkr_mainBase_underAttack")
Rule_Produce_Basilisk("sg_mainBase_defender4", "eg_HQInMainBase_Objective", "mkr_mainBase_underAttack")
Rule_Produce_Marauder("sg_mainBase_defender5", "eg_HQInMainBase_Objective", "mkr_mainBase_underAttack")
Rule_Produce_Marauder("sg_mainBase_defender6", "eg_HQInMainBase_Objective", "mkr_mainBase_underAttack")

-- Produce Some Defending Guardsmen, Bombers & Sentinels for North Base
Rule_Produce_Guardsmen_Full("sg_northBase_defender1", "eg_HQInMainBase_Objective", "mkr_northBase_underAttack")
Rule_Produce_Guardsmen_Full("sg_northBase_defender2", "eg_HQInMainBase_Objective", "mkr_northBase_underAttack")
Rule_Produce_Marauder("sg_northBase_defender3", "eg_HQInMainBase_Objective", "mkr_northBase_underAttack")
Rule_Produce_Marauder("sg_northBase_defender4", "eg_HQInMainBase_Objective", "mkr_northBase_underAttack")
Rule_Produce_Sentinel("sg_northBase_defender5", "eg_HQInMainBase_Objective", "mkr_northBase_underAttack")
Rule_Produce_Sentinel("sg_northBase_defender6", "eg_HQInMainBase_Objective", "mkr_northBase_underAttack")

-- Produce Some Idle Builders (Adds Life to the Base)
Rule_Produce_Enginseer("sg_centerNorthBase_builder1", "eg_HQInMainBase_Objective", "mkr_centerNorthBase_underAttack")
Rule_Produce_Enginseer("sg_centerSouthBase_builder1", "eg_HQInMainBase_Objective", "mkr_centerSouthBase_underAttack")
Rule_Produce_Enginseer("sg_mainBase_builder1", "eg_HQInMainBase_Objective", "mkr_mainBase_underAttack")
Rule_Produce_Enginseer("sg_mainBase_builder2", "eg_HQInMainBase_Objective", "mkr_mainBase_underAttack")
Rule_Produce_Enginseer("sg_northBase_builder1", "eg_HQInMainBase_Objective", "mkr_northBase_underAttack")

-- Set Back to Not Enabled : Renables via alert levels
g_grenadeLauncher_enabled	=	false

end

-- Create & Entrench all the Original Heavy Weapons Teams function Rule_Create_HeavyWeaponsTeams() -- Create the Anti Infantry Heavy Weapons Teams & Entrench them for i = 1, g_number_heavyWeapons_AntiInfantry do Util_CreateSquadsAtMarker(g_Player2, "sg_heavyWeapons_AntiInfantry_"..i, "guard_heavy_weapons_team_squad", "mkr_heavyWeapons_AntiInfantry_"..i, 1) Cmd_SquadEntrench("sg_heavyWeapons_AntiInfantry_"..i) end

-- Create the Anti Vehicle Heavy Weapons Teams & Entrench them
for i = 1, g_number_heavyWeapons_AntiVehicle do
	Util_CreateSquadsAtMarker(g_Player2, "sg_heavyWeapons_AntiVehicle_"..i, "guard_heavy_weapons_team_squad", "mkr_heavyWeapons_AntiVehicle_"..i, 1)
	Cmd_SquadEntrench("sg_heavyWeapons_AntiVehicle_"..i)
end

-- Call the Rule to Regroup the "Heavy Weapon Teams SGroups" since they are lost when a squad entrenchs 
Rule_AddOneShot(Rule_Regroup_Entrenched_HeavyWeaponsTeams, 10)

end

--Regroups the Heavy Weapon Teams SGroups since they are lost when a squad entrenchs function Rule_Regroup_Entrenched_HeavyWeaponsTeams() -- Reget the SGroup and order it to standground for i = 1, g_number_heavyWeapons_AntiInfantry do Player_GetAllSquadsNearMarker(g_Player2, "sg_heavyWeapons_Entrenched_AntiInfantry_"..i, "mkr_heavyWeapons_AntiInfantry_"..i) Cmd_SetStance("sg_heavyWeapons_Entrenched_AntiInfantry_"..i, STANCE_StandGround) end

-- Reget the SGroup and order it to standground
for i = 1, g_number_heavyWeapons_AntiVehicle do
	Player_GetAllSquadsNearMarker(g_Player2, "sg_heavyWeapons_Entrenched_AntiVehicle_"..i, "mkr_heavyWeapons_AntiVehicle_"..i)
	Cmd_SetStance("sg_heavyWeapons_Entrenched_AntiVehicle_"..i, STANCE_StandGround)
end

end

-- Garrisons Troops in the HQs, Infantry Commands, & Mechanized Commands based on Stronghold Strength function Rule_Garrision_Troops_In_Buildings() -- Garrision One Squad in each building for each difficulty tier for i=1, g_strongholdStrengthTier do -- Center Base: HQ for j=1,2 do Util_CreateSquadsAtMarker(g_Player2, "sg_garrisoned_centerBase_HQ"..j..""..i, "guard_squad_guardsmen", "mkr_centerBase_HQ"..j, 1) Cmd_EnterBuilding("sg_garrisoned_centerBase_HQ"..j..""..i, "eg_centerBase_HQ"..j) end

	--Center Base: Infantry Command
	for j=1,4 do
		Util_CreateSquadsAtMarker(g_Player2, "sg_garrisoned_centerBase_infantryCommand"..j.."_"..i, "guard_squad_guardsmen", "mkr_centerBase_infantryCommand"..j, 1)
		Cmd_EnterBuilding("sg_garrisoned_centerBase_infantryCommand"..j.."_"..i, "eg_centerBase_infantryCommand"..j)
	end
	
	-- Center Base: Mechanized Command
	for j=1,2 do
		Util_CreateSquadsAtMarker(g_Player2, "sg_garrisoned_centerBase_mechanizedCommand"..j.."_"..i, "guard_squad_guardsmen", "mkr_centerBase_mechanizedCommand"..j, 1)
		Cmd_EnterBuilding("sg_garrisoned_centerBase_mechanizedCommand"..j.."_"..i, "eg_centerBase_mechanizedCommand"..j)
	end

	-- Convoy Base: HQ
	for j=1,2 do
		Util_CreateSquadsAtMarker(g_Player2, "sg_garrisoned_convoyBase_HQ"..j.."_"..i, "guard_squad_guardsmen", "mkr_convoyBase_HQ"..j, 1)
		Cmd_EnterBuilding("sg_garrisoned_convoyBase_HQ"..j.."_"..i, "eg_convoyBase_HQ"..j)
	end
	
	--Convoy Base: Infantry Command
	for j=2,8 do
		Util_CreateSquadsAtMarker(g_Player2, "sg_garrisoned_convoyBase_infantryCommand"..j.."_"..i, "guard_squad_guardsmen", "mkr_convoyBase_infantryCommand"..j, 1)
		Cmd_EnterBuilding("sg_garrisoned_convoyBase_infantryCommand"..j.."_"..i, "eg_convoyBase_infantryCommand"..j)
	end
	
	-- Convoy Base: Mechanized Command
	for j=1,8 do
		Util_CreateSquadsAtMarker(g_Player2, "sg_garrisoned_convoyBase_mechanizedCommand"..j.."_"..i, "guard_squad_guardsmen", "mkr_convoyBase_mechanizedCommand"..j, 1)
		Cmd_EnterBuilding("sg_garrisoned_convoyBase_mechanizedCommand"..j.."_"..i, "eg_convoyBase_mechanizedCommand"..j)
	end

	-- Main Base: HQ
	Util_CreateSquadsAtMarker(g_Player2, "sg_garrisoned_HQinMainBase_"..i, "guard_squad_guardsmen", "mkr_mainBase_HQ1", 1)
	Cmd_EnterBuilding("sg_garrisoned_HQinMainBase_"..i, "eg_HQInMainBase_Objective")
	
	--Main Base: Infantry Command
	for j=1,6 do
		Util_CreateSquadsAtMarker(g_Player2, "sg_garrisoned_mainBase_infantryCommand"..j.."_"..i, "guard_squad_guardsmen", "mkr_mainBase_infantryCommand"..j, 1)
		Cmd_EnterBuilding("sg_garrisoned_mainBase_infantryCommand"..j.."_"..i, "eg_mainBase_infantryCommand"..j)
	end
	
	-- Main Base: Mechanized Command
	for j=1,2 do
		Util_CreateSquadsAtMarker(g_Player2, "sg_garrisoned_mainBase_mechanizedCommand"..j.."_"..i, "guard_squad_guardsmen", "mkr_mainBase_mechanizedCommand"..j, 1)
		Cmd_EnterBuilding("sg_garrisoned_mainBase_mechanizedCommand"..j.."_"..i, "eg_mainBase_mechanizedCommand"..j)
	end
end

end

-- Create all the Idle Vehicles that become active via drivers as the Player nears them function Rule_Create_All_Ai_Idle_Units() -- Create all the "idle" baneblades in the Main Base -- for i=1,g_number_idle_baneBlade do -- -- Create the SGroup for the Drivers -- SGroup_Create("sg_baneBladeActivator"..i)

-- -- Create the BaneBlade & make so it doesn't attack the player (although can still be attacked) -- Util_CreateSquadsAtMarker(g_Player2, "sg_idle_baneBlade_"..i, "guard_squad_baneblade_nerfed_sp_dxp3", "mkr_idle_baneBlade_"..i, 1) -- Cmd_SetStance("sg_idle_baneBlade_"..i, STANCE_CeaseFire) -- end

-- Create all the "idle" Leman Russ Tanks in the Main Base 
for i=1,g_number_idle_mainBase_lemanRussTank do
	-- Create the SGroup for the Drivers
	SGroup_Create("sg_mainBase_lemanRussTankActivator"..i)

	-- Create the Leman Russ Tank & make so it doesn't attack the player (although can still be attacked)
	Util_CreateSquadsAtMarker(g_Player2, "sg_idle_mainBase_lemanRussTank_"..i, "guard_squad_lemanruss", "mkr_idle_mainBase_lemanRussTank_"..i, 1)
	Cmd_SetStance("sg_idle_mainBase_lemanRussTank_"..i, STANCE_CeaseFire)
	
	-- Play the Shutdown Animation:
	Anim_PlaySGroupAnim("sg_idle_mainBase_lemanRussTank_"..i, "sp_shutdown" )
end

-- Create all the "idle" Valkyries in the North Base 
for i=1,g_number_idle_valkyrie do
	-- Create the valkyrie & make so it doesn't attack the player (although can still be attacked)
	Util_CreateSquadsAtMarker(g_Player2, "sg_idle_valkyrie_"..i, "npc_valkyrie", "mkr_idle_valkyrie_"..i, 1)
	Cmd_SetStance("sg_idle_valkyrie_"..i, STANCE_CeaseFire)
	
	-- Face the Valkyrie in the correct direction
	SGroup_FaceMarker("sg_idle_valkyrie_"..i, "mkr_facing_valkyrie_"..i)
	
	-- Play the Shutdown Animation:
	Anim_PlaySGroupAnim( "sg_idle_valkyrie_"..i, "sp_shutdown" )
end

-- Create all the "idle" Chimeras by Convoy Base (SpawnLocation 1)
for i=1,g_number_idle_chimera do
	-- Create the SGroup for the Drivers
	SGroup_Create("sg_chimeraActivator"..i)

	-- Create the Chimera & make so it doesn't attack the player (although can still be attacked)
	Util_CreateSquadsAtMarker(g_Player2, "sg_idle_chimera_"..i, "guard_squad_chimera", "mkr_idle_chimera_"..i, 1)
	Cmd_SetStance("sg_idle_chimera_"..i, STANCE_CeaseFire)
	
	-- Play the Shutdown Animation:
	Anim_PlaySGroupAnim("sg_idle_chimera_"..i, "sp_shutdown" )		
end

-- Create all the "idle" Leman Russ Tanks by Convoy Base (SpawnLocation 4) 
for i=1,g_number_idle_lemanRussTank do
	-- Create the SGroup for the Drivers
	SGroup_Create("sg_lemanRussTankActivator"..i)

	-- Create the Leman Russ Tank & make so it doesn't attack the player (although can still be attacked)
	Util_CreateSquadsAtMarker(g_Player2, "sg_idle_lemanRussTank_"..i, "guard_squad_lemanruss", "mkr_idle_lemanRussTank_"..i, 1)
	Cmd_SetStance("sg_idle_lemanRussTank_"..i, STANCE_CeaseFire)
	
	-- Face the Tank in the correct direction
	if i <= 5
	then
		SGroup_FaceMarker("sg_idle_lemanRussTank_"..i, "mkr_idle_lemanRussTank_"..i+5)
	end
	
	-- Play the Shutdown Animation:
	Anim_PlaySGroupAnim("sg_idle_lemanRussTank_"..i, "sp_shutdown" )		
end

-- Create all the "idle" sentinels by Convoy Base (SpawnLocation 2&3 ) 
for i=1,g_number_idle_sentinel do
	-- Create the SGroup for the Drivers
	SGroup_Create("sg_sentinelActivator"..i)
	
	-- Create the Sentinel & make so it doesn't attack the player (although can still be attacked)
	Util_CreateSquadsAtMarker(g_Player2, "sg_idle_sentinel_"..i, "guard_squad_sentinel", "mkr_idle_sentinel_"..i, 1)
	Cmd_SetStance("sg_idle_sentinel_"..i, STANCE_CeaseFire)
	
	-- Play the Shutdown Animation:
	Anim_PlaySGroupAnim( "sg_idle_sentinel_"..i, "sp_shutdown" )
end

end

-- Makes it so all the Idle Chimeras & Sentinels are Facing the Correct Direction function Rule_Face_All_Ai_Idle_Units() local j = 0

-- Face the "idle" chimeras by Convoy Base (SpawnLocation 1)
for i=1,6 do
	j = j+1
	SGroup_FaceMarker("sg_idle_chimera_"..i, "mkr_facing_chimera_"..j)
	
	--reset the facing counter for the front row
	if i == 3
	then
		j = 0
	end
end

-- face the "idle" sentinels by Convoy Base (SpawnLocation 2&3 )
for i=1,8 do
	j = i+8
	SGroup_FaceMarker("sg_idle_sentinel_"..i,  "mkr_idle_sentinel_"..j)
end
for i=9,16 do
	j = i-8
	SGroup_FaceMarker("sg_idle_sentinel_"..i,  "mkr_idle_sentinel_"..j)
end

end

-- END OF ALL " CREATE AI INITIAL UNIT " RULES


-- GAME START -- Rule_GameStart( ) : Starts the actual mission : Called from OnInit -- Rule_UI_Game_Timer() : Initially sets up the timer that shows the total elapsed time of the mission -- Rule_UI_Game_Timer_Tick() : Updates & Shows the game timer every second -- Initial_IE_Event() : Play the First IE of the Stronghold : Called for GameStart() after a delay

-- Starts the actual mission : Called from OnInit function Rule_GameStart() if not Event_IsAnyRunning() then -- Silvey Polish 10/10/07: Dave, I moved the music setup after the opening NIS so I have a little more room to breathe. -- Function Used to Setup the Sound and Music : Function Is Defined Below Rule_SetupMusicPlaylist()

	-- Function used to create all the Player Initial Buildings on the Map
	Rule_Create_All_Player_Initial_Buildings( )
	
	-- Function used to create all the Player Initial Units on the Map (including Honor Guard)
	Rule_Create_All_Player_Initial_Units( )
	
	-- Create a few squads of troops to protect some of the bases from early attacks (so don't show up in intro IE)
	Rule_Create_Defending_Troops()
	
	-- Rule_Objective_Define(): Sets up the Objective Lua Tables, but doesn't actually assign them
	Rule_Objective_Define()
	
	-- Show and Control the Game Timer
	Rule_UI_Game_Timer()
	
	-- Show the Alert Level
	UI_ShowCountDXP("AlertLevel_Ui", g_Player1, 3950195, g_currentAlertStatus )
	
	-- Make Sure all base attacks are synced up
	Rule_AddOneShot(Rule_Create_And_Sync_Attacks, 0)
	
	-- Assign the First two Objectives & Play Initial IE
	Rule_AddInterval(Rule_DestroyImperialGuardHQ_Objective, 1)		
	
	-- Spawn in the First Convoy after a delay of g_timeUntilFirstConvoy
	Rule_AddOneShot(Rule_Spawn_First_Convoy, g_timeUntilFirstConvoy)
	
	-- Handles the IE, Assigning the Objectives, & Spawning the first spotters (MOVED TO ALERT LEVEL TWO)		 
	--Rule_AddOneShot(Rule_Activate_Basilisk_And_Spotters, g_timeUntilBasilisk)
	
	--Checks for the Idle Units Deaths
	Rule_Add(Rule_IdleUnits_Die)
	
	-- Handles activating the idle sentinels by the convoy base
	Rule_AddInterval(Rule_Create_Troops_To_Activate_Sentinels, 30)
	Rule_AddInterval(Rule_Activate_Sentinels, 1)
	
	-- Handles activating the idle chimeras by the convoy base
	Rule_AddInterval(Rule_Create_Troops_To_Activate_Chimeras, 30)
	Rule_AddInterval(Rule_Activate_Chimeras, 1)
	
	-- handles activating the idle Leman Russ Tanks by the convoy base
	Rule_AddInterval(Rule_Create_Troops_To_Activate_LemanRussTanks, 45)
	Rule_AddInterval(Rule_Activate_LemanRussTanks, 1)
	
	-- Allow the west base to begin producing units & attacking
	Rule_AddOneShot(Rule_Activate_West_Base, g_time_before_westBase_activates)
	Rule_AddOneShot(Rule_Activate_West_Base_Patrols, g_time_before_westBase_patrol_activates)
	
	-- Increase Alert Level if not already there
	Rule_AddOneShot(Rule_Delayed_Upgrade_To_Alert_One, g_time_until_alertOne)
	Rule_AddOneShot(Rule_Delayed_Upgrade_To_Alert_Two, g_time_until_alertTwo)
	Rule_AddOneShot(Rule_Delayed_Upgrade_To_Alert_Three, g_time_until_alertThree)
	Rule_AddOneShot(Rule_Delayed_Upgrade_To_Alert_Four, g_time_until_alertFour)
	Rule_AddOneShot(Rule_Delayed_Upgrade_To_Alert_Five, g_time_until_alertFive)
	
	-- Check if the Player has attacked an enemy Base before they go activate via Alert Levels
	Rule_AddInterval(Rule_Check_EarlyPlayer_Attack_CenterNorth_Base,5)
	Rule_AddInterval(Rule_Check_EarlyPlayer_Attack_CenterSouth_Base,5)
	Rule_AddInterval(Rule_Check_EarlyPlayer_Attack_Main_Base,5)
	Rule_AddInterval(Rule_Check_EarlyPlayer_Attack_North_Base, 5)
	
	-- Check for Valkrie Drops
	Rule_AddInterval(Rule_Valkrie_Two_CheckDrop, 10)
	Rule_AddInterval(Rule_Valkrie_Three_CheckDrop, 10)
	
	-- Check if Enough Bases are destroyed to activate Main Base
	Rule_AddInterval(Rule_Check_EarlyActivation_MainBase, 10)
	
	-- Set up the check for VICTORY : Function is Defined Below
	Rule_AddInterval(Rule_EndGame_Victory, 1)
	
	-- Set up the check for DEFEAT : Function is Defined Below
	Rule_AddInterval(Rule_EndGame_Defeat, 1)
	
	-- Handles the restoring of save games (so annimations correctly play)
	Rule_AddInterval(Rule_RestoreSupport, 3)
	
	-- Remove this rule so that it never runs again 
	Rule_Remove(Rule_GameStart) 
end

end

-- Initially sets up the timer that shows the total elapsed time of the mission function Rule_UI_Game_Timer() g_UI_gameTimer = 0 WinWarning_Add( "ui_gameTime", World_GetPlayerAt(0), "", "", "" ) Rule_AddInterval(Rule_UI_Game_Timer_Tick, 1) end

-- Updates & Shows the game timer every second function Rule_UI_Game_Timer_Tick() g_UI_gameTimer = g_UI_gameTimer+1 WinWarning_SetText( "ui_gameTime", Loc_FormatText1( 60445, Loc_FormatTime( 60409, g_UI_gameTimer ) ) ) end

-- Play the First IE of the Stronghold : Called for GameStart() after a delay -- Also controls the Initial Attack function Initial_IE_Event() -- Play Initial IE shortly after game start Util_StartIntel(EVENTS.IE_Initial)

-- Produce an Initial Attack
for i=1, g_strongholdStrengthTier do
	Rule_Produce_Guardsmen_Full("sg_initialAttack_troops"..i, "eg_convoyBase_listeningPost7", "mkr_initialLP_troops")
	Cmd_AttackMovePos("sg_initialAttack_troops"..i, Marker_GetPosition(Marker_FromName("mkr_player_mainBase_HQ", "basic_marker")))
	
	Rule_Produce_Guardsmen_Full("sg_initialAttack_troops2_"..i, "eg_convoyBase_listeningPost7", "mkr_initialLP_troops")
	Cmd_AttackMovePos("sg_initialAttack_troops2_"..i, Marker_GetPosition(Marker_FromName("mkr_player_mainBase_HQ", "basic_marker")))
	
	if i > 1
	then
		Rule_Produce_Sentinel("sg_initialAttack_sentinel"..i, "eg_convoyBase_listeningPost7", "mkr_initialLP_troops")
		Cmd_AttackMovePos("sg_initialAttack_sentinel"..i, Marker_GetPosition(Marker_FromName("mkr_player_mainBase_HQ", "basic_marker")))
	end
end

end

-- END OF ALL "GAME START" RULES


-- OBJECTIVES -- INTIAL DEFINE: -- Rule_Objective_Define(): Sets up the actual Objective Lua Tables : Called from OnInit() -- Doesn't actually assign the objectives -- Just sets up the tables for them

-- ASSIGNING AND CHECKING:
	-- Primary Objectives:
		-- Rule_DestroyImperialGuardHQ_Objective : Assigns & Checks for Primary Objective: (Destroy the Imperial Guard HQ)
		-- Rule_StopBaneBladeProduction_Objective() : Assigns & Checks for Primary Ojective : (Stop Baneblade Production)
			-- Rule_DestroyMarsPatternCommand_Objective() : Assigns & Check for Sub-Primary Objective : (Destroy Mars Pattern Command Buildings)
			-- Rule_StopConvoysFromReachingBase_Objective : Assigns & Check for Sub-Primary Objective : (Stop Convoys From Reaching Base)
	-- Secondary Objectives:
		-- Rule_StopMegaBasiliskAttacks_Objective() : Assigns & Checks for Secondary Objective : (Stop MegaBasilisk Attacks)
			-- Rule_DestroyMegaBasilisk_Objective() : Assigns & Checks for Sub-Secondary Objective : (Destroy Mega Basilisk)
			-- Rule_StopSpotterProduction_Objective() : Assigns & Check for Sub-Secondary Objective : (Stop Spotter Production)
			-- Rule_KillSpotters_Objective() : Assigns Sub-Secondary Objective : (Kill Spotters)
				-- Objective Can't Directly Be Completed -- Is Just Extra Reminder Text, & AutoCompletes when the Secondary Objective: StopMegaBasiliskAttacks Completes
		-- Rule_StopBomberProduction_Objective() : Assigns & Checks for Secondary Objective: (Destroy the Marauder Producing Mech Commands)
	-- Intel Event Delays:
		-- Rule_Setup_AirBase_UnderAttack_IE() : Called after a delay when objective is assigned, so can track if player attacks the Air Base once it goes active
		-- Rule_Setup_BigGun_UnderAttack_IE() : Called after a delay when objective is assigned, so can track if player attacks the MegaBasilisk once it goes active

-- Sets up the actual Objective Lua Tables : Called from OnInit() function Rule_Objective_Define() -- Primary Objective : Assigned at Intro (Completed once Main Base HQ is Destroyed) Objective_DestroyImperialGuardHQ = { title_id = 3950175, short_desc_id = 3950176, help_tip_id = 3950175}

-- Primary Objective: Assigned at Intro (Completed once Mars Patterns are Destroyed or all mech commands)
Objective_StopBaneBladeProduction = { title_id = 3950177, short_desc_id = 3950178, help_tip_id = 3950177 }

-- Sub-Primary Ojective : Assigned when first convoy reaches main base (Completed once Mars Patterns are Destroyed)
Objective_DestroyMarsPatternCommand = { title_id = 3950179, short_desc_id = 3950180, help_tip_id = 3950179 }

-- Sub-Primary Objective: Assigned when 1st convoy arrives (Completed once all Convoy Mechanized Commands are Destroyed)
Objective_StopConvoysFromReachingBase = { title_id = 3950181, short_desc_id = 3950182, help_tip_id = 3950181 }

-- Secondary Objective: Assigned when Mega Basilisk goes active (Completed once Mega Basilisk or spotter hqs are destroyed)
Objective_StopMegaBasiliskAttacks = { title_id = 3950183, short_desc_id = 3950184, help_tip_id = 3950183 }

-- Sub-Secondary Objective: Assigned when Mega Basilisk goes active (Completed once Mega Basilisk is destroyed)
Objective_DestroyMegaBasilisk = { title_id = 3950185, short_desc_id = 3950186, help_tip_id = 3950185 }

-- Sub-Secondary Objective: Assigned when Mega Basilisk goes active (Completed once Spotter HQs are both destroyed)
Objective_StopSpotterProduction = { title_id = 3950189, short_desc_id = 3950190, help_tip_id = 3950189 }

-- Sub-Secondary Objective: Assigned when Mega Basilisk goes active (Completed once Main Secondary Objective is completed)
Objective_KillSpotters = { title_id = 3950187, short_desc_id = 3950188, help_tip_id = 3950187 }

-- Secondary Objective: Assigned when Bombers go active (Completed once Mech Commands are both destroyed)
Objective_StopBomberProduction = { title_id = 3950191, short_desc_id = 3950192, help_tip_id = 3950191 }

end

-- Assigns & Checks for Primary Objective: (Destroy the Imperial Guard HQ) function Rule_DestroyImperialGuardHQ_Objective() -- First check if Objective exists and add if not... if Event_IsAnyRunning() == false and Objective_Exists(Objective_DestroyImperialGuardHQ.title_id) == false then -- Create ( & Assign) the objective as a primary one Util_ObjectiveCreate(Objective_DestroyImperialGuardHQ, true) g_PrimaryObjectives = g_PrimaryObjectives + 1

	-- Setup Ping On Objective Screen
	Objective_PingMarker(Objective_DestroyImperialGuardHQ.title_id, "mkr_mainBase_HQ1", true, attack)
	
	-- Set up a one time ping on the ingame screen
	Ping_Marker("mkr_mainBase_HQ1", false, "default")
	
	-- Reveal the Fog of War Around the HQ Briefly
	FOW_RevealMarker("mkr_mainBase_HQ1", 20)
	
	-- Assign Other Initial Objective
	Rule_AddInterval(Rule_StopBaneBladeProduction_Objective, 1)		

-- Else Check if the Imperial Guard HQ in the Main Stronghold is killed
elseif Event_IsAnyRunning() == false and
	EGroup_Count( EGroup_FromName("eg_HQInMainBase_Objective")) == 0
then	
	-- Complete the Objective and Remove the Rule
	Util_ObjectiveComplete(Objective_DestroyImperialGuardHQ.title_id)
	Rule_Remove( Rule_DestroyImperialGuardHQ_Objective )
end

end

-- Assigns & Checks for Primary Ojective : (Stop Baneblade Production) function Rule_StopBaneBladeProduction_Objective() -- First check if Objective exists and add if not... if Event_IsAnyRunning() == false and Objective_Exists(Objective_StopBaneBladeProduction.title_id) == false then -- Create (Assign) the objective as a primary one (& show objective screen) Util_ObjectiveCreate(Objective_StopBaneBladeProduction, true)

	-- Update & Set the Primary Objective To this one when objective screen shows
	g_PrimaryObjectives = g_PrimaryObjectives + 1
	Objective_SetDefaultPrimary(g_PrimaryObjectives)
	Objective_ShowScreen()
	
	-- Fire off the Initial IE Event with 5 Second Delay
	Rule_AddOneShot(Initial_IE_Event, 5)

-- Complete Objective if you completed the Destroy All Mechanized Commands Sub-Objective
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBaneBladeProduction.title_id) == true and
	Objective_Exists(Objective_StopConvoysFromReachingBase.title_id) == true and
	Objective_GetState(Objective_StopConvoysFromReachingBase.title_id) == OS_Complete
then
	-- Play IE: Baneblade production stopped
	Util_StartIntel(EVENTS.IE_BanebladesHalted)
	
	-- Hide the UI Counters in case they are visible:
	UI_HideCount("Convoy_Timer_Ui")
	UI_HideCount("Baneblade_Counter_Ui")
	
	-- Complete the Objective and Remove the Rule
	Util_ObjectiveComplete( Objective_StopBaneBladeProduction.title_id )
	Rule_Remove( Rule_StopBaneBladeProduction_Objective )

-- Complete Objective if you completed the Destroy Mars Pattern Sub-Objective 
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBaneBladeProduction.title_id) == true and
	Objective_Exists(Objective_DestroyMarsPatternCommand.title_id) == true and
	Objective_GetState(Objective_DestroyMarsPatternCommand.title_id) == OS_Complete
then
	-- Play IE: Baneblade production stopped
	Util_StartIntel(EVENTS.IE_BanebladesHalted)
	
	-- Hide the UI Counters in case they are visible:
	UI_HideCount("Convoy_Timer_Ui")
	UI_HideCount("Baneblade_Counter_Ui")
	
	-- Complete the Objective and Remove the Rule
	Util_ObjectiveComplete( Objective_StopBaneBladeProduction.title_id )
	Rule_Remove( Rule_StopBaneBladeProduction_Objective )
end

end

-- Assigns & Check for Sub-Primary Objective : (Destroy Mars Pattern Command Buildings) function Rule_DestroyMarsPatternCommand_Objective() -- Confirm the Primary Objective Exists and then check if the Sub-Objective exists and add sub if not... if Event_IsAnyRunning() == false and Objective_Exists(Objective_StopBaneBladeProduction.title_id) == true and Objective_Exists(Objective_DestroyMarsPatternCommand.title_id) == false and Objective_GetState(Objective_StopBaneBladeProduction.title_id) ~= OS_Complete then -- Create (Assign) the objective as a sub-primary one (& show objective screen) Objective_SubAdd(Objective_DestroyMarsPatternCommand, Objective_StopBaneBladeProduction.title_id)

	-- Update & Set the Primary Objective To this one when objective screen shows
	g_PrimaryObjectives = g_PrimaryObjectives + 1
	Objective_SetDefaultPrimary(g_PrimaryObjectives)
	
	--Associate a Ping with the Objective on the Objective Screen
	g_marsPatternOnePing_Objective = Objective_PingMarker(Objective_DestroyMarsPatternCommand.title_id, "mkr_mainBase_marsPattern1", true, attack)
	g_marsPatternTwoPing_Objective = Objective_PingMarker(Objective_DestroyMarsPatternCommand.title_id, "mkr_mainBase_marsPattern2", true, attack)
	
	-- Set up a one-time ping on the ingame screen
	Ping_Marker("mkr_mainBase_marsPattern1", false, "default")
	Ping_Marker("mkr_mainBase_marsPattern2", false, "default")
	
	-- Reveal the Fog of War Around the Mars Pattern Buildings Briefly
	FOW_RevealMarker("mkr_mainBase_marsPattern1", 10)
	FOW_RevealMarker("mkr_mainBase_marsPattern2", 10)
	
	-- Assign the other SubObjective regarding the convoys (also shows objective screen)
	Rule_AddInterval(Rule_StopConvoysFromReachingBase_Objective, 1)

-- if the objective exists and both of the Mars Pattern Buildings are destroyed
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBaneBladeProduction.title_id) == true and
	Objective_Exists(Objective_DestroyMarsPatternCommand.title_id) == true and	
	EGroup_Count( EGroup_FromName("eg_mainBase_marsPattern_Objective")) == 0
then
	-- Play IE: Mars Patterns all destroyed
	Util_StartIntel(EVENTS.IE_MarsPatterns_AllDestroyed)
	
	-- Complete the Objective and Remove the Rule
	Util_ObjectiveComplete(Objective_DestroyMarsPatternCommand.title_id)
	Rule_Remove(Rule_DestroyMarsPatternCommand_Objective)

-- if the objective exists and Mars Pattern One Building is destroyed
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBaneBladeProduction.title_id) == true and
	Objective_Exists(Objective_DestroyMarsPatternCommand.title_id) == true and	
	EGroup_Count( EGroup_FromName("eg_mainBase_marsPattern1")) == 0
then
	-- Remove the Objective Screen Ping Associated with Mars Pattern Command building One
	Objective_PingRemove(Objective_DestroyMarsPatternCommand.title_id, g_marsPatternOnePing_Objective)

-- if the objective exists and and Mars Pattern Two Building is destroyed
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBaneBladeProduction.title_id) == true and
	Objective_Exists(Objective_DestroyMarsPatternCommand.title_id) == true and	
	EGroup_Count( EGroup_FromName("eg_mainBase_marsPattern2")) == 0
then
	-- Remove the Objective Screen Ping Associated with Mars Pattern Command building Two
	Objective_PingRemove(Objective_DestroyMarsPatternCommand.title_id, g_marsPatternTwoPing_Objective)
end

end

-- Assigns & Check for Sub-Primary Objective : (Stop Convoys From Reaching Base) function Rule_StopConvoysFromReachingBase_Objective( ) -- Confirm the Primary Objective Exists and then check if the Sub-Objective exists and add sub if not... if Event_IsAnyRunning() == false and Objective_Exists(Objective_StopBaneBladeProduction.title_id) == true and Objective_GetState(Objective_StopBaneBladeProduction.title_id) ~= OS_Complete and Objective_Exists(Objective_StopConvoysFromReachingBase.title_id) == false then -- Create (Assign) the objective as a sub-primary one (& show screen) Objective_SubAdd(Objective_StopConvoysFromReachingBase, Objective_StopBaneBladeProduction.title_id)

	--Associate a Ping with the Objective on the Objective Screen (Pings the location where the next convoy will spawn in)
	Rule_AddInterval(Rule_Ping_Convoy_Spawn,1)
	
	-- Handles the First Location so something appears where the screen opens
	g_convoySpawnPings_Objective_Table[1] = Objective_PingMarker(Objective_StopConvoysFromReachingBase.title_id, "mkr_convoy_spawnLocation1", true, attack)
	
	-- Fog of War and Individual InGame Pings will be handled when each convoy spawns in
	--for i=1, g_convoy_locationsToUse do
	--	g_convoySpawnPings_Objective_Table[i] = Objective_PingMarker(Objective_StopConvoysFromReachingBase.title_id, "mkr_convoy_spawnLocation"..i, true, attack)
	--end
	
	-- Update & Set the Primary Objective to this one & show the objective screen
	g_PrimaryObjectives = g_PrimaryObjectives + 1
	Objective_SetDefaultPrimary(g_PrimaryObjectives)	
	Objective_ShowScreen()

-- if the objective exists and all the convoy mechanized commands have been destroyed
elseif	Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBaneBladeProduction.title_id) == true and	
	Objective_Exists(Objective_StopConvoysFromReachingBase.title_id) == true and
	g_convoy_canSpawnNewOne == false
then
	-- Play IE: Mech Commands all destroyed
	Util_StartIntel(EVENTS.IE_MechCommand_AllDestroyed)
	
	--Remove the Rule that handles the pings of the next convoy location to spawn into
	Rule_Remove(Rule_Ping_Convoy_Spawn)
	
	--Make sure all the pings are removed
	for i=1, g_convoy_locationsToUse do
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[i])
	end
	
	-- Complete the Objective and Remove the Rule
	Util_ObjectiveComplete(Objective_StopConvoysFromReachingBase.title_id)
	Rule_Remove(Rule_StopConvoysFromReachingBase_Objective)
end

-- -- Controls Removing the Objective Pings as each mechanized command is destroyed -- for i=1, g_convoy_locationsToUse do -- -- if the mechanized command was destroyed -- if Objective_Exists(Objective_StopConvoysFromReachingBase.title_id) == true and -- EGroup_Count("eg_convoyBase_mechanizedCommand"..i) == 0 -- then -- -- stop the ping at that location -- Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[i]) -- end -- end end

-- Assigns & Checks for Secondary Objective : (Stop MegaBasilisk Attacks) function Rule_StopMegaBasiliskAttacks_Objective() -- First check if Objective exists and add if not... if Event_IsAnyRunning() == false and Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == false then -- Create (Assign) the objective as a secondary one Util_ObjectiveCreate(Objective_StopMegaBasiliskAttacks, false)

	-- Add Sub-Secondary Objectives
	Rule_AddInterval(Rule_DestroyMegaBasilisk_Objective, 1)

-- Complete Objective if you completed the Destroy Mega Basilisk Sub-Objective
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and
	Objective_Exists(Objective_DestroyMegaBasilisk.title_id) == true and
	Objective_GetState(Objective_DestroyMegaBasilisk.title_id) == OS_Complete
then
	-- Complete the Objective and Remove the Rule
	Util_ObjectiveComplete( Objective_StopMegaBasiliskAttacks.title_id )
	Rule_Remove( Rule_StopMegaBasiliskAttacks_Objective )

-- Complete Objective if you completed the Stop Spotter Production Sub-Objective 
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and
	Objective_Exists(Objective_StopSpotterProduction.title_id) == true and
	Objective_GetState(Objective_StopSpotterProduction.title_id) == OS_Complete
then
	-- Complete the Objective and Remove the Rule
	Util_ObjectiveComplete(Objective_StopMegaBasiliskAttacks.title_id)
	Rule_Remove(Rule_StopMegaBasiliskAttacks_Objective)
end

--Once Objective Completes: Remove the SubObjective Rules (in case were never removed)
if Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and
	Objective_GetState(Objective_StopMegaBasiliskAttacks.title_id) == OS_Complete
then
	Rule_Remove(Rule_DestroyMegaBasilisk_Objective)
	Rule_Remove(Rule_StopSpotterProduction_Objective)
	Rule_Remove(Rule_KillSpotters_Objective)
end	

end

-- Assigns & Checks for Sub-Secondary Objective : (Destroy Mega Basilisk) function Rule_DestroyMegaBasilisk_Objective() -- Confirm the Secondary Objective Exists and then check if the Sub-Objective exists and add sub if not... if Event_IsAnyRunning() == false and Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and Objective_GetState(Objective_StopMegaBasiliskAttacks.title_id) ~= OS_Complete and Objective_Exists(Objective_DestroyMegaBasilisk.title_id) == false then -- Create (Assign) the objective as a sub-primary one Objective_SubAdd(Objective_DestroyMegaBasilisk, Objective_StopMegaBasiliskAttacks.title_id)

	--Associate a Ping with the Objective on the Objective Screen
	Objective_PingMarker(Objective_DestroyMegaBasilisk.title_id, "mkr_centerBase_bigGun", true, attack)
	
	-- In game Ping
	Ping_Marker("mkr_centerBase_bigGun", false, "default")
	
	-- Reveal Fog of War around the Objective briefly
	FOW_RevealMarker("mkr_centerBase_bigGun", 10)
	
	-- Buys Gun time to go active, until it can respond with IE to being under attack (so it doesn't look stupid with Activate IE followed by UnderAttack IE)
	Rule_AddOneShot(Rule_Setup_BigGun_UnderAttack_IE, 30)
	
	-- Add Next Sub-Objective
	Rule_AddInterval(Rule_StopSpotterProduction_Objective, 1)

-- if the objective exists and Basilisk is destroyed
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and
	Objective_Exists(Objective_DestroyMegaBasilisk.title_id) == true and
	EGroup_Exists("eg_MegaBasilisk_Objective") and
	EGroup_Count( EGroup_FromName("eg_MegaBasilisk_Objective")) == 0
then
	-- Play IE: MegaBasilisk destroyed
	Util_StartIntel(EVENTS.IE_MegaArtilleryDestroyed)
	
	-- Complete the Objective and Remove the Rule
	Util_ObjectiveComplete(Objective_DestroyMegaBasilisk.title_id)
	Rule_Remove(Rule_DestroyMegaBasilisk_Objective)

--Check if Player is Attacking the Gun after it goes active
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and
	Objective_Exists(Objective_DestroyMegaBasilisk.title_id) == true and
	Player_AreSquadsNearMarker(g_Player1, "mkr_bigGun_underAttack") and
	g_IE_Fired_Attack_BigGun == false
then
	-- Play IE: Defend the Basilisk
	Util_StartIntel(EVENTS.IE_DefendMegaArtillery)
	g_IE_Fired_Attack_BigGun = true
end

end

-- Assigns & Check for Sub-Secondary Objective : (Stop Spotter Production) function Rule_StopSpotterProduction_Objective() -- Confirm the Secondary Objective Exists and then check if the Sub-Objective exists and add sub if not... if Event_IsAnyRunning() == false and Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and Objective_GetState(Objective_StopMegaBasiliskAttacks.title_id) ~= OS_Complete and Objective_Exists(Objective_StopSpotterProduction.title_id) == false then -- Create (Assign) the objective as a sub-primary one Objective_SubAdd(Objective_StopSpotterProduction, Objective_StopMegaBasiliskAttacks.title_id)

	--Associate a Ping with the Objective on the Objective Screen
	g_spotterHQOnePing_Objective = Objective_PingMarker(Objective_StopSpotterProduction.title_id, "mkr_centerBase_HQ1", true, attack)
	g_spotterHQTwoPing_Objective = Objective_PingMarker(Objective_StopSpotterProduction.title_id, "mkr_centerBase_HQ2", true, attack)
	
	-- Set up a ping on the ingame screen
	Ping_Marker("mkr_centerBase_HQ1", false, "default")
	Ping_Marker("mkr_centerBase_HQ2", false, "default")
	
	-- Reveal the Fog of War Around the Spotter HQ Buildings Briefly
	FOW_RevealMarker("mkr_centerBase_HQ1", 10)
	FOW_RevealMarker("mkr_centerBase_HQ2", 10)
	
	-- Add Next Sub-Objective
	Rule_AddInterval(Rule_KillSpotters_Objective, 1)

-- if the objective exists and both of the Spotter HQs are destroyed
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and
	Objective_Exists(Objective_StopSpotterProduction.title_id) == true and	
	EGroup_Count( EGroup_FromName("eg_centerBase_Spotters_Production_Objective")) == 0
then
	-- Play IE: Spotter HQs Destroyed
	Util_StartIntel(EVENTS.IE_MegaArtillerySpottersKilled)
	
	-- Complete the Objective and Remove the Rule
	Util_ObjectiveComplete(Objective_StopSpotterProduction.title_id)
	Rule_Remove(Rule_StopSpotterProduction_Objective)

-- if the objective exists and Spotter HQ One Building is destroyed
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and
	Objective_Exists(Objective_StopSpotterProduction.title_id) == true and	
	EGroup_Count( EGroup_FromName("eg_centerBase_HQ1")) == 0
then
	-- Remove the Objective Screen Ping Associated with Spotter HQ building One
	Objective_PingRemove(Objective_StopSpotterProduction.title_id, g_spotterHQOnePing_Objective)

-- if the objective exists and and Spotter HQ Two is destroyed
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and
	Objective_Exists(Objective_StopSpotterProduction.title_id) == true and	
	EGroup_Count( EGroup_FromName("eg_centerBase_HQ2")) == 0
then
	-- Remove the Objective Screen Ping Associated with Spotter HQ building Two
	Objective_PingRemove(Objective_StopSpotterProduction.title_id, g_spotterHQTwoPing_Objective)
end

end

-- Assigns Sub-Secondary Objective : (Kill Spotters) --Objective Can't Directly Be Completed -- Is Just Extra Reminder Text, & AutoCompletes when the Secondary Objective: StopMegaBasiliskAttacks Completes function Rule_KillSpotters_Objective() -- Confirm the Secondary Objective Exists and then check if the Sub-Objective exists and add sub if not... if Event_IsAnyRunning() == false and Objective_Exists(Objective_StopMegaBasiliskAttacks.title_id) == true and Objective_GetState(Objective_StopMegaBasiliskAttacks.title_id) ~= OS_Complete and Objective_Exists(Objective_KillSpotters.title_id) == false then -- Create (Assign) the objective as a sub-primary one Objective_SubAdd(Objective_KillSpotters, Objective_StopMegaBasiliskAttacks.title_id)

	-- Show the Objective Screen
	Objective_ShowScreen()
end	

end

-- Assigns & Checks for Secondary Objective: (Destroy the Marauder Producing Mech Commands) function Rule_StopBomberProduction_Objective() -- First check if Objective exists and add if not... if Event_IsAnyRunning() == false and Objective_Exists(Objective_StopBomberProduction.title_id) == false then -- Create ( & Assign) the objective as a secondary one Util_ObjectiveCreate(Objective_StopBomberProduction, false)

	--Associate a Ping with the Objective on the Objective Screen
	g_airBaseOnePing_Objective = Objective_PingMarker(Objective_StopBomberProduction.title_id, "mkr_convoyBase_mechanizedCommand5", true, attack)
	g_airBaseTwoPing_Objective = Objective_PingMarker(Objective_StopBomberProduction.title_id, "mkr_convoyBase_mechanizedCommand6", true, attack)
	
	-- Set up a one-time ping on the ingame screen
	Ping_Marker("mkr_convoyBase_mechanizedCommand5", false, "default")
	Ping_Marker("mkr_convoyBase_mechanizedCommand6", false, "default")
	
	-- Reveal the Fog of War Around the Air Unit Mech Commands Briefly
	FOW_RevealMarker("mkr_convoyBase_mechanizedCommand5", 10)
	FOW_RevealMarker("mkr_convoyBase_mechanizedCommand6", 10)
	
	-- Play IE: Activate Airfield & Show Objective Screen
	Util_StartIntel(EVENTS.IE_ActivateAirfield)
	Objective_ShowScreen()
	
	-- Buys Airbase time to go active, until it can respond with IE to being under attack (so it doesn't look stupid with Activate IE followed by UnderAttack IE)
	Rule_AddOneShot(Rule_Setup_AirBase_UnderAttack_IE, 30)

-- if the objective exists and both of the Air Unit Producting Mechanized Commands are destroyed
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBomberProduction.title_id) == true and
	EGroup_Count( EGroup_FromName("eg_StopBomberProduction_Objective")) == 0
then
	-- Play IE: Airfield Destroyed
	Util_StartIntel(EVENTS.IE_AirfieldDestroyed)
	
	-- Complete the Objective and Remove the Rule
	Util_ObjectiveComplete(Objective_StopBomberProduction.title_id)
	Rule_Remove(Rule_StopBomberProduction_Objective)

-- if the objective exists and Mars Pattern One Building is destroyed
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBomberProduction.title_id) == true and
	EGroup_Count( EGroup_FromName("eg_convoyBase_mechanizedCommand5")) == 0
then
	-- Remove the Objective Screen Ping Associated with Air Unit Mech Command One
	Objective_PingRemove(Objective_StopBomberProduction.title_id, g_airBaseOnePing_Objective)

-- if the objective exists and and Air Unit Mech Command Two is destroyed
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBomberProduction.title_id) == true and
	EGroup_Count( EGroup_FromName("eg_convoyBase_mechanizedCommand6")) == 0
then
	-- Remove the Objective Screen Ping Associated with Air Unit Mech Command Two
	Objective_PingRemove(Objective_StopBomberProduction.title_id, g_airBaseTwoPing_Objective)

--Check if Player is Attacking the Base after it goes active
elseif Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBomberProduction.title_id) == true and
	Player_AreSquadsNearMarker(g_Player1, "mkr_northBase_underAttack") and
	g_airField_underAttack_IE == false
then
	-- Play IE: Airfield is under attack
	Util_StartIntel(EVENTS.IE_AirfieldAttacked)
	g_airField_underAttack_IE = true
end

end

-- Called after a delay when objective is assigned, so can track if player attacks the Air Base once it goes active function Rule_Setup_AirBase_UnderAttack_IE() g_IE_Fired_Attack_AirBase = false end -- Called after a delay when objective is assigned, so can track if player attacks the MegaBasilisk once it goes active function Rule_Setup_BigGun_UnderAttack_IE() g_IE_Fired_Attack_BigGun = false end

-- END OF ALL " OBJECTIVES " RULES


-- INCREASE ALERT LEVELS -- Increase the Overall Alert Level -- Allows Better Research & More Unit Production (Enabled Bases) -- Rule_Upgrade_To_Alert_One() -- Rule_Upgrade_To_Alert_Two() -- Rule_Upgrade_To_Alert_Three() -- Rule_Upgrade_To_Alert_Four() -- Rule_Upgrade_To_Alert_Five()

-- Make Sure Alert Level Increased: Time Delay : added in OnGameStart() 
	-- Rule_Delayed_Upgrade_To_Alert_One()
	-- Rule_Delayed_Upgrade_To_Alert_Two()
	-- Rule_Delayed_Upgrade_To_Alert_Three()
	-- Rule_Delayed_Upgrade_To_Alert_Four()
	-- Rule_Delayed_Upgrade_To_Alert_Five()

-- Rule_IncreaseAlertLevel_ConvoyLosing() : Increase the Alert Level since the Player has destroyed too many convoys
	-- Called as a One Shot from: Rule_Check_For_Convoy_Destruction()
-- Rule_Check_For_All_MechanizedCommand_Destroyed() : Checks to Make sure that a mechanized command still exsists to spawn convoys out of
		-- Also Controls Increasing Alert Level since some of the mechanized commands have been destroyed
		-- Added in Rule_Spawn_First_Convoy()

-- Increase the Overall Alert Level -- Allows Better Research & More Unit Production (Enabled Bases) function Rule_Upgrade_To_Alert_One() -- Play IE & Update Onscreen UI Util_StartIntel(g_ie_AlertLevel_Array[1]) UI_ShowCountUpdateDxp("AlertLevel_Ui", g_currentAlertStatus, 3950195)

-- Enable Grenade Launchers
g_grenadeLauncher_enabled	=	true

--Upgrade Main Base HQ to Addon1
	--Enables More Guardsmen
if EGroup_Count("eg_HQInMainBase_Objective") == 1
then
	EGroup_ForceAddOn("eg_HQInMainBase_Objective", "addon_guard_hq_1" )
end

-- Give HQ Upgrade to the Convoy Base HQs if they are still alive
for i = 1, 2 do
	if EGroup_Count("eg_convoyBase_HQ"..i) == 1
	then
		EGroup_ForceAddOn("eg_convoyBase_HQ"..i, "addon_guard_hq_1" )
	end
end

-- Enable the Capturing of Strat Points
g_canCaptureStrat = true

-- enable leaders & their skills
g_leaders_enabled = true

-- Enable Increased Morale Reseach One
Player_GrantResearch(g_Player2, "guard_guardsman_morale")
Player_GrantResearch(g_Player5, "guard_guardsman_morale")

-- Enable Increased Guardsmen Health
Player_GrantResearch(g_Player2, "guard_upgrade_guardsmen_health")
Player_GrantResearch(g_Player5, "guard_upgrade_guardsmen_health")

-- Enable Increased Guardsmen Range on Weapons
Player_GrantResearch(g_Player2, "guard_upgrade_guardsmen_range")
Player_GrantResearch(g_Player5, "guard_upgrade_guardsmen_range")

--Start Comsat Detection Every 60 Seconds (1st Try after 1 second)
Rule_AddIntervalDelay(Rule_ComSat_For_CloakDetection,60,1)

end

-- Increase the Overall Alert Level -- Allows Better Research & More Unit Production (Enabled Bases) function Rule_Upgrade_To_Alert_Two() -- Play IE & Update Onscreen Display Util_StartIntel(g_ie_AlertLevel_Array[2]) UI_ShowCountUpdateDxp("AlertLevel_Ui", g_currentAlertStatus, 3950195)

--Upgrade Main Base HQ to Addon2 & Give Leader Temple Upgrades
	--Enables More Guardsmen & Leader Skills
	-- if fails should mean mission completed
if EGroup_Count("eg_HQInMainBase_Objective") == 1
then
	EGroup_ForceAddOn("eg_HQInMainBase_Objective", "addon_guard_hq_2" )
	EGroup_ForceAddOn("eg_HQInMainBase_Objective", "addon_guard_ministorum_temple" )
	EGroup_ForceAddOn("eg_HQInMainBase_Objective", "addon_guard_telepathica_temple" )
	EGroup_ForceAddOn("eg_HQInMainBase_Objective", "addon_guard_vindicare_temple" )
end

-- Give Upgrades & Temples to the Convoy Bases if they are still alive
for i = 1, 2 do
	if EGroup_Count("eg_convoyBase_HQ"..i) == 1
	then
		EGroup_ForceAddOn("eg_convoyBase_HQ"..i, "addon_guard_hq_2" )
		EGroup_ForceAddOn("eg_convoyBase_HQ"..i, "addon_guard_ministorum_temple" )
		EGroup_ForceAddOn("eg_convoyBase_HQ"..i, "addon_guard_telepathica_temple" )
	end
end

-- Check for Valkrie Drops : One By Initial LP
Rule_AddInterval(Rule_Valkrie_Five_CheckDrop, 5)

-- enable plasma weapons
g_plasmaGun_enabled = true

-- Increase Reinforce Percent (Larger Squad Sizes)
g_reinforce_percent	=	0.80

-- Increase Convoy HP & Speed Here 
Player_GrantResearch(g_Player4, "guard_research_convoy_armor")

-- Enable Increased Morale Research Two
Player_GrantResearch(g_Player2, "guard_guardsman_morale_2")
Player_GrantResearch(g_Player5, "guard_guardsman_morale_2")

-- Upgrade the Original Heavy Weapons Teams that still exsist
Rule_AddOneShot(Rule_Upgrade_Entreched_HeavyWeaponsTeams, 0)

-- Handles the IE, Assigning the Objectives, & Spawning the first spotters (MOVED TO ALERT LEVEL TWO)		 
Rule_AddOneShot(Rule_Activate_Basilisk_And_Spotters, g_timeUntilBasilisk)

--Activate the Center South Base (if not already active)
if g_base_activated_CenterSouth == false
then
	g_base_activated_CenterSouth = true
end

end

-- Increase the Overall Alert Level -- Allows Better Research & More Unit Production (Enabled Bases) function Rule_Upgrade_To_Alert_Three() -- Play IE & Update OnScreen Display Util_StartIntel(g_ie_AlertLevel_Array[3]) UI_ShowCountUpdateDxp("AlertLevel_Ui", g_currentAlertStatus, 3950195)

-- Stop Squads from Retreating
g_retreating_enabled = false

-- Stop the Capturing of Strat Points for good (Can still capture Relic & Critical Points)
g_canCaptureStrat = false

--Spotter tries to follow the Player Army
g_spotter_TargetArmy = true

-- Enable Increase Special Weapon Damage (& More Special Weapons)
Player_GrantResearch(g_Player2, "guard_upgrade_weapon_specialization")
Player_GrantResearch(g_Player5, "guard_upgrade_weapon_specialization")

-- Enable Better Ogryn Melee Attack
Player_GrantResearch(g_Player2, "guard_upgrade_ogryn_melee")
Player_GrantResearch(g_Player5, "guard_upgrade_ogryn_melee")

-- Enable Kasrkin Squads to Move Faster
Player_GrantResearch(g_Player2, "guard_research_kasrkin_speed")
Player_GrantResearch(g_Player5, "guard_research_kasrkin_speed")

-- Enable Kasrkin Squads to Have More Health
Player_GrantResearch(g_Player2, "guard_research_kasrkin_armor")
Player_GrantResearch(g_Player5, "guard_research_kasrkin_armor")

-- Enable More Special  Weapons (Grenade Launchers & Plasma Guns)
	-- So I can give the extra weapons that the research grants
g_number_WeaponsPerSquad	=	5

-- Check for Valkrie Drops -- One Behind the Player Base
Rule_AddInterval(Rule_Valkrie_One_CheckDrop, 5)

-- Shut Down the West Base (Reactives at alert four or when North Base is destroyed)
g_base_activated_West = false

-- Activate the North Base (if not already active)
if g_base_activated_North == false
then
	g_base_activated_North = true
	Rule_AddInterval(Rule_StopBomberProduction_Objective,5)
end

end

-- Increase the Overall Alert Level -- Allows Better Research & More Unit Production (Enabled Bases) function Rule_Upgrade_To_Alert_Four() -- Play IE & Update OnScreen Display Util_StartIntel(g_ie_AlertLevel_Array[4]) UI_ShowCountUpdateDxp("AlertLevel_Ui", g_currentAlertStatus, 3950195)

-- Enable Cloaked Assassin
Player_GrantResearch(g_Player2, "guard_research_assassin_infiltrate")
Player_GrantResearch(g_Player5, "guard_research_assassin_infiltrate")

-- Enable Full Scale War (Probably Does Nothing For Scenario)
Player_GrantResearch(g_Player2, "guard_full_scale_war")
Player_GrantResearch(g_Player5, "guard_full_scale_war")

-- Further increase the Convoy Armor & Speed
Player_GrantResearch(g_Player4, "guard_research_convoy_armor_2")

-- Increase Reinforce Percent (Larger Squad Sizes)
g_reinforce_percent	=	0.90

-- Increase Number of Troops CenterSouth Base Produces
g_num_chimera_troops	=	2

-- Reactivate the West Base (was turned off to lessen attacks for a while -- gives player chance to adapt & catch up)
g_base_activated_West = true

--Activate the Center North Base: Basilisks (if not already active)
if g_base_activated_CenterNorth == false
then
	g_base_activated_CenterNorth = true
end	

end

-- Increase the Overall Alert Level -- Allows Better Research & More Unit Production (Enabled Bases) function Rule_Upgrade_To_Alert_Five() -- Play IE & Update OnScreen Display Util_StartIntel(g_ie_AlertLevel_Array[5]) UI_ShowCountUpdateDxp("AlertLevel_Ui", g_currentAlertStatus, 3950195)

-- Increase Reinforce Percent (Larger Squad Sizes)
g_reinforce_percent	=	0.99

-- Increase Number of Troops CenterSouth Base Produces
g_num_chimera_troops	=	2

--Activate the Main Base in case never activated via attack or base destruction 
if g_base_activated_Main == false
then
	g_base_activated_Main = true
end	

end

-- Make Sure Alert Level Increased: Time Delay : added in OnGameStart() function Rule_Delayed_Upgrade_To_Alert_One() if g_currentAlertStatus == 0 then g_currentAlertStatus = 1 Rule_AddOneShot(Rule_Upgrade_To_Alert_One, 0) end end

-- Make Sure Alert Level Increased: Time Delay : added in OnGameStart() function Rule_Delayed_Upgrade_To_Alert_Two() if g_currentAlertStatus == 1 then g_currentAlertStatus = 2 Rule_AddOneShot(Rule_Upgrade_To_Alert_Two, 0) end end

-- Make Sure Alert Level Increased: Time Delay : added in OnGameStart() function Rule_Delayed_Upgrade_To_Alert_Three() if g_currentAlertStatus == 2 then g_currentAlertStatus = 3 Rule_AddOneShot(Rule_Upgrade_To_Alert_Three, 0) end end -- Make Sure Alert Level Increased: Time Delay : added in OnGameStart() function Rule_Delayed_Upgrade_To_Alert_Four() if g_currentAlertStatus == 3 then g_currentAlertStatus = 4 Rule_AddOneShot(Rule_Upgrade_To_Alert_Four, 0) end end -- Make Sure Alert Level Increased: Time Delay : added in OnGameStart() function Rule_Delayed_Upgrade_To_Alert_Five() if g_currentAlertStatus == 4 then g_currentAlertStatus = 5 Rule_AddOneShot(Rule_Upgrade_To_Alert_Five, 0) end end

-- Increase the Alert Level since the Player has destroyed too many convoys -- Called as a One Shot from: Rule_Check_For_Convoy_Destruction() function IncreaseAlertLevel_ConvoyLosing() -- if the player has destroyed the number of convoys to increase the Alert Level to One & is still at zero if g_number_convoys_destroyed == g_increase_AlertToOne_Convoy and g_currentAlertStatus == 0 then --print("Increasing Alert Level to One base on Convoy Destruction") g_currentAlertStatus = 1 Rule_AddOneShot(Rule_Upgrade_To_Alert_One,1)

-- if the player has destroyed the number of convoys to increase the Alert Level to Two & is still at One
elseif g_number_convoys_destroyed == g_increase_AlertToTwo_Convoy and
	g_currentAlertStatus == 1	
then
	--print("Increasing Alert Level to Two based on Convoy Destruction")
	g_currentAlertStatus = 2
	Rule_AddOneShot(Rule_Upgrade_To_Alert_Two,1)

-- if the player has destroyed the number of convoys to increase the Alert Level to Three & is still at Two
elseif g_number_convoys_destroyed == g_increase_AlertToThree_Convoy and
	g_currentAlertStatus == 2	
then
	--print("Increasing Alert Level to Three based on Convoy Destruction")
	g_currentAlertStatus = 3
	Rule_AddOneShot(Rule_Upgrade_To_Alert_Three,1)

-- if the player has destroyed the number of convoys to increase the Alert Level to Four & is still at Three
elseif g_number_convoys_destroyed == g_increase_AlertToFour_Convoy and
	g_currentAlertStatus == 3	
then
	--print("Increasing Alert Level to Four based on Convoy Destruction")
	g_currentAlertStatus = 4
	Rule_AddOneShot(Rule_Upgrade_To_Alert_Four,1)

-- if the player has destroyed the number of convoys to increase the Alert Level to Five & is still at Four
elseif g_number_convoys_destroyed == g_increase_AlertToFive_Convoy and
	g_currentAlertStatus == 4	
then
	--print("Increasing Alert Level to Five based on Convoy Destruction")
	g_currentAlertStatus = 5
	Rule_AddOneShot(Rule_Upgrade_To_Alert_Five,1)
end

end

-- Checks to Make sure that a mechanized command still exsists to spawn convoys out of : added in Rule_Spawn_First_Convoy() -- Also Controls Increasing Alert Level since some of the mechanized commands have been destroyed function Rule_Check_For_All_MechanizedCommand_Destroyed() local stillCanSpawn = false local howManyDestroyed = 0

--loop through all the active convoy mechanized commands..
for i = 1, g_convoy_locationsToUse do
	-- does a mechanized command still exist?
	if EGroup_Count("eg_convoyBase_mechanizedCommand"..i) == 1
	then
		--... then we can keep spawning in convoys
		stillCanSpawn = true
	else
		-- if not, keep track of how many have been destroyed
		howManyDestroyed = howManyDestroyed + 1
	end		
end

-- all mechanized commands were destroyed
if stillCanSpawn == false 
then
	-- ...Set it so a new convoy never tries to spawn again
	g_convoy_canSpawnNewOne = false

	-- Remove the rule since all Commands destroyed
	Rule_Remove(Rule_Check_For_All_MechanizedCommand_Destroyed)

-- if the player has destroyed enough bases to increase the Alert Level to Five and is still at Four
elseif howManyDestroyed == g_increase_AlertToFive_Bases and
	g_currentAlertStatus == 4
then
	g_currentAlertStatus = 5
	Rule_AddOneShot(Rule_Upgrade_To_Alert_Five,1)
	
-- if the player has destroyed enough bases to increase the Alert Level to Four and is still at Three
elseif howManyDestroyed == g_increase_AlertToFour_Bases and
	g_currentAlertStatus == 3	
then
	g_currentAlertStatus = 4
	Rule_AddOneShot(Rule_Upgrade_To_Alert_Four,1)

-- if the player has destroyed enough bases to increase the Alert Level to Three and is still at Two
elseif howManyDestroyed == g_increase_AlertToThree_Bases and
	g_currentAlertStatus == 2	
then
	g_currentAlertStatus = 3
	Rule_AddOneShot(Rule_Upgrade_To_Alert_Three,1)

-- if the player has destroyed enough bases to increase the Alert Level to Two and is still at One
elseif howManyDestroyed == g_increase_AlertToTwo_Bases and
	g_currentAlertStatus == 1	
then
	g_currentAlertStatus = 2
	Rule_AddOneShot(Rule_Upgrade_To_Alert_Two,1)

-- if the player has destroyed enough bases to increase the Alert Level to One and is still at Zero
elseif howManyDestroyed == g_increase_AlertToOne_Bases and
	g_currentAlertStatus == 0	
then
	g_currentAlertStatus = 1
	Rule_AddOneShot(Rule_Upgrade_To_Alert_One,1)
end

end

-- END OF ALL " INCREASE ALERT LEVELS " RULES


-- UNIT PRODUCTION -- Rule_Produce_XXX (squadName, buildingName, markerName) -- Produces (& Upgrades) XXX from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists -- Return True if XXX is Created, & False if the Building is Destroyed

-- Unit Types:
	-- Rule_Produce_Assassin
	-- Rule_Produce_Enginseer
	-- Rule_Produce_Guardsmen
		-- Rule_Produce_Guardsmen_Full
	-- Rule_Produce_Kasrkin
		-- Rule_Produce_Kasrkin_Full
	-- Rule_Produce_Ogryn
	-- Rule_Produce_Sentinel
	-- Rule_Produce_Basilisk
	-- Rule_Produce_Hellhound
	-- Rule_Produce_Chimera
	-- Rule_Produce_Marauder
	-- Rule_Produce_LemanRuss

-- Rule_Upgrade_Grenade_Launchers_And_Plasma(squadName) : Equips the Guardsman ( & Kaskrin) Squad with Grenade Launchers & Plasma Upgrades if available

-- Produce an assassin from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Assassin(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- Create an assassin & return "true" Util_CreateSquadsAtMarker(g_Player2, squadName, "guard_squad_assassin", markerName, 1) return true end

-- assassin not created since building doesn't exist
return false

end

-- Produce an enginseer (builder) from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Enginseer(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- Create a squad of enginseer & return "true" Util_CreateSquadsAtMarker(g_Player2, squadName, "guard_squad_enginseer", markerName, 1) return true end

-- enginseer squad not created since building doesn't exist
return false

end

-- Produce (& Upgrade) a Guardsmen Squad from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Guardsmen(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- Create a squad of guardsmen & give leader Util_CreateSquadsAtMarkerEx(g_Player2, squadName, "guard_squad_guardsmen", markerName, 1, 5) SGroup_AddLeaders(squadName)

	-- Give the Squad Grenade Launchers & Plasma if enabled
	Rule_Upgrade_Grenade_Launchers_And_Plasma(squadName)
	
	-- Guardsmen Squad was Created
	return true
end

--Guardsmen squad not created since building doesn't exist
return false

end

-- Produce (& Upgrade) a Full Guardsmen Squad from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Guardsmen_Full(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- Create a squad of guardsmen & give leader Util_CreateSquadsAtMarkerEx(g_Player2, squadName, "guard_squad_guardsmen", markerName, 1, 13) SGroup_AddLeaders(squadName)

	-- Give the Squad Grenade Launchers & Plasma if enabled
	Rule_Upgrade_Grenade_Launchers_And_Plasma(squadName)
	
	-- Guardsmen Squad was Created
	return true
end

--Guardsmen squad not created since building doesn't exist
return false

end

-- Produce (& Upgrade) a Kasrkin Squad from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Kasrkin(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- Create a squad of Kasrkin & give leader Util_CreateSquadsAtMarkerEx(g_Player2, squadName, "guard_squad_kasrkin", markerName, 1, 5) SGroup_AddLeaders(squadName)

	-- Give the Squad Grenade Launchers & Plasma if enabled
	Rule_Upgrade_Grenade_Launchers_And_Plasma(squadName)
	
	-- Kasrkin Squad was Created
	return true
end

-- Kasrkin squad not created since building doesn't exist
return false

end

-- Produce (& Upgrade) a Full Kasrkin Squad from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Kasrkin_Full(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- Create a squad of Kasrkin & give leader Util_CreateSquadsAtMarkerEx(g_Player2, squadName, "guard_squad_kasrkin", markerName, 1, 9) SGroup_AddLeaders(squadName)

	-- Give the Squad Grenade Launchers & Plasma if enabled
	Rule_Upgrade_Grenade_Launchers_And_Plasma(squadName)
	
	-- Kasrkin Squad was Created
	return true
end

-- Kasrkin squad not created since building doesn't exist
return false

end

-- Produce a Ogryn Squad from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Ogryn(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- Create a squad of Ogryn & give leader Util_CreateSquadsAtMarkerEx(g_Player2, squadName, "guard_squad_ogryns", markerName, 1, 3) SGroup_AddLeaders(squadName)

	-- Ogryn Squad was Created
	return true
end

-- Ogryn squad not created since building doesn't exist
return false

end

-- Produce a Sentinel from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Sentinel(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- create a Sentinel & return "true" Util_CreateSquadsAtMarker(g_Player2, squadName, "guard_squad_sentinel", markerName, 1) return true end

-- Sentinel not created since the building doesn't exist
return false

end

-- Produce a basilisk from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Basilisk(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- create a basilisk & return "true" Util_CreateSquadsAtMarker(g_Player2, squadName, "guard_squad_basilisk", markerName, 1) return true end

-- basilisk not created since the building doesn't exist
return false

end

-- Produce a Hellhound from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Hellhound(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- create a Hellhound & return "true" Util_CreateSquadsAtMarker(g_Player2, squadName, "guard_squad_hellhound", markerName, 1) return true end

-- Hellhound not created since the building doesn't exist
return false

end

-- Produce a Chimera from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Chimera(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- create a Chimera & return "true" Util_CreateSquadsAtMarker(g_Player2, squadName, "guard_squad_chimera", markerName, 1) return true end

-- Chimera not created since the building doesn't exist
return false

end -- Produce a Marauder from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_Marauder(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- create a Marauder & return "true" Util_CreateSquadsAtMarker(g_Player2, squadName, "guard_squad_marauder", markerName, 1) return true end

-- Marauder not created since the building doesn't exist
return false

end -- Produce a Leman Russ from Building at Marker for g_Player2 & Assign it to SGroup(squadName) if building exists function Rule_Produce_LemanRuss(squadName, buildingName, markerName) -- if building still exists if EGroup_Count(buildingName) == 1 then -- create a Leman Russ Tank & return "true" Util_CreateSquadsAtMarker(g_Player2, squadName, "guard_squad_lemanruss", markerName, 1) return true end

-- Leman Russ Tank not created since the building doesn't exist
return false

end

-- Equips the Guardsman ( & Kaskrin) Squad with Grenade Launchers & Plasma Upgrades if available function Rule_Upgrade_Grenade_Launchers_And_Plasma(squadName) local grenadeLaunchers = 0 local plasmaGuns = 0

-- if grenadeLaunchers are enabled (enabled at Alert Level One) --  Pick how Many grenade launchers per squad
if g_grenadeLauncher_enabled	==	true
then
	grenadeLaunchers = World_GetRand(0,g_number_WeaponsPerSquad)
end

-- only grenade launchers are avalible
if 	g_plasmaGun_enabled == false and 
	g_grenadeLauncher_enabled	== true
then
	-- make all weapons to grenade launchers
	grenadeLaunchers = g_number_WeaponsPerSquad
	
	--print("Giving Troops "..grenadeLaunchers.." grenades")
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName(squadName), 1),"guard_grenade_launcher_guardsmen", grenadeLaunchers)

-- both plasma & grenade are enabled (Plasma is enabled at Alert Level Two)
elseif g_plasmaGun_enabled == true and
		g_grenadeLauncher_enabled	== true
then
	-- Plasma gets whatever is left
	plasmaGuns =  g_number_WeaponsPerSquad - grenadeLaunchers
	
	--print("Giving Troops "..grenadeLaunchers.." grenades & "..plasmaGuns.." Plasma")
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName(squadName), 1),"guard_grenade_launcher_guardsmen", grenadeLaunchers)
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName(squadName), 1),"guard_plasma_gun_guardsmen", plasmaGuns)
end

end


-- END OF ALL " UNIT PRODUCTION " RULES


-- SQUAD AI & TACTICS -- Rule_Squad_Tactics_Helper() : Helper Function that passes squads to the real tactics function & chooses skills for the squad -- Added from Rule_Create_And_Sync_Attacks() -- Rule_Squad_Tactics(squad, squad_status, skill_id) : Decides if a squad should Attack, Use Skills, Reinforce, Retreat, or wait since still loading into a transport -- Rule_Squad_Skill(squad, skillID) : Squad tries to use a variety of skills against Player Squads based on skillID passed in

-- ForEach Functions:
	-- Rule_Detect_Proximity(sgroupid, itemindex, squadID) : Checks if a Enemy Squad (Non-Vehicle) is In Range of Your Squad for Skill Targeting
	-- Rule_Detect_Proximity_Vehicles(sgroupid, itemindex, squadID) : Check if a Enemy Vehicle is In Range of Your Squad for Skill Targeting
	-- Rule_Detect_Proximity_Buildings(egroupid, itemindex, entityID) : Check if a Enemy Building is In Range of Your Squad for Skill Targeting
	-- Rule_Detect_Proximity_CapturePoints(egroupid, itemindex, entityID) : Check if a Player Owned Strategic Point, Relic or Crit Point is In Range of Squad for Capturing
	-- Rule_Detect_Proximity_CapturePoints_Location(egroupid, itemindex, entityID) : Check if a Player Owned Strategic Point, Relic or Crit Point is In Range of Squad for Capturing & Sets Attack Location to that point

-- Helper Function that passes squads to the real tactics function & chooses skills for the squad function Rule_Squad_Tactics_Helper_One() -- Get all the world owned strategic points (relics & crits also) EGroup_Clear("eg_world_points") World_GetStrategicPoints("eg_world_points")

-- Don't Bother with AI Tactics until the Base Activates
if g_base_activated_Main == true
then
	-- Handles Basilisk w/ Earth Shaker, Hellhound with Inferno, & Leman Russ
	g_mainBase_lemanRuss_status[1] = Rule_Squad_Tactics("sg_mainBase_lemanRuss1", g_mainBase_lemanRuss_status[1], 0)
	g_mainBase_hellhound_status[1] = Rule_Squad_Tactics("sg_mainBase_hellhound1", g_mainBase_hellhound_status[1], 5)
	g_mainBase_basilisk_status[1] = Rule_Squad_Tactics("sg_mainBase_basilisk1", g_mainBase_basilisk_status[1], 6)
	
	-- Handles Troops w/ Comissar, Psyker, & Priest Skills
	g_mainBase_troops_status[1] = Rule_Squad_Tactics("sg_mainBase_troops1", g_mainBase_troops_status[1], 1)
	g_mainBase_troops_status[2] = Rule_Squad_Tactics("sg_mainBase_troops2", g_mainBase_troops_status[2], 2)
	g_mainBase_troops_status[3] = Rule_Squad_Tactics("sg_mainBase_troops3", g_mainBase_troops_status[3], 3)
	
	-- Handles Assassin w/ Skill
	g_mainBase_assassin_status[1] = Rule_Squad_Tactics("sg_mainBase_assassin1", g_mainBase_assassin_status[1], 9)
end

-- FOLLOWING SHOULD ALL BE DEAD BY THE TIME MAIN BASE GOES ACTIVE:
	-- Handles Guardsmen from LP North of Player Base
	g_initialLP_troops_status[1] = Rule_Squad_Tactics("sg_initialLP_troops1", g_initialLP_troops_status[1], 10)

	--Idle Base: Handles Guardsmen & Loaded Chimera
	if g_base_activated_Chimera == true
	then
		g_chimeraBase_troops_status[1] = Rule_Squad_Tactics("sg_chimeraBase_troops1", g_chimeraBase_troops_status[1], 10)
		g_chimeraBase_chimera_status[1] = Rule_Squad_Tactics("sg_chimeraBase_chimera1", g_chimeraBase_chimera_status[1], 0)
	end
	
	-- Idle Base: Handles Troops & Sentinels
	if g_base_activated_Sentinel == true
	then
		g_sentinelBase_troops_status[1] = Rule_Squad_Tactics("sg_sentinelBase_troops1", g_sentinelBase_troops_status[2], 10)
		g_sentinelBase_troops_status[2] = Rule_Squad_Tactics("sg_sentinelBase_troops2", g_sentinelBase_troops_status[2], 10)
		g_sentinelBase_sentinel_status[1] = Rule_Squad_Tactics("sg_sentinelBase_sentinel1", g_sentinelBase_sentinel_status[1], 11)
		g_sentinelBase_sentinel_status[2] = Rule_Squad_Tactics("sg_sentinelBase_sentinel2", g_sentinelBase_sentinel_status[2], 11)
	end
	
	-- Idle Base: Handles Leman Russ Tanks
	if g_base_activated_Tank == true
	then
		g_tankBase_tank_status[1] = Rule_Squad_Tactics("sg_tankBase_lemanRuss1", g_tankBase_tank_status[1], 0)
		g_tankBase_tank_status[2] = Rule_Squad_Tactics("sg_tankBase_lemanRuss2", g_tankBase_tank_status[2], 0)
	end

-- Add the Next Tactics Function
Rule_AddOneShot(Rule_Squad_Tactics_Helper_Two, 4)

end

-- Helper Function that passes squads to the real tactics function & chooses skills for the squad function Rule_Squad_Tactics_Helper_Two() -- Get all the world owned strategic points (relics & crits also) EGroup_Clear("eg_world_points") World_GetStrategicPoints("eg_world_points")

-- Handles Kaskrin w/ Grenades & Priest Leader & Ogyrns w/ Priest Leader
g_northBase_troops_status[1] = Rule_Squad_Tactics("sg_northBase_troops1", g_northBase_troops_status[1], 4)
g_northBase_troops_status[2] = Rule_Squad_Tactics("sg_northBase_troops2", g_northBase_troops_status[2], 3)

-- Handles Marauder Bombers & Bombing Skills
g_northBase_marauder_status[1] = Rule_Squad_Tactics("sg_northBase_marauder1", g_northBase_marauder_status[1], 8)

-- Handles Guardsmen w/ Commissar & Psyker Leaders Skills
g_westBase_troops_status[1] = Rule_Squad_Tactics("sg_westBase_troops1", g_westBase_troops_status[1], 1) 
g_westBase_troops_status[2] = Rule_Squad_Tactics("sg_westBase_troops2", g_westBase_troops_status[2], 2)

-- Add the Next Tactics Function
Rule_AddOneShot(Rule_Squad_Tactics_Helper_Three, 4)

end

-- Helper Function that passes squads to the real tactics function & chooses skills for the squad function Rule_Squad_Tactics_Helper_Three() -- Get all the world owned strategic points (relics & crits also) EGroup_Clear("eg_world_points") World_GetStrategicPoints("eg_world_points")

--Handles Guardsmen & Loaded Chimera
g_centerSouthBase_chimera_status[1] = Rule_Squad_Tactics("sg_centerSouthBase_chimera1", g_centerSouthBase_chimera_status[1], 0)

g_centerSouthBase_troops_status[1] = Rule_Squad_Tactics("sg_centerSouthBase_troops1", g_centerSouthBase_troops_status[1], 10)
g_centerSouthBase_troops_status[2] = Rule_Squad_Tactics("sg_centerSouthBase_troops2", g_centerSouthBase_troops_status[2], 10)
g_centerSouthBase_troops_status[3] = Rule_Squad_Tactics("sg_centerSouthBase_troops3", g_centerSouthBase_troops_status[3], 10)

-- Handles Basilisk w EarthShaker Rounds & Troops
g_centerNorthBase_basilisk_status[1] = Rule_Squad_Tactics("sg_centerNorthBase_basilisk1", g_centerNorthBase_basilisk_status[1], 6)
g_centerNorthBase_troops_status[1] = Rule_Squad_Tactics("sg_centerNorthBase_troops1", g_centerNorthBase_troops_status[1], 10)

-- Handles Other Marauder Bombers & Bombing Skills (So Don't Bombing Run at same time)
g_northBase_marauder_status[2] = Rule_Squad_Tactics("sg_northBase_marauder2", g_northBase_marauder_status[2], 8)

-- Restart the Next Cycle of Tactics
Rule_AddOneShot(Rule_Squad_Tactics_Helper_One, 4)

end

-- Decides if a squad should Attack, Use Skills, Reinforce, Retreat, or wait since still loading into a transport function Rule_Squad_Tactics(squad, squad_status, skill_id) -- ForEach Function: Check if a Player Owned Strategic Point, Relic or Crit Point is In Range of Squad for Capturing & Sets Attack Location to that point function Rule_Detect_Proximity_CapturePoints_Location(egroupid, itemindex, entityID) EGroup_Clear("building_target") EGroup_Add("building_target", EGroup_GetSpawnedEntityAt(egroupid,itemindex))

	-- If Squad is in proximity of a Relic
	if g_canCaptureRelic == true and
		Prox_SquadsInProximityOfEntities(squad, "building_target", range, true) and
		EGroup_ContainsBlueprints("building_target", g_blueprintRelic, false) == true
	then
		-- Attack towards the Relic
		g_attack_target = EGroup_GetPosition("building_target")
		return true
	
	-- If Squad is in proximity of a Critical Point 
	elseif g_canCaptureCrit == true and
		Prox_SquadsInProximityOfEntities(squad, "building_target", range, true) and
		EGroup_ContainsBlueprints("building_target", g_blueprintCritPoint, false) == true
	then
		-- Attack towards the Critical Point
		g_attack_target = EGroup_GetPosition("building_target")
		return true
	
	-- If Squad is in proximity of a Strategic Point 
	elseif g_canCaptureStrat == true and
		Prox_SquadsInProximityOfEntities(squad, "building_target", range, true) and
		EGroup_ContainsBlueprints("building_target", g_blueprintStratPoint, false) == true
	then
		-- Attack towards the Strategic Point
		g_attack_target = EGroup_GetPosition("building_target")
		return true
	end	
end

-- Make Sure Squad has members (otherwise this function is useless)
if SGroup_CountSpawned(squad) <= 0
then
	return squad_status
end	

-- if currently in Attack Mode...
if squad_status == g_squad_attacking
then
	-- If not a vehicle, then check for Reinforce (based on squad size being less then X %)
	if SGroup_IsVehicle(squad) == false and
		Squad_GetMax(SGroup_GetSpawnedSquadAt(squad,1)) > Squad_Count(SGroup_GetSpawnedSquadAt(squad,1)) and
		SGroup_GetAvgLoadout(squad) < g_reinforce_percent
	then
		-- Reinforce
		Command_Squad(g_Player2, squad, SCMD_ReinforceTrooper)
		squad_status = g_squad_reinforcing
	
	-- Check for & Attempt to use Skills
	elseif skill_id > 0 and Rule_Squad_Skill(squad, skill_id) == true
	then
		-- Skill Fired
		squad_status = g_squad_usingSkill
	
	-- Check for Retreat (based on morale broken)
	elseif g_retreating_enabled == true and 
		SGroup_IsMoraleBroken(squad,true) and
		World_GetRand(0,10) > 6
	then
		-- Give Location To Retreat To
		Command_SquadPos(g_Player2, squad, SCMD_Move, g_retreat_target)
		squad_status = g_squad_retreating		
	
	-- Just Choose "Attack Target" & Attack Move if none of the above
	else
		--g_attack_target = Marker_GetPosition(Marker_FromName("mkr_player_mainBase_HQ", "basic_marker"))
		
		-- Get the default Attack Targets For the AI Troops
		
		--If players HQ was destroyed
		if EGroup_Count("eg_player_HQ") == 0
		then
			-- Check for a second HQ
			EGroup_CreateFromEGroup("eg_player_HQ", EGroup_GetName(Player_GetEntities(g_Player1)), g_HQ_blueprint)
		end
		
		-- As long as player has an HQ -- that is the default attack location
		if EGroup_Count("eg_player_HQ") > 0
		then
			g_attack_target = EGroup_GetPosition("eg_player_HQ")
		else
			-- otherwise use the default player base location
			g_attack_target = Marker_GetPosition(Marker_FromName("mkr_player_mainBase_HQ", "basic_marker"))
		end
		
		-- Set Range for Target Tracking for Strategic Points:
		range = 150
		
		-- Override Attack Target for Locations of any Player Owned Relic, Critical or Strategic Points:
		if EGroup_ForEach(Player_GetEntities(g_Player1), Rule_Detect_Proximity_CapturePoints_Location)
		then
			-- Do Nothing... ForEach functions already did it
		
		-- Override Attack Target for Locations of any World Owned Relic, Critical or Strategic Points:
		elseif EGroup_Count("eg_world_points") > 0 and
			EGroup_ForEach("eg_world_points", Rule_Detect_Proximity_CapturePoints_Location)
		then
			-- Do Nothing... ForEach functions already did it
		end
		
		-- Attack Move to the Chosen Attack Target (Either default or the location of the strategic pt)
		Cmd_AttackMovePos(squad,g_attack_target)
	end

-- if currently in retreat mode
elseif squad_status == g_squad_retreating
then
	-- Check for Reinforce
	if Squad_GetMax(SGroup_GetSpawnedSquadAt(squad,1)) > Squad_Count(SGroup_GetSpawnedSquadAt(squad,1)) and
		SGroup_GetAvgLoadout(squad) < g_reinforce_percent
	then
		Command_Squad(g_Player2, squad, SCMD_ReinforceTrooper)
		squad_status = g_squad_retreating
	
	-- else set to attack mode if the morale is restored
	elseif SGroup_IsMoraleBroken(squad,true) == false
	then
		squad_status = g_squad_attacking
	end

-- Buy Transports another cycle or two to finish loading, before they attack (loading->produced->attacking)
elseif squad_status == g_squad_loading
then
	squad_status = g_squad_produced

-- Set Back to Attack Mode since everything else is done
	-- Includes g_squad_status == g_squad_reinforcing & g_squad_usingSkill
else
	squad_status = g_squad_attacking
end

-- return the new squad status
return squad_status	

end

-- Squad tries to use a variety of skills against Player Squads based on skillID passed in
function Rule_Squad_Skill(squad, skillID) -- ForEach Function: Checks if a Enemy Squad (Non-Vehicle) is In Range of Your Squad for Skill Targeting function Rule_Detect_Proximity(sgroupid, itemindex, squadID) SGroup_Clear("skill_target") SGroup_Add("skill_target", SGroup_GetSpawnedSquadAt(sgroupid,itemindex))

	if SGroup_IsVehicle("skill_target") == false and
		Prox_SquadsInProximityOfSquads(squad, "skill_target", range, true) and
		Prox_SquadsInProximityOfSquads(squad, "skill_target", rangeMin, true) == false
	then
		return true
	end
end

-- ForEach Function: Check if a Enemy Vehicle is In Range of Your Squad for Skill Targeting
function Rule_Detect_Proximity_Vehicles(sgroupid, itemindex, squadID)
	SGroup_Clear("skill_target")
	SGroup_Add("skill_target", SGroup_GetSpawnedSquadAt(sgroupid,itemindex))
	
	if SGroup_IsVehicle("skill_target") and
		Prox_SquadsInProximityOfSquads(squad, "skill_target", range, true) and
		Prox_SquadsInProximityOfSquads(squad, "skill_target", rangeMin, true) == false
	then
		return true
	end
end
	
-- ForEach Function: Check if a Enemy Building is In Range of Your Squad for Skill Targeting
function Rule_Detect_Proximity_Buildings(egroupid, itemindex, entityID)
	EGroup_Clear("building_target")
	EGroup_Add("building_target", EGroup_GetSpawnedEntityAt(egroupid,itemindex))
	
	-- Avoid Basic Strategic Point, Relic, Critical Point, & Cannibalism Parts
	local blueprintTable = Util_MakeBlueprintTable("relic_struct", "strategic_point_flag", "strategic_objective_struct", "cannibalism_Parts")
	
	if Prox_SquadsInProximityOfEntities(squad, "building_target", range, true) and 
		Prox_SquadsInProximityOfEntities(squad, "building_target", rangeMin, true) == false and 
		EGroup_ContainsBlueprints("building_target", blueprintTable, false) == false
	then
		return true
	end	
end

-- ForEach Function: Check if a Player Owned Strategic Point, Relic or Crit Point is In Range of Squad for Capturing
function Rule_Detect_Proximity_CapturePoints(egroupid, itemindex, entityID)
	EGroup_Clear("building_target")
	EGroup_Add("building_target", EGroup_GetSpawnedEntityAt(egroupid,itemindex))
	
	-- If Squad is in proximity of a Non-IG Owned Relic w/ No LP on it 
	if g_canCaptureRelic == true and
		Prox_SquadsInProximityOfEntities(squad, "building_target", range, true) and
		EGroup_ContainsBlueprints("building_target", g_blueprintRelic, true) == true and
		EGroup_HasStrategicPointWithStructure("building_target") == false
	then
		-- Try to Capture the Relic Point
		Cmd_Capture(squad, "building_target")
		return true
	
	-- If Squad is in proximity of a Non-IG Owned Critical Point 
	elseif g_canCaptureCrit == true and
		Prox_SquadsInProximityOfEntities(squad, "building_target", range, true) and
		EGroup_ContainsBlueprints("building_target", g_blueprintCritPoint, true) == true
	then
		-- Try to Capture the Critical Point
		Cmd_Capture(squad, "building_target")
		return true	
	
	-- If Squad is in proximity of a Non-IG Owned Strategic Point w/ No LP on it 
	elseif g_canCaptureStrat == true and
		Prox_SquadsInProximityOfEntities(squad, "building_target", range, true) and
		EGroup_ContainsBlueprints("building_target", g_blueprintStratPoint, true) == true and
		EGroup_HasStrategicPointWithStructure("building_target") == false
	then
		-- Try to Capture the Strategic Point
		Cmd_Capture(squad, "building_target")
		return true			
	end	
end	

rangeMin = 0

-- Commissar Execute Skill (Increase Morale & Fire Speed)
if skillID == 1
then
	local blueprintTable = Util_MakeBlueprintTable( "guard_squad_commissar")
	range = 30

	-- If Low Morale & Squad Actually Contains Commisar
	if SGroup_ContainsBlueprints(squad, blueprintTable, true) and
		SGroup_GetAvgMorale(squad) < 0.80 and
		Cmd_CastAbilitySGroup(squad, "guard_commissar_execute", squad)			
	then
		return true
	
	-- If Morale Not Broken -- Prioritize Infantry for attacks:
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0
	then
		Cmd_AttackSGroup(squad, "skill_target")
		return true
	
	-- If Morale Not Broken -- Try & Capture Player LPs
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		EGroup_ForEach(Player_GetEntities(g_Player1), Rule_Detect_Proximity_CapturePoints) and
		EGroup_Count("building_target") > 0
	then
		return true
	
	-- If Morale Not Broken -- Try & Capture World Owned LPs
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		EGroup_Count("eg_world_points") > 0 and
		EGroup_ForEach("eg_world_points", Rule_Detect_Proximity_CapturePoints)
	then
		return true
	end

-- Psker Proximity Skills (NOTE: All of these destroy morale of guardsmen in squad)
elseif skillID == 2
then
	local blueprintTable = Util_MakeBlueprintTable("guard_squad_psyker")
	range = 40
	
	-- Lightning Arc on Infantry Squads
	if SGroup_ContainsBlueprints(squad, blueprintTable, true) and
		SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0 and
		Cmd_CastAbilitySGroup(squad, "guard_psyker_lightning_arc", "skill_target")
	then
		return true
	
	-- Curse of the Machine Spirits on Vehicles
	elseif SGroup_ContainsBlueprints(squad, blueprintTable, true) and
			SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity_Vehicles) and
			SGroup_Count("skill_target") > 0 and
			Cmd_CastAbilitySGroup(squad, "guard_curse_machine_spirits", "skill_target")
	then
		return true
	
	-- Strip Soul on Infantry Squads
	elseif SGroup_ContainsBlueprints(squad, blueprintTable, true) and
			SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
			SGroup_Count("skill_target") > 0 and
			Cmd_CastAbilitySGroup(squad, "guard_psyker_strip_soul", "skill_target")
	then
		return true
		
	-- If Morale Not Broken -- Prioritize Infantry for attacks:
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0
	then
		Cmd_AttackSGroup(squad, "skill_target")
		return true
		
	-- If Morale Not Broken -- Try & Capture Player LPs
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		EGroup_ForEach(Player_GetEntities(g_Player1), Rule_Detect_Proximity_CapturePoints) and
		EGroup_Count("building_target") > 0
	then
		return true
	
	-- If Morale Not Broken -- Try & Capture World Owned LPs
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		EGroup_Count("eg_world_points") > 0 and
		EGroup_ForEach("eg_world_points", Rule_Detect_Proximity_CapturePoints)
	then
		return true
	end

-- Priest Fanatical Skill (Makes Squad Invulnerable)
elseif skillID == 3
then
	-- Set Range for Capturing
	range = 35
	
	local blueprintTable = Util_MakeBlueprintTable("guard_squad_priest")

	-- If Damaged Morale (Basically first time get into firefight) & Squad Contains Priest
	if SGroup_ContainsBlueprints(squad, blueprintTable, true) and
		SGroup_GetAvgMorale(squad) < 0.95 and
		Cmd_CastAbilitySelf(squad, "guard_priest_fanatical")
	then
		return true
	
	-- If Morale Not Broken -- Prioritize Infantry for attacks:
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0
	then
		Cmd_AttackSGroup(squad, "skill_target")
		return true
	
	-- If Morale Not Broken -- Try & Capture Player LPs
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		EGroup_ForEach(Player_GetEntities(g_Player1), Rule_Detect_Proximity_CapturePoints) and
		EGroup_Count("building_target") > 0
	then
		return true
	
	-- If Morale Not Broken -- Try & Capture World Owned LPs
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		EGroup_Count("eg_world_points") > 0 and
		EGroup_ForEach("eg_world_points", Rule_Detect_Proximity_CapturePoints)
	then
		return true
	end

--Kaskrin Grenades
elseif skillID == 4
then
	-- Set Range for Capturing / skills
	range = 35
	
	local blueprintTable = Util_MakeBlueprintTable("guard_squad_priest")
	
	-- Use Grenade on Infantry Squads
	if SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0 and
		Cmd_CastAbilitySGroup(squad, "guard_kasrkin_frag_grenades", "skill_target")
	then
		return true

	-- If Damaged Morale (Basically first time get into firefight) & Squad Contains Priest
	elseif SGroup_ContainsBlueprints(squad, blueprintTable, true) and
		SGroup_GetAvgMorale(squad) < 0.95 and
		Cmd_CastAbilitySelf(squad, "guard_priest_fanatical")
	then
		return true
	
	-- If Morale Not Broken -- Prioritize Infantry for attacks:
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0
	then
		Cmd_AttackSGroup(squad, "skill_target")
		return true
	
	-- If Morale Not Broken -- Try & Capture Player LPs
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		EGroup_ForEach(Player_GetEntities(g_Player1), Rule_Detect_Proximity_CapturePoints) and
		EGroup_Count("building_target") > 0
	then
		return true
	
	-- If Morale Not Broken -- Try & Capture World Owned LPs
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		EGroup_Count("eg_world_points") > 0 and
		EGroup_ForEach("eg_world_points", Rule_Detect_Proximity_CapturePoints)
	then
		return true
	end

--Hellhound Inferno
elseif skillID == 5
then
	range = 35
	
	-- Use Inferno on Infantry Squads
	if SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0 and
		Cmd_CastAbilitySGroup(squad, "guard_let_it_burn", "skill_target")
	then
		return true
	
	-- Attack Proximity Infantry Targets (So hellhound tries to avoid targeting vehicles)
	elseif SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0
	then			
		Cmd_AttackSGroup(squad, "skill_target")
		return true			
	end

--Basilisk Earthshaker Shot
elseif skillID == 6
then
	rangeMin = 25
	range = 45 --50
	
	-- Use Basilisk Earthshaker Shot on Infantry Squads
	if SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0 and
		Cmd_CastAbilitySGroup(squad, "earthshaker_round", "skill_target")
	then
		return true
	
	-- Attack Proximity Infantry Targets
	elseif SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0
	then			
		Cmd_AttackSGroup(squad, "skill_target")
		return true			
	end

--Commander Strafing Run ("guard_squad_command_squad", "guard_strafing_run")
elseif skillID == 7
then
	-- Do Nothing : Not Used in Mission

-- 8 is marauder bomber skills
elseif skillID == 8
then
	-- Set Bombing Ranges (so dont try to bomb targets too close to plane)
	rangeMin = 36
	range = 70
	
	-- Use Bombs on Buildings
	if  EGroup_ForEach(Player_GetEntities(g_Player1), Rule_Detect_Proximity_Buildings) and
		EGroup_Count("building_target") > 0 and
		Squad_BombingRun(SGroup_GetSpawnedSquadAt(squad,1), 2, EGroup_GetPosition("building_target"))
	then
		return true
	
	-- Use Bombs on Vehicles Squads
	elseif SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity_Vehicles) and
		SGroup_Count("skill_target") > 0 and
		Squad_BombingRun(SGroup_GetSpawnedSquadAt(squad,1), 2, SGroup_GetPosition("skill_target"))
	then
		return true
	
	-- Use Bombs on Infantry Squads
	elseif SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0 and
		Squad_BombingRun(SGroup_GetSpawnedSquadAt(squad,1), 1, SGroup_GetPosition("skill_target"))
	then
		return true
	end
	
	-- if bombed nothing -- Readjust Range & Attack Proximity Infantry Targets
	rangeMin = 0
	range = 35
	if SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0
	then			
		Cmd_AttackSGroup(squad, "skill_target")
		return true			
	end

-- Assassin tries to use assassinate skill
elseif skillID == 9
then
	range = 75
	
	-- Use Assassinate Ability if  Infantry Squads are in range
	if SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0 and
		Cmd_CastAbilitySelf(squad, "guard_assassin_assassinate")
	then
		return true
	
	-- Attack Proximity Infantry Targets (So assassin tries to avoid targeting vehicles)
	elseif SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0
	then			
		Cmd_AttackSGroup(squad, "skill_target")
		return true
	end

-- Basic Guardsmen Squad (Try to Capture or Target Infantry)
elseif skillID == 10
then
	range = 25
	
	-- If Morale is not Broken -- Prioritize Infantry for Attack
	if SGroup_IsMoraleBroken(squad,true) == false and
		SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity) and
		SGroup_Count("skill_target") > 0
	then
		Cmd_AttackSGroup(squad, "skill_target")
		return true
		
	-- If Morale is not Broken -- Try & Capture Unowned LPs
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		EGroup_ForEach(Player_GetEntities(g_Player1), Rule_Detect_Proximity_CapturePoints) and
		EGroup_Count("building_target") > 0
	then
		return true

	-- If Morale is not Broken -- Try & Capture World Owned LPs
	elseif SGroup_IsMoraleBroken(squad,true) == false and
		EGroup_Count("eg_world_points") > 0 and
		EGroup_ForEach("eg_world_points", Rule_Detect_Proximity_CapturePoints)
	then
		return true
	end

-- Sentinel (Target Vehicles & Buildings First)
elseif skillID == 11
then
	range = 40
	
	-- Prioritize Vehicles
	if SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Detect_Proximity_Vehicles) and
		SGroup_Count("skill_target") > 0
	then
		Cmd_AttackSGroup(squad, "skill_target")
		return true
	
	-- Prioritize Buildings
	elseif EGroup_ForEach(Player_GetEntities(g_Player1), Rule_Detect_Proximity_Buildings) and
		EGroup_Count("building_target") > 0
	then
		Cmd_AttackEGroup(squad, "building_target")
		return true
	end	
end

end


-- BASE ACTIVATION, PRODUCTION, & ATTACKS -- Rule_Create_And_Sync_Attacks() : Creates the SGroups Used & Adds all the attack Rules at the same time to sync them

-- Initial Listening Post ( One By Player Base)
	-- Rule_Production_Initial_ListeningPost() : Handles Production of Units (Guardsmen)

-- Chimera Base ( One By Convoy Spawn Location 1)
	-- Rule_Activate_Chimera_Base() : Play IE & Enable the Base to Start Producing Units
	-- Rule_Production_Chimera_Base() : Handles Production of Units (Chimeras & Guardsmen)

-- Center North Base ( One By Center HQ1)
	-- Rule_Check_EarlyPlayer_Attack_CenterNorth_Base() : Checks if the Player Attacks the Base before it has been activated
	-- Rule_Production_CenterNorth_Base() : Handles Production of Units (Basilisk & Guardsmen)

-- Center South Base ( One By CenterBase HQ2)
	-- Rule_Check_EarlyPlayer_Attack_CenterSouth_Base() : Checks if the Player Attacks the Base before it has been activated
	-- Rule_Production_CenterSouth_Base() : Handles Production of Units (Chimeras & Guardsmen)

-- Main Base
	-- Rule_Check_EarlyPlayer_Attack_Main_Base : Checks if the Player Attacks the Base before it has been activated
	-- Rule_Check_EarlyActivation_MainBase() : Check for MainBase Activation when enough major bases have been destroyed
		-- Major Bases:  CenterNorth, CenterSouth, North, & West
	-- Rule_Production_Main_Base() : Handles Production of Units (Assassin, Guardsmen w/ Leaders, Leman Russ, Hellhound, Basilisk)

-- North Base ( One by Convoy Spawn Location 5&6)
	-- Rule_Check_EarlyPlayer_Attack_North_Base() : Checks if the Player Attacks the Base before it has been activated
	-- Rule_Production_North_Base() : Handles Production of Units (Kaskrin, Ogyrns w. Priest,  & Marauder Bomber)

-- Tank Base ( One by Convoy Spawn Location 4)
	-- Rule_Activate_Tank_Base() : Play IE & Enable the Base to Start Producing Units
	-- Rule_Production_Tank_Base() : Handles Production of Units (Leman Russ Tanks)

-- Sentinel Base ( One By Convoy Spawn Location 2&3)
	-- Rule_Activate_Sentinel_Base() : Play IE & Enable the Base to Start Producing Units
	-- Rule_Production_Sentinel_Base() : Handles Production of Units (Sentinels & Guardsmen)

-- West Base ( One By Convoy Spawn Location 7)
	-- Rule_Activate_West_Base() : Play IE & Enable the Base to Start Producing Units
	-- Rule_Activate_West_Base_Patrols() : Activate the Patrols from the WestBase
	-- Rule_Production_West_Base() : Handles Production of Units (Patrols(Hellhounds or Sentinels) & Guardsmen w/ Leaders)
	-- Rule_Patrol_WestBase() : Controls the Clockwise Patroling Vehicles from WestBase

-- Creates the SGroups Used & Adds all the attack Rules at the same time to sync them function Rule_Create_And_Sync_Attacks() -- Target Location for when a squad is told to retreat (Retreat Toward Main Base HQ) g_retreat_target = Marker_GetPosition(Marker_FromName("mkr_mainBase_HQ1", "basic_marker"))

-- Default Attack Target (Changes During Mission)
g_attack_target = Marker_GetPosition(Marker_FromName("mkr_player_mainBase_HQ", "basic_marker"))

-- SGroup & EGroup used for targeting of skills
SGroup_Create("skill_target")
EGroup_Create("building_target")

--Egroup for all of the Strategic Points the World Owns
EGroup_Create("eg_world_points")

-- Egroup for Player HQ
EGroup_Create("eg_player_HQ")

--SGroups for the Spotters	
SGroup_Create("sg_spotter_HQ1")
SGroup_Create("sg_spotter_HQ2")

-- Initial LP by Player Base: Create the SGroups for Troops
for i=1,2	do
	SGroup_Create("sg_initialLP_troops"..i)
end

-- CenterNorthBase: Create the SGroups for Troops & Basilisks
SGroup_Create("sg_centerNorthBase_troops1")

for i =1,1	do
	SGroup_Create("sg_centerNorthBase_basilisk"..i)
end

-- CenterSouthBase: Create the Sgroups used for Troops & Chimeras	
for i=1,1	do
	SGroup_Create("sg_centerSouthBase_chimera"..i)
end

for i=1,3	do
	SGroup_Create("sg_centerSouthBase_troops"..i)
end

-- Chimera Base: Create the SGroups for Troops & Chimeras
for i =1,1	do
	SGroup_Create("sg_chimeraBase_troops"..i)
	SGroup_Create("sg_chimeraBase_chimera"..i)
end

-- Main Base:
--Vehicles: LemanRuss, Hellhound, & Basilisk
SGroup_Create("sg_mainBase_lemanRuss1")
SGroup_Create("sg_mainBase_hellhound1")
SGroup_Create("sg_mainBase_basilisk1")

--Troops: Guardsmen w/ Leaders & Assassin
for i =1,3	do
	SGroup_Create("sg_mainBase_troops"..i)
end	
SGroup_Create("sg_mainBase_assassin1")

-- North Base: Create the SGroups for Troops, Marauder(Bomber)
for i =1,2	do
	SGroup_Create("sg_northBase_troops"..i)
	SGroup_Create("sg_northBase_marauder"..i)
end

-- Sentinel Base: Create the SGroups for Troops & Sentinels
for i =1,2	do
	SGroup_Create("sg_sentinelBase_troops"..i)
	SGroup_Create("sg_sentinelBase_sentinel"..i)
end

-- Tank Base: Create the SGroups for LemanRuss Tanks
for i =1,2	do
	SGroup_Create("sg_tankBase_lemanRuss"..i)
end

-- WestBase: Create the SGroups for Patrols (Hellhounds & Sentinels)
	-- 7&8 Are the mech command numbers
for i =1,1	do
	SGroup_Create("sg_westBase_7_patrol"..i)
	SGroup_Create("sg_westBase_8_patrol"..i)
end

-- WestBase: Create the SGroups for Troops with Leaders
for i =1,2 do
	SGroup_Create("sg_westBase_troops"..i)
end

-- Production for the Idle Unit Bases (Won't Start Producing until all the idle units used up 
Rule_AddInterval(Rule_Production_Chimera_Base, g_timer_chimeraBase)
Rule_AddInterval(Rule_Production_Sentinel_Base, g_timer_sentinelBase)
Rule_AddInterval(Rule_Production_Tank_Base, g_timer_tankBase)

-- Sync the Production Rules for the Bases (Bases won't actually produce / attack until they activate)
Rule_AddInterval(Rule_Production_CenterNorth_Base, g_timer_centerNorthBase)
Rule_AddInterval(Rule_Production_CenterSouth_Base, g_timer_centerSouthBase)
Rule_AddInterval(Rule_Production_Initial_ListeningPost, g_timer_initialLP)
Rule_AddInterval(Rule_Production_Main_Base, g_timer_mainBase)
Rule_AddInterval(Rule_Production_North_Base, g_timer_northBase)
Rule_AddInterval(Rule_Production_West_Base, g_timer_westBase)

-- Patrols from West Base
Rule_AddInterval(Rule_Patrol_WestBase, 5)

-- SQUAD TACTICS:
Rule_AddOneShot(Rule_Squad_Tactics_Helper_One, 5)

-- Provides Some Random Movement & Life to the Bases
Rule_AddInterval(Rule_RandomMovement_Base,10)

end


-- Initial Listening Post ( One By Player Base)

-- Handles Production of Units (Guardsmen) function Rule_Production_Initial_ListeningPost() local initialLP_troopsProduced = false

-- Loop through all the possible initialLP_troop Squads
for i =1,1	do		
	-- If the SGroup is Not Currently Used...
	if initialLP_troopsProduced == false and
		SGroup_Count("sg_initialLP_troops"..i) == 0
	then
		-- Try to Produce & Upgrade a guardsmen squad from the Infantry Command
		if Rule_Produce_Guardsmen("sg_initialLP_troops"..i, "eg_convoyBase_listeningPost7", "mkr_initialLP_troops") == true
		then
			--print("initial LP -- Producing Guardsmen")
			initialLP_troopsProduced = true
			
			-- Reset Status (in case died while retreating etc...)
			g_initialLP_troops_status[i] = g_squad_produced
		end
	end
end

--if listening post is destroyed, remove rules since base is gone
if 	EGroup_Count("eg_convoyBase_listeningPost7") == 0
then
	Rule_Remove(Rule_Production_Initial_ListeningPost)
end

end


-- Chimera Base ( One By Convoy Spawn Location 1)

-- Play IE & Enable the Base to Start Producing Units function Rule_Activate_Chimera_Base() -- Activate Base if not already active if g_base_activated_Chimera == false then -- base is now activated g_base_activated_Chimera = true

	-- Play IE:  Chimera Bases out of idle vehicles, start real production
	Util_StartIntel(EVENTS.IE_Idle_Chimera_Base_Out_Of_Units)
end

end

-- Handles Production of Units (Chimeras & Guardsmen) function Rule_Production_Chimera_Base() -- Track when & what squads of Chimeras & Guardsmen are produced local chimeraBase_troopsProduced = false local chimeraBase_chimeraProduced = false local troopProduced = 0 local chimeraProduced = 0

-- Loop through all the possible chimeraBase_troop Squads
for i =1,1	do
	-- If the SGroup is Not Currently Used (& Base Activated)...
	if g_base_activated_Chimera == true and
		chimeraBase_troopsProduced == false and
		SGroup_Count("sg_chimeraBase_troops"..i) == 0
	then
		-- Try to Produce & Upgrade a guardsmen squad from the Infantry Command
		if Rule_Produce_Guardsmen("sg_chimeraBase_troops"..i, "eg_convoyBase_infantryCommand5", "mkr_convoyBase_infantryCommand5") == true
		then
			--print("Chimera Base -- Producing Guardsmen")
			chimeraBase_troopsProduced = true
			troopProduced = i
			
			-- Reset Status (in case died while retreating etc...)
			g_chimeraBase_troops_status[i] = g_squad_produced
		end
	end
end

-- Loop through all the possible chimeraBase_chimera Squads
for i =1,1	do
	-- If the SGroup is not currently used (& Base Activated)...
	if g_base_activated_Chimera == true and
		chimeraBase_chimeraProduced == false and
		SGroup_Count("sg_chimeraBase_chimera"..i) == 0
	then
		-- Try to Produce a chimera from the mechanizedCommand
		if Rule_Produce_Chimera("sg_chimeraBase_chimera"..i, "eg_convoyBase_mechanizedCommand1", "mkr_convoyBase_mechanizedCommand1") == true
		then
			--print("Chimera Base -- Producing chimera")
			chimeraBase_chimeraProduced = true
			chimeraProduced = i
			
			g_chimeraBase_chimera_status[i] = g_squad_loading				
		end
	end
end

-- if both troops & transport exist...
if chimeraBase_troopsProduced == true and
	chimeraBase_chimeraProduced == true
then
	-- load the troops into the transport (& set chimera status to loading to buy time before sending in)
	Cmd_EnterTransport("sg_chimeraBase_troops"..troopProduced, "sg_chimeraBase_chimera"..chimeraProduced)
	g_chimeraBase_chimera_status[chimeraProduced] = g_squad_loading	
	g_chimeraBase_troops_status[troopProduced] = g_squad_loading	
end

--if both barracks & mechanized command  are destroyed, remove rules since base is gone
if 	EGroup_Count("eg_convoyBase_infantryCommand5") == 0 and
	EGroup_Count("eg_convoyBase_mechanizedCommand1") == 0
then
	Rule_Remove(Rule_Production_Chimera_Base)
	
	-- In case the buildings are destroyed before all the idle chimeras
	Rule_Remove(Rule_Activate_Chimera_Base)
end

end

-- Center North Base ( One By Center HQ1)

-- Checks if the Player Attacks the Base before it has been activated function Rule_Check_EarlyPlayer_Attack_CenterNorth_Base() -- Checks if the Base is already activated if g_base_activated_CenterNorth == false then -- if not...Check if the Player is attacking the base if Player_AreSquadsNearMarker(g_Player1, "mkr_centerNorthBase_underAttack") then -- Count How many play units are at that marker Player_GetAllSquadsNearMarker(g_Player1, "sg_NearMarker", "mkr_centerNorthBase_underAttack") local unitCount = SGroup_Count("sg_NearMarker")

		--is it enough units to activate a base?
		if unitCount >= g_num_PlayerUnits_ActivateBase
		then
			-- Activate the North Base Instantly
			g_base_activated_CenterNorth = true
		end
	end

-- Remove the Rule since the base is already activated
else
	Rule_Remove(Rule_Check_EarlyPlayer_Attack_CenterNorth_Base)
end

end

-- Handles Production of Units (Basilisk & Guardsmen) function Rule_Production_CenterNorth_Base() local centerNorthBase_troopsProduced = false local centerNorthBase_vehicleProduced = false

-- Loop through all the possible centerNorthBase_troop Squads
for i =1,1	do
	-- If the SGroup is Not Currently Used...
	if g_base_activated_CenterNorth == true and 
		centerNorthBase_troopsProduced == false and
		SGroup_Count("sg_centerNorthBase_troops"..i) == 0
	then
		-- Try to Produce & Upgrade a guardsmen squad from the Infantry Command
		if Rule_Produce_Guardsmen("sg_centerNorthBase_troops"..i, "eg_centerBase_infantryCommand1", "mkr_centerBase_infantryCommand1") == true
		then
			--print("centerNorthBase -- Producing Guardsmen")
			centerNorthBase_troopsProduced = true
			
			-- Reset Status (in case died while retreating etc...)
			g_centerNorthBase_troops_status[i] = g_squad_produced
		end
	end
end

-- Loop through all the possible centerNorthBase_basilisk Squads
for i =1,1	do
	-- If the SGroup is not currently used...
	if g_base_activated_CenterNorth == true and
		centerNorthBase_vehicleProduced == false and
		SGroup_Count("sg_centerNorthBase_basilisk"..i) == 0
	then
		-- Try to Produce a Basilisk from the mechanizedCommand
		if Rule_Produce_Basilisk("sg_centerNorthBase_basilisk"..i, "eg_centerBase_mechanizedCommand1", "mkr_centerBase_mechanizedCommand1") == true
		then
			--print("centerNorthBase -- Producing Basilisk")
			centerNorthBase_vehicleProduced = true
			
			-- Reset Status (in case died while retreating etc...)
			g_centerNorthBase_basilisk_status[i] = g_squad_produced
		end
	end
end

--if all barracks & mechanized command  are destroyed, remove rules since base is gone
if 	EGroup_Count("eg_centerBase_infantryCommand1") == 0 and
	EGroup_Count("eg_centerBase_mechanizedCommand1") == 0
then
	-- Increment Count Until Main Base Activates
	g_bases_count_mainBase_activates = g_bases_count_mainBase_activates + 1
	
	Rule_Remove(Rule_Production_CenterNorth_Base)
end

end

-- Center South Base ( One By CenterBase HQ2)

-- Checks if the Player Attacks the Base before it has been activated function Rule_Check_EarlyPlayer_Attack_CenterSouth_Base() -- Checks if the Base is already activated if g_base_activated_CenterSouth == false then -- if not...Check if the Player is attacking the base if Player_AreSquadsNearMarker(g_Player1, "mkr_centerSouthBase_underAttack") then -- Count How many play units are at that marker Player_GetAllSquadsNearMarker(g_Player1, "sg_NearMarker", "mkr_centerSouthBase_underAttack") local unitCount = SGroup_Count("sg_NearMarker")

		--is it enough units to activate a base?
		if unitCount >= g_num_PlayerUnits_ActivateBase
		then
			-- Activate the South Base Instantly
			g_base_activated_CenterSouth = true
		end
	end

-- Remove the Rule since the base is already activated
else
	Rule_Remove(Rule_Check_EarlyPlayer_Attack_CenterSouth_Base)
end

end

-- Handles Production of Units (Chimeras & Guardsmen) function Rule_Production_CenterSouth_Base() -- Track when & what squads of Chimeras & Guardsmen are produced local centerSouthBase_chimeraProduced = false local centerSouthBase_troopsProduced = false local chimeraProduced = 0 local troopProduced = 0

-- Loop through all the possible chimeraBase_chimera Squads
for i =1,1 do
	-- If the SGroup is not currently used...
	if g_base_activated_CenterSouth == true and
		centerSouthBase_chimeraProduced == false and
		SGroup_Count("sg_centerSouthBase_chimera"..i) == 0
	then
		-- Try to Produce a chimera from the mechanizedCommand
		if Rule_Produce_Chimera("sg_centerSouthBase_chimera"..i, "eg_centerBase_mechanizedCommand2", "mkr_centerBase_mechanizedCommand2") == true
		then
			--print("centerSouthBase -- Producing chimera")
			centerSouthBase_chimeraProduced = true
			chimeraProduced = i
			
			--Set Status to Produced (Changes to Loaded if troops put in)
			g_centerSouthBase_chimera_status[i] = g_squad_produced				
		end
	end
end

-- Loop through all the Infantry Commands
for j = 2,4 do
	centerSouthBase_troopsProduced = false
	
	-- if the infantry Command still exists
	if EGroup_Count("eg_centerBase_infantryCommand"..j) == 1 and
		g_base_activated_CenterSouth == true
	then
		-- Loop through all the possible centerSouthBase_troop Squads
		for i =1, g_num_chimera_troops
		do
			-- If the SGroup is Not Currently Used...
			if centerSouthBase_troopsProduced == false and
				SGroup_Count("sg_centerSouthBase_troops"..i) == 0
			then
				-- Try to Produce & Upgrade a guardsmen squad from the Infantry Command
				if Rule_Produce_Guardsmen("sg_centerSouthBase_troops"..i, "eg_centerBase_infantryCommand"..j, "mkr_centerBase_infantryCommand"..j) == true
				then
					--print("centerSouthBase -- Producing Guardsmen")
					centerSouthBase_troopsProduced = true
					troopProduced = i
					
					-- Reset Status (in case died while retreating etc...)
					g_centerSouthBase_troops_status[i] = g_squad_produced
					
					-- if both troops & transport exist...
					if centerSouthBase_troopsProduced == true and
						centerSouthBase_chimeraProduced == true
					then
						-- load the troops into the transport(& set chimera status to loading to buy time before sending in)
						Cmd_EnterTransport("sg_centerSouthBase_troops"..troopProduced, "sg_centerSouthBase_chimera"..chimeraProduced)
						g_centerSouthBase_chimera_status[chimeraProduced] =  g_squad_loading
						g_centerSouthBase_troops_status[troopProduced] = g_squad_loading
					end
				end
			end
		end
	end
end

--if both barracks & mechanized command are destroyed, remove rules since base is gone
if 	EGroup_Count("eg_centerBase_infantryCommand2") == 0 and
	EGroup_Count("eg_centerBase_infantryCommand3") == 0 and
	EGroup_Count("eg_centerBase_infantryCommand4") == 0 and
	EGroup_Count("eg_centerBase_mechanizedCommand2") == 0
then
	-- Increment Count Until Main Base Activates
	g_bases_count_mainBase_activates = g_bases_count_mainBase_activates + 1
	
	Rule_Remove(Rule_Production_CenterSouth_Base)
end

end


-- Main Base

-- Checks if the Player Attacks the Base before it has been activated function Rule_Check_EarlyPlayer_Attack_Main_Base() -- Checks if the Base is already activated if g_base_activated_Main == false then -- if not...Check if the Player is attacking the base if Player_AreSquadsNearMarker(g_Player1, "mkr_mainBase_underAttack") then -- Count How many play units are at that marker Player_GetAllSquadsNearMarker(g_Player1, "sg_NearMarker", "mkr_mainBase_underAttack") local unitCount = SGroup_Count("sg_NearMarker")

		--is it enough units to activate a base? (& are we past alert level three at least since dont want player activating really early by mistake)
		if unitCount >= g_num_PlayerUnits_ActivateBase and
			g_currentAlertStatus >= 3
		then
			-- Activate the Main Base
			g_base_activated_Main = true				
		end
	end

-- Remove the Rule since the base is already activated
else
	Rule_Remove(Rule_Check_EarlyPlayer_Attack_Main_Base)
end

end

-- Check for MainBase Activation when enough major bases have been destroyed -- Major Bases: CenterNorth, CenterSouth, North, & West function Rule_Check_EarlyActivation_MainBase() -- Checks if the Base is already activated if g_base_activated_Main == false then -- If enough major bases have been destroyed if g_bases_count_mainBase_activates >= g_bases_before_mainBase_activates then -- Activate the Main Base g_base_activated_Main = true end

-- Remove the Rule since the base is already activated
else
	Rule_Remove(Rule_Check_EarlyActivation_MainBase)
end

end

-- Handles Production of Units (Assassin, Guardsmen w/ Leaders, Leman Russ, Hellhound, Basilisk) function Rule_Production_Main_Base() -- Loop through all the Mech Commands for j = 1,2 do -- if the mech Command still exists & base activated if EGroup_Count("eg_mainBase_mechanizedCommand"..j) == 1 and g_base_activated_Main == true then -- If Leman Russ Doesn't Exist if SGroup_Count("sg_mainBase_lemanRuss1") == 0 then Rule_Produce_LemanRuss("sg_mainBase_lemanRuss1", "eg_mainBase_mechanizedCommand"..j, "mkr_mainBase_mechanizedCommand"..j) g_mainBase_lemanRuss_status[1] = g_squad_produced

		-- If Hellhound doesn't exist
		elseif SGroup_Count("sg_mainBase_hellhound1") == 0
		then
			Rule_Produce_Hellhound("sg_mainBase_hellhound1", "eg_mainBase_mechanizedCommand"..j, "mkr_mainBase_mechanizedCommand"..j)
			g_mainBase_hellhound_status[1] = g_squad_produced
		
		-- If Basilisk doesn't exist
		elseif SGroup_Count("sg_mainBase_basilisk1") == 0
		then
			Rule_Produce_Basilisk("sg_mainBase_basilisk1", "eg_mainBase_mechanizedCommand"..j, "mkr_mainBase_mechanizedCommand"..j)
			g_mainBase_basilisk_status[1] = g_squad_produced
		end
	end
end

-- Loop through all the Infantry Commands (Produces 3 squads max)
for j = 1,6 do
	-- Track when & what squads of Guardsmen are produced
	local mainBase_troopsProduced = false
	
	-- if the infantry Command still exists & base activated
	if EGroup_Count("eg_mainBase_infantryCommand"..j) == 1 and
		g_base_activated_Main == true
	then
		for i =1,3 do
			-- If the SGroup is Not Currently Used...
			if 	g_base_activated_Main == true and
				mainBase_troopsProduced == false and
				SGroup_Count("sg_mainBase_troops"..i) == 0
			then
				-- Try to Produce & Upgrade a guardsmen squad from the Infantry Command
				if Rule_Produce_Guardsmen("sg_mainBase_troops"..i, "eg_mainBase_infantryCommand"..j, "mkr_mainBase_infantryCommand"..j) == true
				then
					--print("mainBase -- Producing Guardsmen")
					mainBase_troopsProduced = true
			
					-- Reset Status (in case died while retreating etc...)
					g_mainBase_troops_status[i] = g_squad_produced
			
					-- Add Leader to Squad if the HQ is Still Alive
					if EGroup_Count("eg_HQInMainBase_Objective") == 0
					then
						-- Do Nothing: HQ is Destroyed
					elseif g_leaders_enabled == false
					then
						-- Do Nothing: Leaders not enabled yet
					elseif i == 1
					then
						-- Create Commisar
						Util_CreateSquadsAtMarker(g_Player2, "sg_mainBase_leader", "guard_squad_commissar", "mkr_mainBase_HQ1", 1)
						Cmd_AttachSquads("sg_mainBase_troops"..i, "sg_mainBase_leader")
						SGroup_Clear("sg_mainBase_leader")	
					elseif i == 2
					then
						-- Create Psyker
						Util_CreateSquadsAtMarker(g_Player2, "sg_mainBase_leader", "guard_squad_psyker", "mkr_mainBase_HQ1", 1)
						Cmd_AttachSquads("sg_mainBase_troops"..i, "sg_mainBase_leader")
						SGroup_Clear("sg_mainBase_leader")
					else
						-- Create Priest
						Util_CreateSquadsAtMarker(g_Player2, "sg_mainBase_leader", "guard_squad_priest", "mkr_mainBase_HQ1", 1)
						Cmd_AttachSquads("sg_mainBase_troops"..i, "sg_mainBase_leader")
						SGroup_Clear("sg_mainBase_leader")	
					end
				end
			end
		end
	end
end

-- If Assassin is Dead (& HQ is alive)
if SGroup_Count("sg_mainBase_assassin1") == 0 and
	g_base_activated_Main == true and
	Rule_Produce_Assassin("sg_mainBase_assassin1", "eg_HQInMainBase_Objective", "mkr_mainBase_HQ1") == true
then
	-- Reset Status (in case died while retreating etc...)
	g_mainBase_assassin_status[1] = g_squad_produced
end

--if all barracks, mechanized commands, & HQ are destroyed, remove rules since base is gone
if 	EGroup_Count("eg_mainBase_mechanizedCommand1") == 0 and
	EGroup_Count("eg_mainBase_mechanizedCommand2") == 0 and
	EGroup_Count("eg_mainBase_infantryCommand1") == 0 and
	EGroup_Count("eg_mainBase_infantryCommand2") == 0 and
	EGroup_Count("eg_mainBase_infantryCommand3") == 0 and
	EGroup_Count("eg_mainBase_infantryCommand4") == 0 and
	EGroup_Count("eg_mainBase_infantryCommand5") == 0 and
	EGroup_Count("eg_mainBase_infantryCommand6") == 0 and
	EGroup_Count("eg_HQInMainBase_Objective") == 0
then
	Rule_Remove(Rule_Production_Main_Base)
end

end


-- North Base ( One By Convoy Spawn Location 5&6)

-- Checks if the Player Attacks the Base before it has been activated function Rule_Check_EarlyPlayer_Attack_North_Base() -- Checks if the Base is already activated if g_base_activated_North == false then -- if not...Check if the Player is attacking the base if Player_AreSquadsNearMarker(g_Player1, "mkr_northBase_underAttack") then -- Count How many play units are at that marker Player_GetAllSquadsNearMarker(g_Player1, "sg_NearMarker", "mkr_northBase_underAttack") local unitCount = SGroup_Count("sg_NearMarker")

		--is it enough units to activate a base?
		if unitCount >= g_num_PlayerUnits_ActivateBase
		then
			-- Activate the North Base Instantly
			g_base_activated_North = true				
			Rule_AddInterval(Rule_StopBomberProduction_Objective,5)
		end
	end

-- Remove the Rule since the base is already activated
else
	Rule_Remove(Rule_Check_EarlyPlayer_Attack_North_Base)
end

end

-- Handles Production of Units (Kaskrin w/ Priest, Ogyrns w/ Priest, & Marauder Bombers) function Rule_Production_North_Base() -- Track when & what squads of marauders & Guardsmen are produced local northBase_marauderProduced = false local northBase_troopsProduced = false

-- Loop through all the Mech Commands
for j = 5,6 do
	northBase_marauderProduced = false
	
	-- if the mech Command still exists & base activated
	if EGroup_Count("eg_convoyBase_mechanizedCommand"..j) == 1 and
		g_base_activated_North == true
	then
		-- Loop through all the possible sg_northBase_marauder Squads
		for i =1,2	do
			-- If the SGroup is not currently used...Try to Produce a Marauder Bomber
			if northBase_marauderProduced == false and
				SGroup_Count("sg_northBase_marauder"..i) == 0 and
				Rule_Produce_Marauder("sg_northBase_marauder"..i, "eg_convoyBase_mechanizedCommand"..j, "mkr_convoyBase_mechanizedCommand"..j) == true					
			then
				--print("northBase -- Producing Marauder")
				northBase_marauderProduced = true
				
				-- Reset Status (in case died while retreating etc...)
				g_northBase_marauder_status[i] = g_squad_produced						
			end
		end
	end
end

-- Loop through all the Infantry Commands
for j = 6,7 do
	northBase_troopsProduced = false
	
	-- if the infantry Command still exists & base activated
	if EGroup_Count("eg_convoyBase_infantryCommand"..j) == 1 and
		g_base_activated_North == true
	then
		-- Loop through all the possible northBase_troop Squads
		for i =1,2	do
			-- If the SGroup is Not Currently Used...
			if northBase_troopsProduced == false and
				SGroup_Count("sg_northBase_troops"..i) == 0
			then
				-- Produce & Upgrade a kaskrin squad from IC1 (or ogryn squad from IC2 )
				if i ==1
				then
					Rule_Produce_Kasrkin("sg_northBase_troops"..i, "eg_convoyBase_infantryCommand"..j, "mkr_convoyBase_infantryCommand"..j)
					
					-- Add Leader to Squad if the HQ is Still Alive
					if EGroup_Count("eg_convoyBase_HQ1") == 1 and
						g_leaders_enabled == true
					then
						-- Create Priest & Attach to Kaskrin Squad
						Util_CreateSquadsAtMarker(g_Player2, "sg_northBase_leader", "guard_squad_priest", "mkr_convoyBase_HQ1", 1)
						Cmd_AttachSquads("sg_northBase_troops"..i, "sg_northBase_leader")
						SGroup_Clear("sg_northBase_leader")
					end
				else 
					Rule_Produce_Ogryn("sg_northBase_troops"..i, "eg_convoyBase_infantryCommand"..j, "mkr_convoyBase_infantryCommand"..j)
					
					-- Add Leader to Squad if the HQ is Still Alive
					if EGroup_Count("eg_convoyBase_HQ1") == 1 and
						g_leaders_enabled == true
					then
						-- Create Priest & Attach to Ogyrn Squad
						Util_CreateSquadsAtMarker(g_Player2, "sg_northBase_leader", "guard_squad_priest", "mkr_convoyBase_HQ1", 1)
						Cmd_AttachSquads("sg_northBase_troops"..i, "sg_northBase_leader")
						SGroup_Clear("sg_northBase_leader")
					end
				end
				
				--print("northBase -- Producing Troops")
				northBase_troopsProduced = true
				
				-- Reset Status (in case died while retreating etc...)
				g_northBase_troops_status[i] = g_squad_produced
			end
		end
	end
end

--if all barracks & mechanized commands are destroyed, remove rules since base is gone
if 	EGroup_Count("eg_convoyBase_infantryCommand6") == 0 and
	EGroup_Count("eg_convoyBase_infantryCommand7") == 0 and
	EGroup_Count("eg_convoyBase_mechanizedCommand5") == 0 and
	EGroup_Count("eg_convoyBase_mechanizedCommand6") == 0
then
	-- Increment Count Until Main Base Activates
	g_bases_count_mainBase_activates = g_bases_count_mainBase_activates + 1
	
	-- Make sure WestBase is activated (In case player destroys North Base while in Alert Level 3)
	g_base_activated_West = true
	
	Rule_Remove(Rule_Production_North_Base)
end

end


-- Tank Base ( One By Convoy Spawn Location 4) -- These are pretty much useless rules since odds that the player destroys all idle tanks without destroying the base are slim

-- Play IE & Enable the Base to Start Producing Units function Rule_Activate_Tank_Base() -- Activate Base if Not already active (& if the mechanized command still exists) if g_base_activated_Tank == false and EGroup_Count("eg_convoyBase_mechanizedCommand4") == 1 then -- base is now activated g_base_activated_Tank = true

	-- Play IE
	Util_StartIntel(EVENTS.IE_Idle_Tank_Base_Out_Of_Units)
end

end

-- Handles Production of Units (Leman Russ Tanks) function Rule_Production_Tank_Base() local tankBase_troopsProduced = false

-- Mech Command Still Exists & Base is Activated
if EGroup_Count("eg_convoyBase_mechanizedCommand4") == 1 and
	g_base_activated_Tank == true
then
	-- Loop through all tank sgroups
	for i =1,2	do
		-- If the SGroup is Not Currently Used...
		if tankBase_troopsProduced == false and
			SGroup_Count("sg_tankBase_lemanRuss"..i) == 0
		then
			-- Try to Produce LemanRuss Tank
			if Rule_Produce_LemanRuss("sg_tankBase_lemanRuss"..i, "eg_convoyBase_mechanizedCommand4", "mkr_convoyBase_mechanizedCommand4") == true
			then
				--print("tankBase -- Producing LemanRuss")
				tankBase_troopsProduced = true
				
				-- Reset Status (in case died while retreating etc...)
				g_tankBase_tank_status[i] = g_squad_produced
			end
		end
	end
end		

-- All Mech Commands are destroyed...Remove Rules since Base is dead
if EGroup_Count("eg_convoyBase_mechanizedCommand4") == 0
then
	Rule_Remove(Rule_Production_Tank_Base)
	
	-- In case the mech command is destroyed before all the idle tanks
	Rule_Remove(Rule_Activate_Tank_Base)
end

end


-- Sentinel Base ( One By Convoy Spawn Location 2&3) -- These are pretty much useless rules since odds that the player destroys all idle sentinels without destroying the base are slim

-- Play IE & Enable the Base to Start Producing Units function Rule_Activate_Sentinel_Base() -- Activate Base if Not already active if g_base_activated_Sentinel == false then -- base is now activated g_base_activated_Sentinel = true

	-- Play IE : 
	Util_StartIntel(EVENTS.IE_Idle_Sentinel_Base_Out_Of_Units)
end

end

-- Handles Production of Units (Sentinels & Guardsmen) function Rule_Production_Sentinel_Base() -- Loop through sentinelBase infantryCommands: for j = 3,4 do -- Confirm the Barrack still exists (& Base is Active) if EGroup_Count("eg_convoyBase_infantryCommand"..j) == 1 and g_base_activated_Sentinel == true then -- Track if able to Produce a Squad of Guardsmen for the Barracks sentinelBase_troopsProduced = false

		-- Loop through all the possible sentinelBase_troop Squads
		for i =1,2	do
			-- If the SGroup is Not Currently Used...
			if sentinelBase_troopsProduced == false and
				SGroup_Count("sg_sentinelBase_troops"..i) == 0
			then
				-- Try to Produce & Upgrade a guardsmen squad from the Infantry Command
				if Rule_Produce_Guardsmen("sg_sentinelBase_troops"..i, "eg_convoyBase_infantryCommand"..j, "mkr_convoyBase_infantryCommand"..j) == true
				then
					-- Reset Status (in case died while retreating etc...)
					g_sentinelBase_troops_status[i] = g_squad_produced
				
					--print("Sentinel Base -- Producing Guardsmen")
					sentinelBase_troopsProduced = true
				end
			end
		end
	end
end

-- Loop through sentinelBase mechanizedCommands:
for j = 2,3 do
	-- Confirm the mechanizedCommand still exist
	if EGroup_Count("eg_convoyBase_mechanizedCommand"..j) == 1 and
		g_base_activated_Sentinel == true
	then
		-- Track if able to Produce a Sentinel
		sentinelBase_sentinelProduced = false
		
		-- Loop through all the possible sentinelBase_sentinel Squads
		for i =1,2	do
			-- If the SGroup is not currently used...
			if sentinelBase_sentinelProduced == false and
				SGroup_Count("sg_sentinelBase_sentinel"..i) == 0
			then
				-- Try to Produce a sentinel from the mechanizedCommand
				if Rule_Produce_Sentinel("sg_sentinelBase_sentinel"..i, "eg_convoyBase_mechanizedCommand"..j, "mkr_convoyBase_mechanizedCommand"..j) == true
				then
					--print("Sentinel Base -- Producing Sentinel")
					sentinelBase_sentinelProduced = true
					
					-- Reset Status (in case died while retreating etc...)
					g_sentinelBase_sentinel_status[i] = g_squad_produced
				end
			end
		end
	end
end

--if all barracks & mechanized command  are destroyed, remove rules since base is gone
if 	EGroup_Count("eg_convoyBase_infantryCommand3") == 0 and
	EGroup_Count("eg_convoyBase_infantryCommand4") == 0 and
	EGroup_Count("eg_convoyBase_mechanizedCommand2") == 0 and
	EGroup_Count("eg_convoyBase_mechanizedCommand3") == 0
then
	Rule_Remove(Rule_Production_Sentinel_Base)
	
	-- In case base is destroyed before all idle sentinels are destroyed
	Rule_Remove(Rule_Activate_Sentinel_Base)
end

end

-- West Base ( One By Convoy Spawn Location 7)

-- Play IE & Enable the Base to Start Producing Units function Rule_Activate_West_Base() -- Activate Base if Not already active if g_base_activated_West == false then -- base is now activated g_base_activated_West = true end end

-- Activate the Patrols from the WestBase function Rule_Activate_West_Base_Patrols() -- Activate the Patrols from the Base if Not already active if g_base_activated_West_Patrol == false then -- base is now activated g_base_activated_West_Patrol = true end end

-- Handles Production of Units (Patrols(Hellhounds or Sentinels) & Guardsmen w/ Leaders) function Rule_Production_West_Base() local westBase_troopsProduced = false

-- Loop through all the possible westBase_troop Squads
for i =1,2	do
	-- If the SGroup is Not Currently Used...
	if 	g_base_activated_West == true and
		westBase_troopsProduced == false and
		SGroup_Count("sg_westBase_troops"..i) == 0
	then
		-- Try to Produce & Upgrade a guardsmen squad from the Infantry Command
		if Rule_Produce_Guardsmen("sg_westBase_troops"..i, "eg_convoyBase_infantryCommand2", "mkr_convoyBase_infantryCommand2") == true
		then
			westBase_troopsProduced = true
			
			-- Reset Status (in case died while retreating etc...)
			g_westBase_troops_status[i] = g_squad_produced
			
			-- Add Leader to Squad if the HQ is Still Alive
			if EGroup_Count("eg_convoyBase_HQ2") == 1 and
				g_leaders_enabled == true and
				i == 1
			then
				-- Create Commisar
				Util_CreateSquadsAtMarker(g_Player2, "sg_westBase_leader", "guard_squad_commissar", "mkr_convoyBase_HQ2", 1)
				Cmd_AttachSquads("sg_westBase_troops"..i, "sg_westBase_leader")
				SGroup_Clear("sg_westBase_leader")
			
			elseif EGroup_Count("eg_convoyBase_HQ2") == 1 and
				g_leaders_enabled == true and
				i == 2
			then
				-- Create Psyker
				Util_CreateSquadsAtMarker(g_Player2, "sg_westBase_leader", "guard_squad_psyker", "mkr_convoyBase_HQ2", 1)
				Cmd_AttachSquads("sg_westBase_troops"..i, "sg_westBase_leader")
				SGroup_Clear("sg_westBase_leader")		
			end
		end
	end
end

--Loop through all Mech Commands & if still exists...
for j =7,8 do
	westBase_troopsProduced = false

	-- Try to Produce Patroling Vehicles if activated & Mech Commands Still Alive
	if EGroup_Count("eg_convoyBase_mechanizedCommand"..j) == 1 and
		g_base_activated_West_Patrol == true and
		g_base_activated_West == true
	then
		-- Loop through all the possible westBase_patrol Squads
		for i =1,1	do
			-- If the SGroup is Not Currently Used...
			if westBase_troopsProduced == false and
				SGroup_Count("sg_westBase_"..j.."_patrol"..i) == 0
			then
				westBase_troopsProduced = true
				
				-- Pick Sentinel or Hellhound
				local produceWhat = World_GetRand(0, g_currentAlertStatus)
		
				-- This will mean that only Sentinels are produced in Alert 0 & 1, and then random after alert 2
				if produceWhat <= 1
				then
					-- Produce a Sentinel from the Mechanized Command
					Rule_Produce_Sentinel("sg_westBase_"..j.."_patrol"..i, "eg_convoyBase_mechanizedCommand"..j, "mkr_convoyBase_mechanizedCommand"..j)
				else
					-- Produce a Hellhound from the Mechanized Command
					Rule_Produce_Hellhound("sg_westBase_"..j.."_patrol"..i, "eg_convoyBase_mechanizedCommand"..j, "mkr_convoyBase_mechanizedCommand"..j)
				end
				
				-- Order Patrol Squad to First Patrol Point
				Cmd_AttackMoveMarker("sg_westBase_"..j.."_patrol"..i, "mkr_westBase_Patrol1")
			end
		end
	end
end

--if all barracks & mechanized commands are destroyed, remove rules since base is gone
if 	EGroup_Count("eg_convoyBase_infantryCommand2") == 0 and
	EGroup_Count("eg_convoyBase_mechanizedCommand7") == 0 and
	EGroup_Count("eg_convoyBase_mechanizedCommand8") == 0
then
	-- Increment Count Until Main Base Activates
	g_bases_count_mainBase_activates = g_bases_count_mainBase_activates + 1
	
	Rule_Remove(Rule_Production_West_Base)
end

end

-- Controls the Clockwise Patroling Vehicles from WestBase function Rule_Patrol_WestBase() for j =7,8 do -- If the Squad is Killed if SGroup_Exists("sg_westBase_"..j.."patrol1") and SGroup_Count("sg_westBase"..j.."_patrol1") == 0 then -- Unit is Dead, Do Nothing, since production is handled differently

	-- Check if the Squad arrived at the Patrol Location 1
	elseif SGroup_Exists("sg_westBase_"..j.."_patrol1") and
		Prox_AllSquadsNearMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol1")
	then
		-- Task to Next Patrol Point
		Cmd_AttackMoveMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol7")

	-- Check if the Squad arrived at the Patrol Location 7
	elseif SGroup_Exists("sg_westBase_"..j.."_patrol1") and
		Prox_AllSquadsNearMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol7")
	then
		-- Task to Next Patrol Point
		Cmd_AttackMoveMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol6")	

	-- Check if the Squad arrived at the Patrol Location 6
	elseif SGroup_Exists("sg_westBase_"..j.."_patrol1") and
		Prox_AllSquadsNearMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol6")
	then
		-- Task to Next Patrol Point
		Cmd_AttackMoveMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol5")

	-- Check if the Squad arrived at the Patrol Location 5
	elseif SGroup_Exists("sg_westBase_"..j.."_patrol1") and
		Prox_AllSquadsNearMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol5")
	then
		-- Task to Next Patrol Point
		Cmd_AttackMoveMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol4")

	-- Check if the Squad arrived at the Patrol Location 4
	elseif SGroup_Exists("sg_westBase_"..j.."_patrol1") and
		Prox_AllSquadsNearMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol4")
	then
		-- Task to Next Patrol Point
		Cmd_AttackMoveMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol3")		

	-- Check if the Squad arrived at the Patrol Location 3
	elseif SGroup_Exists("sg_westBase_"..j.."_patrol1") and
		Prox_AllSquadsNearMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol3")
	then
		-- Task to Next Patrol Point
		Cmd_AttackMoveMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol2")		
	
	-- Check if the Squad arrived at the Patrol Location 2
	elseif SGroup_Exists("sg_westBase_"..j.."_patrol1") and
		Prox_AllSquadsNearMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol2")
	then
		-- Task to Next Patrol Point
		Cmd_AttackMoveMarker("sg_westBase_"..j.."_patrol1", "mkr_westBase_Patrol1")		
	end
end

end

-- END OF ALL " BASE ACTIVATION, PRODUCTION, & ATTACKS " RULES


-- CONVOY SPAWNING, PATHING, & UPGRADING -- SPAWNNG : Spawn in a new convoy from the correct place -- Rule_Spawn_First_Convoy() : Play IE, Set up the spawning of the first convoy & adds the objective to stop the convoys -- Pick_Convoy_Spawn_Location : Picks Same Convoy Location Until it is destroyed -- function returns to "g_spawnLocation =" -- Rule_Spawn_New_Convoy() : Spawn in a convoy & task to first location

-- PATHING : Controls Sending the Convoy to the Next Checkpoint along their routes
	-- Rule_Convoy_Path_Zero() : 18,1,2,4
	-- Rule_Convoy_Path_One() : 17,6,5,3,4
	-- Rule_Convoy_Path_Two() : 1,2,4
	-- Rule_Convoy_Path_Two_A() : 12 to 1 (then follows path two)
	-- Rule_Convoy_Path_Two_B() : 13 to 1 (then follows path two)
	-- Rule_Convoy_Path_Three() : 11,2,4
	-- Rule_Convoy_Path_Four() : 7,8,9,10
	-- Rule_Convoy_Path_Four_A() : 15 to 7 (then follows path four)
	-- Rule_Convoy_Path_Four_B() : 16 to 7 (then follows path two)
	-- Rule_Convoy_Path_Five() : 14,3,4
	-- Rule_Convoy_Reached_Mars_Command() : Convoy has reached the Mars Command -- Increment Baneblade counter, reset timer & prepare for next convoy to spawn

-- EXTRA CONVOY RULES
	-- Rule_Update_Baneblade_Counter() : Update the Baneblade counter & produces the baneblades when the counter hits 0
	-- Rule_Convoy_Spawn_Warning( ) : Controls the OnScreen Countdown Timer until Next Convoy Spawns
	-- Rule_Check_For_Convoy_Destruction() : Checks if a convoy is destroyed before it reaches the mars command building


-- CONVOY SPAWNING

-- Play IE, Set up the spawning of the first convoy & adds the objective to stop the convoys function Rule_Spawn_First_Convoy() -- Play IE Util_StartIntel(EVENTS.IE_Convoy_FirstMechanized)

-- Assign Sub-Objective Regarding Mars Command Building Objective & Stopping Convoys
Rule_AddInterval(Rule_DestroyMarsPatternCommand_Objective, 1)

-- Set the Counter for Baneblade Production to the maximum number needed
g_convoy_currentNumberForBaneBlade = g_convoy_maxNumberForBaneBlade

-- Show the Counter until the Baneblade is produced
UI_ShowCountDXP("Baneblade_Counter_Ui", g_Player1, 3950194, g_convoy_currentNumberForBaneBlade )

-- So the Player can see the Transport Convoys (convoy is the only unit belonging to AI: g_Player4)
--World_EnablePlayerToPlayerFOW(g_Player1, g_Player4, false)

-- So game knows to assign the Objective the first time a convoy reaches the Mars Pattern Building
g_MarsPatternObjective_Assigned = false

-- So Normal Convoy Spawn IE doesn't play the first time
g_firstConvoy_Spawned = false

-- Make Sure the Player didn't manage to somehow destroy the first Mechanized Command (should be impossible unless badly adjusted timers
if EGroup_Count("eg_convoyBase_mechanizedCommand1") == 1
then
	-- Tell the Convoy to Use Location One
	g_spawnLocation = 1
else
	g_spawnLocation = 2
end

-- Spawn in the Convoy
Rule_Spawn_New_Convoy()

--Check for the Convoy Destruction 
Rule_AddInterval(Rule_Check_For_Convoy_Destruction, 3)

-- Check if the mechanized commands are all destroyed
Rule_AddInterval(Rule_Check_For_All_MechanizedCommand_Destroyed, 1)

end

-- Picks Same Convoy Location Until it is destroyed -- function returns to "g_spawnLocation =" function Pick_Convoy_Spawn_Location() -- One By Convoy Base if EGroup_Count("eg_convoyBase_mechanizedCommand1") == 1 then return 1

-- One By Sentinel Base
elseif EGroup_Count("eg_convoyBase_mechanizedCommand2") == 1
then
	return 2

-- One By Sentinel Base
elseif EGroup_Count("eg_convoyBase_mechanizedCommand3") == 1
then
	return 3

-- One by North Base
elseif EGroup_Count("eg_convoyBase_mechanizedCommand5") == 1
then
	return 5

-- One by North Base
elseif EGroup_Count("eg_convoyBase_mechanizedCommand6") == 1
then
	return 6

-- One by Tank Base
elseif EGroup_Count("eg_convoyBase_mechanizedCommand4") == 1
then
	return 4
end

-- All Mech Commands Are Destroyed
return 0

end

--Ping the Mechanized Command that the convoys will spawn out of next function Rule_Ping_Convoy_Spawn()

whatLocation = Pick_Convoy_Spawn_Location()

-- if the objective exists
if Event_IsAnyRunning() == false and
	Objective_Exists(Objective_StopBaneBladeProduction.title_id) == true and	
	Objective_Exists(Objective_StopConvoysFromReachingBase.title_id) == true
then
	-- One By Convoy Base
	if EGroup_Count("eg_convoyBase_mechanizedCommand1") == 1 and
		g_convoySpawnPings_Objective_Table[1] == 0 and
		whatLocation == 1
	then
		g_convoySpawnPings_Objective_Table[1] = Objective_PingMarker(Objective_StopConvoysFromReachingBase.title_id, "mkr_convoy_spawnLocation1", true, attack)
	
	-- One By Sentinel Base
	elseif EGroup_Count("eg_convoyBase_mechanizedCommand2") == 1 and
		g_convoySpawnPings_Objective_Table[2] == 0 and
		whatLocation == 2
	then
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[1])
		g_convoySpawnPings_Objective_Table[2] = Objective_PingMarker(Objective_StopConvoysFromReachingBase.title_id, "mkr_convoy_spawnLocation2", true, attack)
	
	-- One By Sentinel Base
	elseif EGroup_Count("eg_convoyBase_mechanizedCommand3") == 1 and
		g_convoySpawnPings_Objective_Table[3] == 0 and
		whatLocation == 3
	then
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[1])
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[2])
		g_convoySpawnPings_Objective_Table[3] = Objective_PingMarker(Objective_StopConvoysFromReachingBase.title_id, "mkr_convoy_spawnLocation3", true, attack)
	
	-- One by North Base
	elseif EGroup_Count("eg_convoyBase_mechanizedCommand5") == 1 and
		g_convoySpawnPings_Objective_Table[5] == 0 and
		whatLocation == 5
	then
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[1])
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[2])
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[3])
		g_convoySpawnPings_Objective_Table[5] = Objective_PingMarker(Objective_StopConvoysFromReachingBase.title_id, "mkr_convoy_spawnLocation5", true, attack)
	
	-- One by North Base
	elseif EGroup_Count("eg_convoyBase_mechanizedCommand6") == 1 and
		g_convoySpawnPings_Objective_Table[6] == 0 and
		whatLocation == 6			
	then
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[1])
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[2])
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[3])
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[5])
		g_convoySpawnPings_Objective_Table[6] = Objective_PingMarker(Objective_StopConvoysFromReachingBase.title_id, "mkr_convoy_spawnLocation6", true, attack)
	
	-- One by Tank Base
	elseif EGroup_Count("eg_convoyBase_mechanizedCommand4") == 1 and
		g_convoySpawnPings_Objective_Table[4] == 0 and
		whatLocation == 4
	then
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[1])
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[2])
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[3])
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[5])
		Objective_PingRemove(Objective_StopConvoysFromReachingBase.title_id, g_convoySpawnPings_Objective_Table[6])
		g_convoySpawnPings_Objective_Table[4] = Objective_PingMarker(Objective_StopConvoysFromReachingBase.title_id, "mkr_convoy_spawnLocation4", true, attack)
	end
end

end

-- Spawn in a convoy & task to first location function Rule_Spawn_New_Convoy() -- Skip the Convoy Spawned IE the first time, since another IE covers it if g_firstConvoy_Spawned == true then Util_StartIntel(EVENTS.IE_Convoy_Mechanized) else g_firstConvoy_Spawned = true end

-- Create the Transport (& Share FOW Vision)
Util_CreateSquadsAtMarkerEx(g_Player4, "sg_convoy_transport_"..g_spawnLocation, "guard_squad_convoy_sp_dxp3", "mkr_convoy_spawnLocation"..g_spawnLocation, 1, 1)
FOW_TagSGroup(g_Player1, "sg_convoy_transport_"..g_spawnLocation)

-- Set it so game knows a convoy has spawned from a location & thus checks if it has been destroyed
g_convoy_Spawned_table[g_spawnLocation] = true

-- If only at alert status 0 -- Order transport to each locations first checkpoint: 18
if g_spawnLocation == 1 and
	g_currentAlertStatus == 0 
then
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint18")
	Rule_AddInterval(Rule_Convoy_Path_Zero, g_convoy_MaxTime_SpentCheckpoint)

-- If greater than Alert Status 1 -- Order transport to each locations first checkpoint: 17
elseif g_spawnLocation == 1
then
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint17")
	Rule_AddInterval(Rule_Convoy_Path_One, g_convoy_MaxTime_SpentCheckpoint)

-- Order transport to each locations first checkpoint: 13
elseif g_spawnLocation == 2 and
	g_currentAlertStatus <= 2
then
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint13")
	Rule_AddInterval(Rule_Convoy_Path_Two_B, g_convoy_MaxTime_SpentCheckpoint)

-- Order transport to each locations first checkpoint: 12
elseif g_spawnLocation == 2 and
	g_currentAlertStatus > 2
then
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint12")
	Rule_AddInterval(Rule_Convoy_Path_Two_A, g_convoy_MaxTime_SpentCheckpoint)

-- Order transport to each locations first checkpoint: 13
elseif g_spawnLocation == 3 and
	g_currentAlertStatus < 2
then
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint13")
	Rule_AddInterval(Rule_Convoy_Path_Two_B, g_convoy_MaxTime_SpentCheckpoint)

-- Order transport to each locations first checkpoint: 12
elseif g_spawnLocation == 3 and
	g_currentAlertStatus >= 2
then
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint12")
	Rule_AddInterval(Rule_Convoy_Path_Two_A, g_convoy_MaxTime_SpentCheckpoint)

-- Order transport to each locations first checkpoint: 11
elseif g_spawnLocation == 4
then
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint11")
	Rule_AddInterval(Rule_Convoy_Path_Three, g_convoy_MaxTime_SpentCheckpoint)

-- Order transport to each locations first checkpoint: 15
elseif g_spawnLocation == 5
then
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint15")
	Rule_AddInterval(Rule_Convoy_Path_Four_A, g_convoy_MaxTime_SpentCheckpoint)

-- Order transport to each locations first checkpoint: 16
elseif g_spawnLocation == 6
then
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint16")
	Rule_AddInterval(Rule_Convoy_Path_Four_B, g_convoy_MaxTime_SpentCheckpoint)

-- Order transport to each locations first checkpoint: 14
elseif g_spawnLocation == 7
then
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint14")
	Rule_AddInterval(Rule_Convoy_Path_Five, g_convoy_MaxTime_SpentCheckpoint)
end

end


-- CONVOY PATHING

--18,1,2,4 function Rule_Convoy_Path_Zero() -- if the convoy was destroyed along the way, remove the rule so it can be added again next time this convoy spawns if g_convoy_Spawned_table[1] == false then Rule_Remove(Rule_Convoy_Path_Zero)

-- if the transport has arrived at checkpoint: 18
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint18") == true
then
	-- Order transport to next checkpoint: 1
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint1")

-- if the transport has arrived at checkpoint: 1
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint1") == true
then
	-- Order transport to next checkpoint: 2
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint2")

-- if the transport has arrived at checkpoint: 2
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint2") == true
then
	-- Order transport to next checkpoint: 4
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint4")

-- if the transport has arrived at the Mars Command (Checkpoint: 4)	
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint4") == true
then
	Rule_Add(Rule_Convoy_Reached_Mars_Command)
	Rule_Remove(Rule_Convoy_Path_Zero)
end

end

-- 17,6,5,3,4 function Rule_Convoy_Path_One() -- if the convoy was destroyed along the way, remove the rule so it can be added again next time this convoy spawns if g_convoy_Spawned_table[1] == false and g_convoy_Spawned_table[2] == false and g_convoy_Spawned_table[3] == false then Rule_Remove(Rule_Convoy_Path_One)

-- if the transport has arrived at checkpoint: 17
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint17") == true
then
	-- Order transport and its escort to next checkpoint: 6

-- Cmd_AttackMoveMarker("sg_convoy_transportEscort_"..g_spawnLocation, "mkr_convoy_checkPoint6") Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint6")

-- if the transport has arrived at checkpoint: 6
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint6") == true
then
	-- Order transport and its escort to next checkpoint: 5

-- Cmd_AttackMoveMarker("sg_convoy_transportEscort_"..g_spawnLocation, "mkr_convoy_checkPoint5") Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint5")

-- if the transport has arrived at checkpoint: 5
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint5") == true
then
	-- Order transport and its escort to next checkpoint: 3

-- Cmd_AttackMoveMarker("sg_convoy_transportEscort_"..g_spawnLocation, "mkr_convoy_checkPoint3") Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint3")

-- if the transport has arrived at checkpoint: 3
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint3") == true
then
	-- Order transport and its escort to next checkpoint: 4

-- Cmd_AttackMoveMarker("sg_convoy_transportEscort_"..g_spawnLocation, "mkr_convoy_checkPoint4") Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint4")

-- if the transport has arrived at the Mars Command (Checkpoint: 4)	
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint4") == true
then
	Rule_Add(Rule_Convoy_Reached_Mars_Command)
	Rule_Remove(Rule_Convoy_Path_One)
end

end

--1,2,4 function Rule_Convoy_Path_Two() -- if the convoy was destroyed along the way, remove the rule so it can be added again next time this convoy spawns -- both these convoys use this path if g_convoy_Spawned_table[2] == false and g_convoy_Spawned_table[3] == false then Rule_Remove(Rule_Convoy_Path_Two)

-- if the transport has arrived at checkpoint: 1
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint1") == true
then
	-- Order transport to next checkpoint: 2
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint2")

-- if the transport has arrived at checkpoint: 2
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint2") == true
then
	-- Order transport to next checkpoint: 4
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint4")

-- if the transport has arrived at the Mars Command (Checkpoint: 4)	
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint4") == true
then
	Rule_Add(Rule_Convoy_Reached_Mars_Command)
	Rule_Remove(Rule_Convoy_Path_Two)
end

end

-- 12 to 1 (then follows path two) function Rule_Convoy_Path_Two_A() -- if the convoy was destroyed along the way, remove the rule so it can be added again next time this convoy spawns if g_convoy_Spawned_table[2] == false and g_convoy_Spawned_table[3] == false then Rule_Remove(Rule_Convoy_Path_Two_A)

-- if the transport has arrived at checkpoint: 12
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint12") == true
then
	-- Order transport to next checkpoint: 1
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint1")

	-- Remove this rule and add the Main Rule for Path Two
	Rule_Remove(Rule_Convoy_Path_Two_A)
	Rule_AddInterval(Rule_Convoy_Path_Two, g_convoy_MaxTime_SpentCheckpoint)
end

end

-- 13 to 1 (then follows path two) function Rule_Convoy_Path_Two_B() -- if the convoy was destroyed along the way, remove the rule so it can be added again next time this convoy spawns if g_convoy_Spawned_table[2] == false and g_convoy_Spawned_table[3] == false then Rule_Remove(Rule_Convoy_Path_Two_B)

-- if the transport has arrived at checkpoint: 13
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint13") == true
then
	-- Order transport to next checkpoint: 19
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint19")

-- if the transport has arrived at checkpoint: 19
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint19") == true
then
	-- Order transport to next checkpoint: 20
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint20")
	
-- if the transport has arrived at checkpoint: 20
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint20") == true
then
	-- Order transport to next checkpoint: 21
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint21")
	
-- if the transport has arrived at checkpoint: 21
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint21") == true
then
	-- Order transport to next checkpoint: 17
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint17")
	
	-- Remove this rule and add the Main Rule for Path One
	Rule_Remove(Rule_Convoy_Path_Two_B)
	Rule_AddInterval(Rule_Convoy_Path_One, g_convoy_MaxTime_SpentCheckpoint)
end

end

--11,2,4 function Rule_Convoy_Path_Three() -- if the convoy was destroyed along the way, remove the rule so it can be added again next time this convoy spawns if g_convoy_Spawned_table[4] == false then Rule_Remove(Rule_Convoy_Path_Three)

-- if the transport has arrived at checkpoint: 11
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint11") == true
then
	-- Order transport to next checkpoint: 2
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint2")

-- if the transport has arrived at checkpoint: 2
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint2") == true
then
	-- Order transport to next checkpoint: 4
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint4")

-- if the transport has arrived at the Mars Command (Checkpoint: 4)
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint4") == true
then
	Rule_Add(Rule_Convoy_Reached_Mars_Command)
	Rule_Remove(Rule_Convoy_Path_Three)
end

end

-- 7,8,9,10 function Rule_Convoy_Path_Four() -- if the convoy was destroyed along the way, remove the rule so it can be added again next time this convoy spawns -- both these convoys use this path if g_convoy_Spawned_table[5] == false and g_convoy_Spawned_table[6] == false then Rule_Remove(Rule_Convoy_Path_Four)

-- if the transport has arrived at checkpoint: 7
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint7") == true
then
	-- Order transport to next checkpoint: 8
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint8")

-- if the transport has arrived at checkpoint: 8
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint8") == true
then
	-- Order transport to next checkpoint: 9
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint9")

-- if the transport has arrived at checkpoint: 9
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint9") == true
then
	-- Order transport to next checkpoint: 10
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint10")

-- if the transport has arrived at the Mars Command (Checkpoint: 10)
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint10") == true
then
	Rule_Add(Rule_Convoy_Reached_Mars_Command)
	Rule_Remove(Rule_Convoy_Path_Four)
end

end

-- 15 to 7 (then follows path four) function Rule_Convoy_Path_Four_A() -- if the convoy was destroyed along the way, remove the rule so it can be added again next time this convoy spawns if g_convoy_Spawned_table[5] == false then Rule_Remove(Rule_Convoy_Path_Four_A)

-- if the transport has arrived at checkpoint: 15
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint15") == true
then
	-- Order transport to next checkpoint: 7
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint7")

	-- Remove this rule and add the Main Rule for Path Four
	Rule_Remove(Rule_Convoy_Path_Four_A)
	Rule_AddInterval(Rule_Convoy_Path_Four, g_convoy_MaxTime_SpentCheckpoint)
end

end

-- 16 to 7 (then follows path four) function Rule_Convoy_Path_Four_B() -- if the convoy was destroyed along the way, remove the rule so it can be added again next time this convoy spawns if g_convoy_Spawned_table[6] == false then Rule_Remove(Rule_Convoy_Path_Four_B)

-- if the transport has arrived at checkpoint: 16
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint16") == true
then
	-- Order transport to next checkpoint: 7
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint7")

	-- Remove this rule and add the Main Rule for Path Four
	Rule_Remove(Rule_Convoy_Path_Four_B)
	Rule_AddInterval(Rule_Convoy_Path_Four, g_convoy_MaxTime_SpentCheckpoint)
end

end

-- 14,3,4 function Rule_Convoy_Path_Five() -- if the convoy was destroyed along the way, remove the rule so it can be added again next time this convoy spawns if g_convoy_Spawned_table[7] == false then Rule_Remove(Rule_Convoy_Path_Five)

-- if the transport has arrived at checkpoint: 14
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint14") == true
then
	-- Order transport to next checkpoint: 3
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint3")

-- if the transport has arrived at checkpoint: 3
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint3") == true
then
	-- Order transport to next checkpoint: 4
	Cmd_MoveToMarker("sg_convoy_transport_"..g_spawnLocation, "mkr_convoy_checkPoint4")

-- if the transport has arrived at the Mars Command (Checkpoint: 4)
elseif Player_AreSquadsNearMarker(g_Player4, "mkr_convoy_checkPoint4") == true
then
	Rule_Add(Rule_Convoy_Reached_Mars_Command)
	Rule_Remove(Rule_Convoy_Path_Five)
end

end

-- Convoy has reached the Mars Command -- Increment Baneblade counter, reset timer & prepare for next convoy to spawn function Rule_Convoy_Reached_Mars_Command() -- the first time a convoy reaches the Mars Pattern Command( & the mars command still exists) if g_MarsPatternObjective_Assigned == false and EGroup_Count( EGroup_FromName("eg_mainBase_marsPattern_Objective")) > 0 then -- Assign the Objective & play IE, (Objective moved so assigns when convoy one is assigned) Util_StartIntel(EVENTS.IE_Convoy_FirstMarsPattern) --Rule_AddInterval(Rule_DestroyMarsPatternCommand_Objective, 1)

	-- So never fires again
	g_MarsPatternObjective_Assigned = true

-- Make sure the Mars Pattern Still Exists if playing IE
elseif EGroup_Count( EGroup_FromName("eg_mainBase_marsPattern_Objective")) > 0
then
	-- Play Repeatable IE -- Either Long Version or Short Version
	local pickIE = World_GetRand(0,1)
	
	if pickIE == 0 then
		Util_StartIntel(EVENTS.IE_Convoy_MarsPattern_Short)
	else
		Util_StartIntel(EVENTS.IE_Convoy_MarsPattern_Long)
	end
end

-- Despawn the Transport (remove from world)
SGroup_DeSpawn("sg_convoy_transport_"..g_spawnLocation)
SGroup_Clear("sg_convoy_transport_"..g_spawnLocation)

--Baneblade counter goes up here
Rule_AddOneShot(Rule_Update_Baneblade_Counter,0)

-- Set back to false so can spawn again from this slot
g_convoy_Spawned_table[g_spawnLocation] = false

-- Do we still have a mechanized command to spawn from?
if g_convoy_canSpawnNewOne == true
then
	-- Pick the Spawn location of the next Convoy (REDONE BEFORE CONVOY ACTUALLY SPAWNS)
	g_spawnLocation = Pick_Convoy_Spawn_Location()
	
	-- Reset the Timer until next convoy spawns in
	g_convoy_Timer = g_timeUntilNextConvoy
	
	-- Show the convoy timer on the screen
	UI_ShowCountDXP("Convoy_Timer_Ui", g_Player1, 3950193, g_convoy_Timer )
	
	-- Start the onscreen timer until the convoy spawns in
	Rule_AddInterval(Rule_Convoy_Spawn_Warning,1)
end

Rule_Remove(Rule_Convoy_Reached_Mars_Command)

end

-- EXTRA CONVOY RULES

-- Update the Baneblade counter since a convoy has reached the mars command & produces the baneblades when the counter hits 0 function Rule_Update_Baneblade_Counter() --Update the Counter since a convoy has arrived g_convoy_currentNumberForBaneBlade = g_convoy_currentNumberForBaneBlade - 1 UI_ShowCountUpdateDxp("Baneblade_Counter_Ui", g_convoy_currentNumberForBaneBlade, 3950194)

-- Play IE the 1st Time the Counter Gets to Halfway
if g_convoy_currentNumberForBaneBlade == (g_convoy_maxNumberForBaneBlade/2) and
	g_firstBaneBladeProduced == false
then
	Util_StartIntel(EVENTS.IE_HalfConvoysNotice)
end

-- if the counter has reached 0 (All shipments arrived) & One of the Mars Patterns Still Exists
if g_convoy_currentNumberForBaneBlade == 0 and
	EGroup_Count( EGroup_FromName("eg_mainBase_marsPattern_Objective")) > 0
then
	--Reset the Counter to Maximum
	g_convoy_currentNumberForBaneBlade  = g_convoy_maxNumberForBaneBlade

	-- So the Player can see the Baneblades Coming (Baneblade is the only unit belonging to AI: g_Player7)
	--World_EnablePlayerToPlayerFOW(g_Player1, g_Player7, false)
	
	-- PLay IE for Baneblade Production		
	if g_firstBaneBladeProduced == false
	then
		-- Play 1st BaneBlade Produced IE
		Util_StartIntel(EVENTS.IE_FirstBanebladeReady)
		g_firstBaneBladeProduced = true
	else
		-- Play Basic Repeatable IE
		Util_StartIntel(EVENTS.IE_BanebladeReady)
	end

	-- Create a baneBlade out of the Mars Pattern Command1 if it still exsists
	if EGroup_Count("eg_mainBase_marsPattern1") == 1
	then
		-- Create & Order the Baneblades to attack move on the player base (& share FOW with Player)
		Util_CreateSquadsAtMarker(g_Player7, "sg_baneblade_production", "guard_squad_baneblade", "mkr_mainBase_marsPattern1",1)
		FOW_TagSGroup(g_Player1, "sg_baneblade_production")
		Cmd_AttackMoveMarker("sg_baneblade_production", "mkr_player_mainBase_HQ")
	else
		-- in case player destroys the mars command before any baneblades are produced (so it will produce the one baneblade out of second mars)
		g_spawnTwoBaneBlades = true
	end

	-- Create a baneBlade out of the Mars Pattern Command2 if it still exsists
	if EGroup_Count("eg_mainBase_marsPattern2") == 1 and
		g_spawnTwoBaneBlades == true
	then
		-- Create & Order the Baneblades to attack move on the player base (& share FOW with Player)
		Util_CreateSquadsAtMarker(g_Player7, "sg_baneblade_production", "guard_squad_baneblade", "mkr_mainBase_marsPattern2",1)
		FOW_TagSGroup(g_Player1, "sg_baneblade_production")
		Cmd_AttackMoveMarker("sg_baneblade_production", "mkr_player_mainBase_HQ")
	end
	
	-- alternates between making 1 and 2 baneblades each time
	if g_spawnTwoBaneBlades == false
	then
		-- false to true (1-2)
		--g_spawnTwoBaneBlades = true
		
		-- Stay as Only One Baneblade : 2 baneblades at once is too hard
		g_spawnTwoBaneBlades = false
	end
	
	-- Update the counter back to maximum number
	UI_ShowCountUpdateDxp("Baneblade_Counter_Ui", g_convoy_currentNumberForBaneBlade, 3950194)
end

end

-- Controls the OnScreen Countdown Timer until Next Convoy Spawns function Rule_Convoy_Spawn_Warning( ) --counting down from g_timeUntilNextConvoy to 0 g_convoy_Timer = g_convoy_Timer -1

--3950193 is the localized string that appears on screen
UI_ShowCountUpdateDxp("Convoy_Timer_Ui", g_convoy_Timer, 3950193)

--once you hit 0 the next convoy will spawn in
if g_convoy_Timer == 0
then
	-- Hide the Timer until next convoy spawns
	UI_HideCount("Convoy_Timer_Ui")
	
	-- Pick the Spawn location of the Convoy
	g_spawnLocation = Pick_Convoy_Spawn_Location()
	
	-- If Still Has a spawn location to spawn into & Mars Command Still Alive... spawn new convoy in
	if g_spawnLocation > 0 and
		EGroup_Count( EGroup_FromName("eg_mainBase_marsPattern_Objective")) > 0
	then
		Rule_Spawn_New_Convoy()
	end
	
	-- Remove this rule (will be readded next time ready to start convoy countdown)
	Rule_Remove( Rule_Convoy_Spawn_Warning)
end

end

-- Checks if a convoy is destroyed before it reaches the mars command building : Added as an interval from Rule_Spawn_First_Convoy() function Rule_Check_For_Convoy_Destruction() -- Loop through all the active convoys for i = 1,g_convoy_locationsToUse do -- if the convoy was created & then destroyed if g_convoy_Spawned_table[i] == true and SGroup_Count("sg_convoy_transport_"..i) == 0 then -- Reset the Convoy Creation back to false g_convoy_Spawned_table[i] = false

		-- increment a counter that another convoy was destroyed
			-- so mission can react to the fact that player is doing good
		g_number_convoys_destroyed = g_number_convoys_destroyed +1

		-- Check for Alert Level Increase based on convoy destruction
		Rule_AddOneShot(IncreaseAlertLevel_ConvoyLosing, 1)

		-- Do we still have a mechanized command to spawn from?
		if g_convoy_canSpawnNewOne == true
		then
			-- Reset the Timer until next convoy spawns in
			g_convoy_Timer = g_timeUntilNextConvoy

			-- Show the convoy timer on the screen
			UI_ShowCountDXP("Convoy_Timer_Ui", g_Player1, 3950193, g_convoy_Timer )

			-- Start the onscreen timer until the convoy spawns in
			Rule_AddInterval(Rule_Convoy_Spawn_Warning,1)
		else
			-- Remove the rule, since the last convoy was destroyed & all mechanized commands are destroyed
			Rule_Remove(Rule_Check_For_Convoy_Destruction)
		end
	end
end

end


-- END OF ALL " CONVOY SPAWNING, PATHING, & UPGRADING " RULES


-- MEGA BASILISK & SPOTTER -- Rule_Activate_Basilisk_And_Spotters() : Play IE, Set up the spawning of the first spotters & adds the objectives with the Basilisk & Spotters -- Rule_Spawn_New_Spotter() : Spawn in New Spotters & Task to the Player Base -- Rule_Spotter_Has_Reached_Target_PrepareAttack() : Spotter has reached target without being attacked -- prepare to fire -- Rule_Spotter_Has_Been_Hurt_PrepareAttack() : Spotter was uncloaked & hurt before reaching target -- prepare to fire as a suicide result -- Rule_Spotter_One_Fire() : Spotter One was Ready to Fire -- Check if still alive after the delay & fire if so -- Rule_Spotter_Two_Fire() : Spotter Two was Ready to Fire -- Check if still alive after the delay & fire if so

-- ForEach Function: Checks if a Enemy Squad is In Range of Your Spotter (1 or 2) for Skill Targeting
	-- Rule_Spotter_Detect_Proximity_1(sgroupid, itemindex, squadID)
	-- Rule_Spotter_Detect_Proximity_2(sgroupid, itemindex, squadID)

--Play IE, Set up the spawning of the first spotters & adds the objectives with the Basilisk & Spotters function Rule_Activate_Basilisk_And_Spotters() -- Play IE: Util_StartIntel(EVENTS.IE_Artillary_ReadyToFire)

-- Add MegaBasilisk Secondary Objective 
Rule_AddInterval(Rule_StopMegaBasiliskAttacks_Objective, 5)

-- Spawn the First Spotters		
Rule_AddInterval(Rule_Spawn_New_Spotter, g_productionTimer_Spotters)

-- Handles Checking for the Spotter Attack (both via reach target & via damage)
Rule_AddInterval(Rule_Spotter_Has_Reached_Target_PrepareAttack,1)
Rule_AddInterval(Rule_Spotter_Has_Been_Hurt_PrepareAttack,1)

end

-- Spawn in New Spotters & Task to the Player Base function Rule_Spawn_New_Spotter() -- if gun exists if EGroup_Count("eg_MegaBasilisk_Objective") == 1 then -- Pick Random Spotter To Spawn i =World_GetRand(1,2)

	-- If Spotter Doesn't Exsists From HQ & HQ is still alive
	if SGroup_Count("sg_spotter_HQ"..i) == 0	and
		EGroup_Count("eg_centerBase_HQ"..i) == 1 and
		g_Spotter_Firing == false 
	then
		-- Spawn New Spotter (Spawns Infiltrated)
		Util_CreateSquadsAtMarker(g_Player5, "sg_spotter_HQ"..i, "guard_squad_artillery_spotter_sp_dxp3", "mkr_centerBase_HQ"..i, 1)

		-- Skip the Spotter Spawned IE the first time, since another IE covers it

-- if g_firstSpotter_Spawned == true -- then -- -- Play IE: Spotter Produced -- Util_StartIntel(EVENTS.IE_Artillary_SpotterProduced) -- else -- g_firstSpotter_Spawned = true -- end

		-- task the spotter to player base
		Cmd_MoveToMarker("sg_spotter_HQ"..i, "mkr_player_mainBase_HQ")
	end

-- Remove the Rule since the Gun Has Been Destroyed
else
	Rule_Remove(Rule_Spawn_New_Spotter)
end

end

-- Spotter has reached target without being attacked -- prepare to fire function Rule_Spotter_Has_Reached_Target_PrepareAttack() -- if gun exists if EGroup_Exists("eg_MegaBasilisk_Objective") and EGroup_Count("eg_MegaBasilisk_Objective") == 1 then for i=1,2 do -- If spotter reaches target marker if SGroup_Count("sg_spotter_HQ"..i) == 1 and Marker_InProximity(Marker_FromName("mkr_player_mainBase_HQ","basic_marker"), SGroup_GetPosition("sg_spotter_HQ"..i)) and g_Spotter_Firing == false then -- Ping Location of Spotter Ping_Position(SGroup_GetPosition("sg_spotter_HQ"..i), false, attack)

			-- Order the spotter to stand still & Spot
			Cmd_StopSquads("sg_spotter_HQ"..i)
			Cmd_SetStance("sg_spotter_HQ"..i, STANCE_CeaseFire)
			
			-- Play Random IE
			local spotterFire = World_GetRand(1,5)
			Util_StartIntel(g_ie_Spotter_ReadyToFire_Array[spotterFire])
			
			if i == 1
			then
				-- Spotter One Try to Fire : Delay was built into the skill
				g_Spotter_Firing = true
				Rule_AddOneShot(Rule_Spotter_One_Fire, 0) -- g_basilisk_delay)
			else
				-- Spotter Two Try to Fire : Delay was built into the Skill
				g_Spotter_Firing = true
				Rule_AddOneShot(Rule_Spotter_Two_Fire, 0) -- g_basilisk_delay)
			end
		end
	end

-- Remove the Rule since the Gun Has Been Destroyed
else
	Rule_Remove(Rule_Spotter_Has_Reached_Target_PrepareAttack)
end

end

-- Spotter was uncloaked & hurt before reaching target -- prepare to fire as a suicide result function Rule_Spotter_Has_Been_Hurt_PrepareAttack() -- if gun exists if EGroup_Exists("eg_MegaBasilisk_Objective") and EGroup_Count("eg_MegaBasilisk_Objective") == 1 then for i=1,2 do -- If Spotter exists & has been hurt (basically if the Player found them) if SGroup_Count("sg_spotter_HQ"..i) == 1 and SGroup_GetAvgHealth("sg_spotter_HQ"..i) ~= 1.0 and g_Spotter_Firing == false then -- Ping Location of Spotter Ping_Position(SGroup_GetPosition("sg_spotter_HQ"..i), false, attack)

			-- Order the spotter to stand still & Spot
			Cmd_StopSquads("sg_spotter_HQ"..i)
			Cmd_SetStance("sg_spotter_HQ"..i, STANCE_CeaseFire)
			
			-- Play Race Based IE the first time you find a spotter
			if g_firstSpotterCaught == false
			then
				Util_StartIntel(g_ie_Artillary_FirstSpotter_Found_Array[g_intelEvent_raceId])
				g_firstSpotterCaught = true
			else
				-- Play Random IE
				local spotterCaught = World_GetRand(1,4)
				Util_StartIntel(g_ie_Spotter_Caught_Array[spotterCaught])
			end
			
			if i == 1
			then
				-- Spotter One Try to Fire : Delay was built into the skill
				Rule_AddOneShot(Rule_Spotter_One_Fire, 0) -- g_basilisk_delay)
				g_Spotter_Firing = true
			else
				-- Spotter Two Try to Fire : Delay was built into the Skill
				Rule_AddOneShot(Rule_Spotter_Two_Fire, 0) -- g_basilisk_delay)
				g_Spotter_Firing = true
			end
		
		-- Try to target the Player Army with the Basilisk Attack
		elseif SGroup_Count("sg_spotter_HQ"..i) == 1 and
			g_spotter_TargetArmy == true and
			g_Spotter_Firing == false
		then
			--print("Spotter is Hunting Down the Player Army")
			Cmd_AttackMovePos("sg_spotter_HQ"..i,SGroup_GetPosition(Player_GetSquads(g_Player1)))
		end
		
		-- Range for the Spotter Proximity to Troops
		range = 20
		
		-- Check for Player Proximity to Spotter 1
		if SGroup_Count("sg_spotter_HQ"..i) == 1 and
			g_spotter_TargetArmy == true and
			g_Spotter_Firing == false and
			i == 1
		then
			-- Check if Enemy Squads are in range
			if SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Spotter_Detect_Proximity_1) and
				SGroup_Count("skill_target") > 0
			then
				-- Health has to == 1.0 in order to get here (otherwise would have fired)
				-- Setting to 0.95 so gun will fire next check & walk towards the enemy
				SGroup_SetAvgHealth("sg_spotter_HQ"..i, 0.95 )
				Cmd_AttackMovePos("sg_spotter_HQ"..i, SGroup_GetPosition("skill_target"))
			end
		
		-- Check for Player Proximity to Spotter 2
		elseif SGroup_Count("sg_spotter_HQ"..i) == 1 and
			g_spotter_TargetArmy == true and
			g_Spotter_Firing == false and
			i == 2
		then
			-- Check if Enemy Squads are in range
			if SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Spotter_Detect_Proximity_2) and
				SGroup_Count("skill_target") > 0
			then
				-- Health has to == 1.0 in order to get here (otherwise would have fired)
				-- Setting to 0.95 so gun will fire next check & walk towards the enemy
				SGroup_SetAvgHealth("sg_spotter_HQ"..i, 0.95 )
				Cmd_AttackMovePos("sg_spotter_HQ"..i, SGroup_GetPosition("skill_target"))
			end
		end
	end

-- Remove the Rule since the Gun Has Been Destroyed
else
	Rule_Remove(Rule_Spotter_Has_Been_Hurt_PrepareAttack)
end

end

-- Spotter One was Ready to Fire -- Check if still alive after the delay & fire if so function Rule_Spotter_One_Fire() -- if gun exists if EGroup_Exists("eg_MegaBasilisk_Objective") and EGroup_Count("eg_MegaBasilisk_Objective") == 1 then -- If Spotter exists still... Fire the Mega Basilisk if SGroup_Count("sg_spotter_HQ1") == 1 then -- Range for the Spotter Proximity to Troops range = 20

		-- Check if Enemy Squads are in range
		if SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Spotter_Detect_Proximity_1) and
			SGroup_Count("skill_target") > 0
		then
			-- Target the Enemy Squad
			Command_SquadAbilityPos(g_Player2,SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_spotter_HQ1"), 1), 
				"earthshaker_round_stronghold_dxp3_spotter", SGroup_GetPosition("skill_target"))
			--Command_EntityAbilityPos(g_Player2,EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_MegaBasilisk_Objective"), 1), 
			--	"earthshaker_round_stronghold_dxp3", SGroup_GetPosition("skill_target"))
		
		-- Check if Enemy Buldings are in range
		elseif EGroup_ForEach(Player_GetEntities(g_Player1), Rule_Spotter_Detect_Proximity_Buildings_1) and
			EGroup_Count("building_target") > 0
		then
			-- Target the Enemy Building
			Command_SquadAbilityPos(g_Player2,SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_spotter_HQ1"), 1), 
				"earthshaker_round_stronghold_dxp3_spotter", EGroup_GetPosition("building_target"))
			--Command_EntityAbilityPos(g_Player2,EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_MegaBasilisk_Objective"), 1), 
			--	"earthshaker_round_stronghold_dxp3", EGroup_GetPosition("building_target"))
		
		else
			-- Target the Spotter
			Command_SquadAbilityPos(g_Player2,SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_spotter_HQ1"), 1), 
				"earthshaker_round_stronghold_dxp3_spotter", SGroup_GetPosition("sg_spotter_HQ1"))
			--Command_EntityAbilityPos(g_Player2,EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_MegaBasilisk_Objective"), 1), 
			--	"earthshaker_round_stronghold_dxp3", SGroup_GetPosition("sg_spotter_HQ1"))
		end
	end
end

-- Delay for Skill Firing and then Re-allow basilisk Attack
Rule_AddOneShot(Rule_ReEnable_Spotter_Attacks, g_basilisk_delay)

-- So Can Fire Again : Now in Above Rule Since Delay is controlled via Skill
--g_Spotter_Firing = false

end

-- Spotter Two was Ready to Fire -- Check if still alive after the delay & fire if so function Rule_Spotter_Two_Fire() -- if gun exists if EGroup_Exists("eg_MegaBasilisk_Objective") and EGroup_Count("eg_MegaBasilisk_Objective") == 1 then -- If Spotter exists still... Fire the Mega Basilisk if SGroup_Count("sg_spotter_HQ2") == 1 then -- Range for the Spotter Proximity to Troops range = 20

		-- Check if Enemy Squads are in range
		if SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Spotter_Detect_Proximity_2) and
			SGroup_Count("skill_target") > 0
		then
			-- Target the Enemy Squad
			Command_SquadAbilityPos(g_Player2,SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_spotter_HQ2"), 1), 
				"earthshaker_round_stronghold_dxp3_spotter", SGroup_GetPosition("skill_target"))
			--Command_EntityAbilityPos(g_Player2,EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_MegaBasilisk_Objective"), 1), 
			--	"earthshaker_round_stronghold_dxp3", SGroup_GetPosition("skill_target"))
		
		-- Check if Enemy Buldings are in range
		elseif EGroup_ForEach(Player_GetEntities(g_Player1), Rule_Spotter_Detect_Proximity_Buildings_2) and
			EGroup_Count("building_target") > 0
		then
			-- Target the Enemy Building
			Command_SquadAbilityPos(g_Player2,SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_spotter_HQ2"), 1), 
				"earthshaker_round_stronghold_dxp3_spotter", EGroup_GetPosition("building_target"))
			--Command_EntityAbilityPos(g_Player2,EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_MegaBasilisk_Objective"), 1), 
			--	"earthshaker_round_stronghold_dxp3", EGroup_GetPosition("building_target"))
		
		else
			-- Target the Spotter
			Command_SquadAbilityPos(g_Player2,SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_spotter_HQ2"), 1), 
				"earthshaker_round_stronghold_dxp3_spotter", SGroup_GetPosition("sg_spotter_HQ2"))
			--Command_EntityAbilityPos(g_Player2,EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_MegaBasilisk_Objective"), 1), 
			--	"earthshaker_round_stronghold_dxp3", SGroup_GetPosition("sg_spotter_HQ2"))
		end
	end
end

-- Delay for Skill Firing and then Re-allow basilisk Attack
Rule_AddOneShot(Rule_ReEnable_Spotter_Attacks, g_basilisk_delay)

-- So Can Fire Again : Now in Above Rule Since Delay is controlled via Skill
--g_Spotter_Firing = false

end

-- Reable the Basilisk to Fire Again : Since the Spotter Delay is now skill controlled function Rule_ReEnable_Spotter_Attacks() -- So Can Fire Again g_Spotter_Firing = false end

-- ForEach Function: Checks if a Enemy Squad is In Range of Your Spotter1 for Skill Targeting function Rule_Spotter_Detect_Proximity_1(sgroupid, itemindex, squadID) SGroup_Clear("skill_target") SGroup_Add("skill_target", SGroup_GetSpawnedSquadAt(sgroupid,itemindex))

if Prox_SquadsInProximityOfSquads("sg_spotter_HQ1", "skill_target", range, true)
then
	return true
end

end

-- ForEach Function: Check if a Enemy Building is In Range of Your Spotter1 for Skill Targeting function Rule_Spotter_Detect_Proximity_Buildings_1(egroupid, itemindex, entityID) EGroup_Clear("building_target") EGroup_Add("building_target", EGroup_GetSpawnedEntityAt(egroupid,itemindex))

-- Avoid Basic Strategic Point, Relic, Critical Point, & Cannibalism Parts
local blueprintTable = Util_MakeBlueprintTable("relic_struct", "strategic_point_flag", "strategic_objective_struct", "cannibalism_Parts")

if Prox_SquadsInProximityOfEntities("sg_spotter_HQ1", "building_target", range, true) and 
	EGroup_ContainsBlueprints("building_target", blueprintTable, false) == false
then
	return true
end	

end

-- ForEach Function: Checks if a Enemy Squad is In Range of Your Spotter2 for Skill Targeting function Rule_Spotter_Detect_Proximity_2(sgroupid, itemindex, squadID) SGroup_Clear("skill_target") SGroup_Add("skill_target", SGroup_GetSpawnedSquadAt(sgroupid,itemindex))

if Prox_SquadsInProximityOfSquads("sg_spotter_HQ2", "skill_target", range, true)
then
	return true
end

end

-- ForEach Function: Check if a Enemy Building is In Range of Your Spotter2 for Skill Targeting function Rule_Spotter_Detect_Proximity_Buildings_2(egroupid, itemindex, entityID) EGroup_Clear("building_target") EGroup_Add("building_target", EGroup_GetSpawnedEntityAt(egroupid,itemindex))

-- Avoid Basic Strategic Point, Relic, Critical Point, & Cannibalism Parts
local blueprintTable = Util_MakeBlueprintTable("relic_struct", "strategic_point_flag", "strategic_objective_struct", "cannibalism_Parts")

if Prox_SquadsInProximityOfEntities("sg_spotter_HQ2", "building_target", range, true) and 
	EGroup_ContainsBlueprints("building_target", blueprintTable, false) == false
then
	return true
end	

end

-- END OF ALL " MEGA BASILISK & SPOTTER " RULES


-- COMSAT & CLOAK DETECTION -- Rule_ComSat_For_CloakDetection() : Main Rule that Handles ComSat Detection for cloak units -- These Functions are called once for every squad the player has: -- Rule_Count_Infiltrated(sgroupid, itemindex, squadID) : Counts how many infiltrated units the player currently has -- Rule_ComSat_Infiltrated(sgroupid, itemindex, squadID) : Casts the ComSat detection Ability on the Chosen Infiltrated Player Squad

-- Main Rule that Handles ComSat Detection for cloak units function Rule_ComSat_For_CloakDetection() -- Counts How Many Infiltrated Units Player Has g_howManyCloaked = 0

-- Chance to Play a Taunt IE
local randIEChance = World_GetRand(1,10)

-- Loop through & count number of infiltrated squads
SGroup_ForEach(Player_GetSquads(g_Player1), Rule_Count_Infiltrated)
--print("Infiltrated Player Units Found: "..g_howManyCloaked)	

if g_howManyCloaked > 0 and
	EGroup_Count("eg_HQInMainBase_Objective") == 1
then		
	-- Do we play a random taunt or not?
	if randIEChance > 5
	then
		local cloakTaunt = World_GetRand(1,3)
		Util_StartIntel(g_ie_CloakDetect_Taunt_Array[cloakTaunt])
	end
	
	-- Pick a Unit To ComSat
	g_whichOneToComstat = World_GetRand(1,g_howManyCloaked)
	
	-- Reset for Checking Reasons
	g_howManyCloaked = 0
	
	-- Loop Through and Comstat the chosen unit
	SGroup_ForEach(Player_GetSquads(g_Player1), Rule_ComSat_Infiltrated)

-- Fire the Comsat at the Spotters (will make it appear more random)
elseif SGroup_Count("sg_spotter_HQ1") == 1 and
		EGroup_Count("eg_HQInMainBase_Objective") == 1
then
	--print("Firing comsat at Spotter1 since no infiltrated found")
	Command_EntityAbilityPos(g_Player2,EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_HQInMainBase_Objective"), 1), "guard_detection_field", SGroup_GetPosition("sg_spotter_HQ1"))

-- Fire the Comsat at the Spotters (will make it appear more random)
elseif SGroup_Count("sg_spotter_HQ2") == 1 and
		EGroup_Count("eg_HQInMainBase_Objective") == 1
then
	--print("Firing comsat at Spotter2 since no infiltrated found")
	Command_EntityAbilityPos(g_Player2,EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_HQInMainBase_Objective"), 1), "guard_detection_field", SGroup_GetPosition("sg_spotter_HQ2"))

-- Fire the Comsat at the Player HQ (Default location)
elseif EGroup_Count("eg_HQInMainBase_Objective") == 1
then
	--print("Firing comsat at player HQ since no infiltrated  or spotters found")
	Command_EntityAbilityPos(g_Player2,EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_HQInMainBase_Objective"), 1), "guard_detection_field", Marker_GetPosition(Marker_FromName("mkr_player_mainBase_HQ", "basic_marker"))) --EGroup_GetPosition("eg_player_mainBase_HQ"))
end	

end

-- Counts how many infiltrated units the player currently has function Rule_Count_Infiltrated(sgroupid, itemindex, squadID) -- Check if the Squad is Infiltrated if Squad_IsInfiltrated(squadID) then -- if so... increase count of how many infiltrated units there are g_howManyCloaked = g_howManyCloaked + 1 end end

-- Casts the ComSat detection Ability on the Chosen Infiltrated Player Squad function Rule_ComSat_Infiltrated(sgroupid, itemindex, squadID) -- Check if the Squad is Infiltrated if Squad_IsInfiltrated(squadID) then g_howManyCloaked = g_howManyCloaked + 1

	-- Check if this is the unit chosen to be comsated....
	if g_howManyCloaked == g_whichOneToComstat and
		EGroup_Count("eg_HQInMainBase_Objective") == 1
	then
		--print("Fire the comsat "..g_howManyCloaked)			
		Command_EntityAbilityPos(g_Player2,EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_HQInMainBase_Objective"), 1), "guard_detection_field", Squad_GetPosition(squadID))
		return true
	end
end

end


-- END OF ALL " COMSAT & CLOAK DETECTION " RULES


-- VALKRIE DROP RULES -- VALKRIE DROP -- Rule_Valkrie_One-Five_CheckDrop : Checks if player has enough units in area to call in a Valkrie Drop -- VALKRIE TAKEOFF -- Rule_Valkrie_One-Five_TakeOff : Drops off troops based on alert levels & orders valkrie to takeoff -- VALKRIE DESPAWN -- Rule_Valkrie_One-Five_Despawn() : Delete the Valkrie & Despawn the SGroup


-- " VALKRIE DROP " RULES

-- Checks if the Area is Clear Before Attempting Valkrie Drop function Rule_Valkrie_One_CheckDrop() -- Check if the Player is near the drop area if Player_AreSquadsNearMarker(g_Player1, "mkr_valkrie_drop_1") == false then -- PLay IE valkrie_ie = World_GetRand(1,3) Util_StartIntel(g_ie_ValkyrieDrop_Array[valkrie_ie])

	-- Call in Valkrie Drop
	Util_CreateSquadsAtMarkerEx(g_Player2, "sg_valkrie_drop_1", "npc_valkyrie", "mkr_valkrie_drop_1", 1, 1)
	Anim_PlaySGroupAnim(SGroup_FromName("sg_valkrie_drop_1"), "sp_land")

	Rule_AddOneShot(Rule_Valkrie_One_TakeOff,8)
	Rule_Remove(Rule_Valkrie_One_CheckDrop)
end

end

-- Checks if player has enough units in area to call in a Valkrie Drop function Rule_Valkrie_Two_CheckDrop() -- Check if the Player is near the drop area if Player_AreSquadsNearMarker(g_Player1, "mkr_valkrie_drop_2") then -- Count How many play units are at that marker Player_GetAllSquadsNearMarker(g_Player1, "sg_NearMarker", "mkr_valkrie_drop_2") local unitCount = SGroup_Count("sg_NearMarker")

	--is it enough units to activate a drop?
	if unitCount >= g_num_PlayerUnits_ActivateBase
	then
		-- PLay IE
		valkrie_ie = World_GetRand(1,3)
		Util_StartIntel(g_ie_ValkyrieDrop_Array[valkrie_ie])
		
		-- Call in Valkrie Drop
		Util_CreateSquadsAtMarkerEx(g_Player2, "sg_valkrie_drop_2", "npc_valkyrie", "mkr_valkrie_drop_2", 1, 1)
		Anim_PlaySGroupAnim(SGroup_FromName("sg_valkrie_drop_2"), "sp_land")

		Rule_AddOneShot(Rule_Valkrie_Two_TakeOff,8)
		Rule_Remove(Rule_Valkrie_Two_CheckDrop)
	end
end

end -- Checks if player has enough units in area to call in a Valkrie Drop function Rule_Valkrie_Three_CheckDrop() -- Check if the Player is near the drop area if Player_AreSquadsNearMarker(g_Player1, "mkr_valkrie_drop_3") then -- Count How many play units are at that marker Player_GetAllSquadsNearMarker(g_Player1, "sg_NearMarker", "mkr_valkrie_drop_3") local unitCount = SGroup_Count("sg_NearMarker")

	--is it enough units to activate a drop?
	if unitCount >= g_num_PlayerUnits_ActivateBase
	then
		-- PLay IE
		valkrie_ie = World_GetRand(1,3)
		Util_StartIntel(g_ie_ValkyrieDrop_Array[valkrie_ie])
		
		-- Call in Valkrie Drop
		Util_CreateSquadsAtMarkerEx(g_Player2, "sg_valkrie_drop_3", "npc_valkyrie", "mkr_valkrie_drop_3", 1, 1)
		Anim_PlaySGroupAnim(SGroup_FromName("sg_valkrie_drop_3"), "sp_land")

		Rule_AddOneShot(Rule_Valkrie_Three_TakeOff,8)
		Rule_Remove(Rule_Valkrie_Three_CheckDrop)
	end
end

end -- Checks if player has enough units in area to call in a Valkrie Drop function Rule_Valkrie_Five_CheckDrop() -- Check if the Player is near the drop area if Player_AreSquadsNearMarker(g_Player1, "mkr_valkrie_drop_5") then -- Count How many play units are at that marker Player_GetAllSquadsNearMarker(g_Player1, "sg_NearMarker", "mkr_valkrie_drop_5") local unitCount = SGroup_Count("sg_NearMarker")

	--is it enough units to activate a drop?
	if unitCount >= g_num_PlayerUnits_ActivateBase
	then
		-- PLay IE
		valkrie_ie = World_GetRand(1,3)
		Util_StartIntel(g_ie_ValkyrieDrop_Array[valkrie_ie])
		
		-- Call in Valkrie Drop
		Util_CreateSquadsAtMarkerEx(g_Player2, "sg_valkrie_drop_5", "npc_valkyrie", "mkr_valkrie_drop_5", 1, 1)
		Anim_PlaySGroupAnim(SGroup_FromName("sg_valkrie_drop_5"), "sp_land")

		Rule_AddOneShot(Rule_Valkrie_Five_TakeOff,8)
		Rule_Remove(Rule_Valkrie_Five_CheckDrop)
	end
end

end

-- " VALKRIE TAKEOFF " RULES

function Rule_Valkrie_One_TakeOff() -- Produce some troops from the Valkrie if g_currentAlertStatus > 2 and EGroup_Count("eg_HQInMainBase_Objective") > 0 then Rule_Produce_Kasrkin_Full("sg_valkrie_kaskrin1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_1") Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_1") Rule_Produce_Sentinel("sg_valkrie_sentinel2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_1")

	Cmd_AttackMovePos("sg_valkrie_kaskrin1",g_attack_target)
	Cmd_AttackMovePos("sg_valkrie_sentinel1",g_attack_target)
	Cmd_AttackMovePos("sg_valkrie_sentinel2",g_attack_target)

elseif g_currentAlertStatus == 2 and
	EGroup_Count("eg_HQInMainBase_Objective") > 0
then
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_1")
	Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_1")
	Rule_Produce_Sentinel("sg_valkrie_sentinel2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_1")
	
	Cmd_AttackMovePos("sg_valkrie_troops1",g_attack_target)
	Cmd_AttackMovePos("sg_valkrie_sentinel1",g_attack_target)
	Cmd_AttackMovePos("sg_valkrie_sentinel2",g_attack_target)

elseif EGroup_Count("eg_HQInMainBase_Objective") > 0
then
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_1")
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_1")
	Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_1")
	
	Cmd_AttackMovePos("sg_valkrie_troops1",g_attack_target)
	Cmd_AttackMovePos("sg_valkrie_troops2",g_attack_target)
	Cmd_AttackMovePos("sg_valkrie_sentinel1",g_attack_target)
end

-- Take Off
Anim_PlaySGroupAnim(SGroup_FromName("sg_valkrie_drop_1"), "sp_take_off")
Rule_AddOneShot(Rule_Valkrie_One_Despawn,10)

end

function Rule_Valkrie_Two_TakeOff() -- Produce some troops from the Valkrie if g_currentAlertStatus > 2 and EGroup_Count("eg_HQInMainBase_Objective") > 0 then Rule_Produce_Kasrkin_Full("sg_valkrie_kaskrin1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_2") Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_2") Rule_Produce_Sentinel("sg_valkrie_sentinel2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_2")

elseif g_currentAlertStatus == 2 and
	EGroup_Count("eg_HQInMainBase_Objective") > 0
then
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_2")
	Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_2")
	Rule_Produce_Sentinel("sg_valkrie_sentinel2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_2")

elseif EGroup_Count("eg_HQInMainBase_Objective") > 0
then
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_2")
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_2")
	Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_2")
end

-- Take Off
Anim_PlaySGroupAnim(SGroup_FromName("sg_valkrie_drop_2"), "sp_take_off")
Rule_AddOneShot(Rule_Valkrie_Two_Despawn,10)

end

function Rule_Valkrie_Three_TakeOff() -- Produce some troops from the Valkrie if g_currentAlertStatus > 2 and EGroup_Count("eg_HQInMainBase_Objective") > 0 then Rule_Produce_Kasrkin_Full("sg_valkrie_kaskrin1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_3") Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_3") Rule_Produce_Sentinel("sg_valkrie_sentinel2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_3")

elseif g_currentAlertStatus == 2 and
	EGroup_Count("eg_HQInMainBase_Objective") > 0
then
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_3")
	Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_3")
	Rule_Produce_Sentinel("sg_valkrie_sentinel2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_3")

elseif EGroup_Count("eg_HQInMainBase_Objective") > 0
then
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_3")
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_3")
	Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_3")
end

-- Take Off
Anim_PlaySGroupAnim(SGroup_FromName("sg_valkrie_drop_3"), "sp_take_off")
Rule_AddOneShot(Rule_Valkrie_Three_Despawn,10)

end

function Rule_Valkrie_Five_TakeOff() -- Produce some troops from the Valkrie if g_currentAlertStatus > 2 and EGroup_Count("eg_HQInMainBase_Objective") > 0 then Rule_Produce_Kasrkin_Full("sg_valkrie_kaskrin1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_5") Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_5") Rule_Produce_Sentinel("sg_valkrie_sentinel2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_5")

elseif g_currentAlertStatus == 2 and
	EGroup_Count("eg_HQInMainBase_Objective") > 0
then
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_5")
	Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_5")
	Rule_Produce_Sentinel("sg_valkrie_sentinel2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_5")

elseif EGroup_Count("eg_HQInMainBase_Objective") > 0
then
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_5")
	Rule_Produce_Guardsmen_Full("sg_valkrie_troops2", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_5")
	Rule_Produce_Sentinel("sg_valkrie_sentinel1", "eg_HQInMainBase_Objective", "mkr_valkrie_drop_5")
end

-- Take Off
Anim_PlaySGroupAnim(SGroup_FromName("sg_valkrie_drop_5"), "sp_take_off")
Rule_AddOneShot(Rule_Valkrie_Five_Despawn,10)

end


-- " VALKRIE DESPAWN " RULES

function Rule_Valkrie_One_Despawn() SGroup_DeSpawn("sg_valkrie_drop_1") SGroup_Destroy("sg_valkrie_drop_1") end function Rule_Valkrie_Two_Despawn() SGroup_DeSpawn("sg_valkrie_drop_2") SGroup_Destroy("sg_valkrie_drop_2") end function Rule_Valkrie_Three_Despawn() SGroup_DeSpawn("sg_valkrie_drop_3") SGroup_Destroy("sg_valkrie_drop_3") end function Rule_Valkrie_Five_Despawn() SGroup_DeSpawn("sg_valkrie_drop_5") SGroup_Destroy("sg_valkrie_drop_5") end

-- END OF ALL " VALKRIE DROP " RULES


-- RANDOM MOVEMENT RULES -- Rule_RandomMovement_Support(squadName, markerName) -- Makes sure the squad Exists & has units, before telling the squad to randomly move to a location inside marker -- Rule_RandomMovement_Support_Builder(squadName, markerName) -- Causes Units to Move (Instead of Attack Move) to random location inside marker -- Rule_RandomMovement_Base() -- Causes a few units in each base to wander around it -- giving it the feeling of some life

-- Makes sure the squad Exists & has units, before telling the squad to randomly move to a location inside marker function Rule_RandomMovement_Support(squadName, markerName) if SGroup_Exists(squadName) and SGroup_Count(squadName) > 0 then Util_AttackMoveMarkerRandomRadius(squadName, markerName) end end

-- Causes Units to Move (Instead of Attack Move) to random location inside marker function Rule_RandomMovement_Support_Builder(squadName, markerName) if SGroup_Exists(squadName) and SGroup_Count(squadName) > 0 then local pos = Marker_GetPosition( Marker_FromName( markerName, "basic_marker" ) ) local prox = Marker_GetProximity( Marker_FromName( markerName, "basic_marker" ) )

	local xrand = World_GetRand( -prox, prox ) 
	local zrand = World_GetRand( -prox, prox ) 

	local movePos = World_Pos( xrand + pos.x, pos.y, zrand + pos.z )

	Command_SquadPos(g_Player2, squadName, SCMD_Move, movePos)
end

end

-- Causes a few units in each base to wander around it -- giving it the feeling of some life function Rule_RandomMovement_Base() -- CenterNorth Base: Guardsmen, Sentinel & Builders Rule_RandomMovement_Support("sg_centerNorthBase_defender1", "mkr_centerNorthBase_underAttack") Rule_RandomMovement_Support("sg_centerNorthBase_defender2", "mkr_centerNorthBase_underAttack") Rule_RandomMovement_Support("sg_centerNorthBase_defender3", "mkr_centerNorthBase_underAttack") Rule_RandomMovement_Support_Builder("sg_centerNorthBase_builder1", "mkr_centerNorthBase_underAttack")

-- CenterSouth Base: Guardsmen & Builders
Rule_RandomMovement_Support("sg_centerSouthBase_defender1", "mkr_centerSouthBase_underAttack")
Rule_RandomMovement_Support("sg_centerSouthBase_defender2", "mkr_centerSouthBase_underAttack")
Rule_RandomMovement_Support_Builder("sg_centerSouthBase_builder1", "mkr_centerSouthBase_underAttack")

-- CenterSouthBase: MegaBasilisk: Kaskrin, Guardsmen, & Sentinels
Rule_RandomMovement_Support("sg_centerSouthBase_defender3", "mkr_bigGun_underAttack")
Rule_RandomMovement_Support("sg_centerSouthBase_defender4", "mkr_bigGun_underAttack")
Rule_RandomMovement_Support("sg_centerSouthBase_defender5", "mkr_bigGun_underAttack")
Rule_RandomMovement_Support("sg_centerSouthBase_defender6", "mkr_bigGun_underAttack")

-- Main Base: Basilisk, Kaskrin, Bombers, Guardsmen & Builders
Rule_RandomMovement_Support("sg_mainBase_defender1", "mkr_mainBase_underAttack")
Rule_RandomMovement_Support("sg_mainBase_defender2", "mkr_mainBase_underAttack")
Rule_RandomMovement_Support("sg_mainBase_defender3", "mkr_mainBase_underAttack")
Rule_RandomMovement_Support("sg_mainBase_defender4", "mkr_mainBase_underAttack")
Rule_RandomMovement_Support("sg_mainBase_defender5", "mkr_mainBase_underAttack")
Rule_RandomMovement_Support("sg_mainBase_defender6", "mkr_mainBase_underAttack")
Rule_RandomMovement_Support_Builder("sg_mainBase_builder1", "mkr_mainBase_underAttack")
Rule_RandomMovement_Support_Builder("sg_mainBase_builder1", "mkr_mainBase_underAttack")

-- North Base: Guardsmen, Sentinels, Bombers, & Builders
Rule_RandomMovement_Support("sg_northBase_defender1", "mkr_northBase_underAttack")
Rule_RandomMovement_Support("sg_northBase_defender2", "mkr_northBase_underAttack")
Rule_RandomMovement_Support("sg_northBase_defender3", "mkr_northBase_underAttack")
Rule_RandomMovement_Support("sg_northBase_defender4", "mkr_northBase_underAttack")
Rule_RandomMovement_Support("sg_northBase_defender5", "mkr_northBase_underAttack")
Rule_RandomMovement_Support("sg_northBase_defender6", "mkr_northBase_underAttack")
Rule_RandomMovement_Support_Builder("sg_northBase_builder1", "mkr_northBase_underAttack")

end

-- END OF ALL " RANDOM MOVEMENT " RULES

-- Play Correct Animations for when Units Die function Rule_IdleUnits_Die() -- Sentinels: for i = 1,g_number_idle_sentinel do -- if the sentinel has just died (& never went active) if SGroup_Exists("sg_idle_sentinel_"..i) == true and g_idle_sentinel_table[i] == false and SGroup_GetAvgHealth("sg_idle_sentinel_"..i) <= 0.07 then g_idle_sentinel_table[i] = true

		--Stop the Shutdown Animation
		Anim_StopSGroupAnim("sg_idle_sentinel_"..i, "sp_shutdown" )
	end
end
	
-- Chimeras:
for i = 1,g_number_idle_chimera do
	-- if the chimera has just died (& never went active)
	if SGroup_Exists("sg_idle_chimera_"..i) == true and
		g_idle_chimera_table[i] == false and
		SGroup_GetAvgHealth("sg_idle_chimera_"..i) <= 0.07
	then
		g_idle_chimera_table[i] = true
		
		--Stop the Shutdown Animation
		Anim_StopSGroupAnim("sg_idle_chimera_"..i, "sp_shutdown" )
	end
end
	
-- Leman Russ Tanks: Main Base: Never Go Active
for i=1,g_number_idle_mainBase_lemanRussTank do
	-- if the Leman Russ has just died
	if SGroup_Exists("sg_mainBase_lemanRussTankActivator"..i) == true and
		SGroup_GetAvgHealth("sg_mainBase_lemanRussTankActivator"..i) <= 0.07 and
		SGroup_GetAvgHealth("sg_mainBase_lemanRussTankActivator"..i) > 0
	then
		--Stop the Shutdown Animation
		Anim_StopSGroupAnim("sg_idle_mainBase_lemanRussTank_"..i, "sp_shutdown" )
	end		
end
	
-- Leman Russ Tanks: Tank Base:
for i = 1,g_number_idle_lemanRussTank do
	-- if the leman russ tank has just died (& never went active)
	if SGroup_Exists("sg_idle_lemanRussTank_"..i) == true and
		g_idle_lemanRussTank_table[i] == false and
		SGroup_GetAvgHealth("sg_idle_lemanRussTank_"..i) <= 0.07
	then
		g_idle_lemanRussTank_table[i] = true
		
		--Stop the Shutdown Animation
		Anim_StopSGroupAnim("sg_idle_lemanRussTank_"..i, "sp_shutdown" )
	end
end
	
-- Valkries: North base -- Never Go Active
for i=1,g_number_idle_valkyrie do
	-- if the Valkrie has just died
	if SGroup_Exists("sg_idle_valkyrie_"..i) == 1 and
		SGroup_GetAvgHealth("sg_idle_valkyrie_"..i) <= 0.10 and
		SGroup_GetAvgHealth("sg_idle_valkyrie_"..i) > 0 
	then
		--Stop the Shutdown Animation
		Anim_StopSGroupAnim("sg_idle_valkyrie_"..i, "sp_shutdown" )
	end		
end

end

-- Dispatches a driver out of the Infantry Command by Convoy Base (SpawnLocation 1) & sends him to a chimera to activate it function Rule_Create_Troops_To_Activate_Chimeras() -- if the player has units in the area if Player_AreSquadsNearMarker(g_Player1, "mkr_idle_activateChimera") == true then -- if this is first time... if g_IE_Fired_Attack_ChimeraBase == false then -- Play IE g_IE_Fired_Attack_ChimeraBase = true Util_StartIntel(EVENTS.IE_Enemy_Attacks_Idle_Chimera_Base) end

	-- pick the highest inactive chimera
	local pick = Pick_Chimera( )

	-- if the chimeras still exsist...
	if pick ~= 0
	then
		-- Reveal the area around the Chimera & Barracks
		FOW_RevealMarker("mkr_idle_activateChimera", 30)
	else
		-- ... otherwise remove the rule since all chimeras were destroyed or all ready active
		Rule_Remove(Rule_Create_Troops_To_Activate_Chimeras)
		Rule_Remove(Rule_Activate_Chimeras)
		
		-- Activate the Base since all Chimeras used up (if barracks is still alive)
		if EGroup_Count("eg_convoyBase_infantryCommand5") == 1
		then
			Rule_AddOneShot(Rule_Activate_Chimera_Base, 5)
		end			
		
		return false
	end

	-- If the barracks still exsists( & haven't already dispatched a driver to that chimera)
	if EGroup_Count("eg_convoyBase_infantryCommand5") == 1 and
		SGroup_Count("sg_chimeraActivator"..pick) == 0
	then
		-- Create a driver out of barracks and task to chimera
		Util_CreateSquadsAtMarkerEx(g_Player5, "sg_chimeraActivator"..pick, "guard_squad_driver_sp_dxp3", "mkr_convoyBase_infantryCommand5", 1,2)
		Cmd_MoveToMarker("sg_chimeraActivator"..pick, "mkr_idle_chimera_"..pick)
	end
end

end

-- Dispatches a driver out of the Mechanized Command by Convoy Base (SpawnLocation 4) & sends him to a leman russ tank to activate it function Rule_Create_Troops_To_Activate_LemanRussTanks() -- if the player has units in the area if Player_AreSquadsNearMarker(g_Player1, "mkr_idle_activateTanks") == true then -- if this is first time... if g_IE_Fired_Attack_TankBase == false then -- Play IE g_IE_Fired_Attack_TankBase = true Util_StartIntel(EVENTS.IE_Enemy_Attacks_Idle_Tank_Base) end

	-- pick inactive LemanRuss tanks (lowest & highest remaining)
	local pick = Pick_LemanRussTank( )
	local pick_decreasing = Pick_LemanRussTank_Decreasing( )

	-- if the leman Russ Tanks still exsist...
	if pick ~= 0
	then
		-- Reveal the area around the Tanks & Vehicle Bay
		FOW_RevealMarker("mkr_idle_activateTanks", 30)
	else
		-- ... otherwise remove the rule since all Leman Russ Tanks were destroyed or all ready active
		Rule_Remove(Rule_Create_Troops_To_Activate_LemanRussTanks)
		Rule_Remove(Rule_Activate_LemanRussTanks)
		
		-- Activate the Base since all tanks used up (if mech command is still alive)
		if EGroup_Count("eg_convoyBase_mechanizedCommand4") == 1
		then
			Rule_AddOneShot(Rule_Activate_Tank_Base, 30)
		end
		
		return false
	end

	-- If the mechanized command still exists( & haven't already dispatched a driver to that leman russ tank)
	if EGroup_Count("eg_convoyBase_mechanizedCommand4") == 1 and
		SGroup_Count("sg_lemanRussTankActivator"..pick) == 0
	then
		-- Create a driver out of mechanized command & task to leman russ tank
		Util_CreateSquadsAtMarkerEx(g_Player5, "sg_lemanRussTankActivator"..pick, "guard_squad_driver_sp_dxp3", "mkr_convoyBase_mechanizedCommand4", 1, 1)
		Cmd_MoveToMarker("sg_lemanRussTankActivator"..pick, "mkr_idle_lemanRussTank_"..pick)
	end
	
	-- If the mechanized command still exists( & haven't already dispatched a driver to that leman russ tank)
	if EGroup_Count("eg_convoyBase_mechanizedCommand4") == 1 and
		SGroup_Count("sg_lemanRussTankActivator"..pick_decreasing) == 0
	then
		-- Create a driver out of mechanized command & task to leman russ tank
		Util_CreateSquadsAtMarkerEx(g_Player5, "sg_lemanRussTankActivator"..pick_decreasing, "guard_squad_driver_sp_dxp3", "mkr_convoyBase_mechanizedCommand4", 1, 1)
		Cmd_MoveToMarker("sg_lemanRussTankActivator"..pick_decreasing, "mkr_idle_lemanRussTank_"..pick_decreasing)
	end
end

end

-- Dispatches a driver out of the Infantry Command by Convoy Base (SpawnLocation 2&3 ) & sends him to a sentinel to activate it function Rule_Create_Troops_To_Activate_Sentinels() -- if the player has units in the area if Player_AreSquadsNearMarker(g_Player1, "mkr_idle_activateSentinels") == true then -- if this is first time... if g_IE_Fired_Attack_SentinelBase == false then -- Play IE g_IE_Fired_Attack_SentinelBase = true Util_StartIntel(EVENTS.IE_Enemy_Attacks_Idle_Sentinel_Base) end

	-- Pick inactive sentinels to active
	local increase = Pick_Sentinel_Increasing( )
	local decrease = Pick_Sentinel_Decreasing( )

	-- if the sentinels still exsist...
	if increase ~= 0
	then
		-- Reveal the area around the sentinels & barracks
		FOW_RevealMarker("mkr_idle_activateSentinels", 30)
	else
		-- ... otherwise remove the rule since all sentinels were destroyed or all ready active
		Rule_Remove(Rule_Create_Troops_To_Activate_Sentinels)
		Rule_Remove(Rule_Activate_Sentinels)
		
		-- Activate the Base since all sentinels used up (if base is still alive)
		if EGroup_Count("eg_convoyBase_mechanizedCommand2") == 1 or
			EGroup_Count("eg_convoyBase_mechanizedCommand3") == 1
		then
			Rule_AddOneShot(Rule_Activate_Sentinel_Base, 10)
		end
		
		return false
	end

	-- If the barracks still exsists(& haven't already dispatched a driver to that sentinel)
	if EGroup_Count("eg_convoyBase_infantryCommand3") == 1 and
		SGroup_Count("sg_sentinelActivator"..increase) == 0
	then
		-- Create a driver out of barracks & task to sentinel
		Util_CreateSquadsAtMarkerEx(g_Player5, "sg_sentinelActivator"..increase, "guard_squad_driver_sp_dxp3", "mkr_convoyBase_infantryCommand3", 1,1)
		Cmd_MoveToMarker("sg_sentinelActivator"..increase, "mkr_idle_sentinel_"..increase)
	end
	
	-- If the barracks still exsists ( & haven't already dispatched a driver to that sentinel)
	if EGroup_Count("eg_convoyBase_infantryCommand4") == 1 and
		SGroup_Count("sg_sentinelActivator"..decrease) == 0
	then
		-- Create a driver out of barracks & task to sentinel
		Util_CreateSquadsAtMarkerEx(g_Player5, "sg_sentinelActivator"..decrease, "guard_squad_driver_sp_dxp3", "mkr_convoyBase_infantryCommand4", 1,1)
		Cmd_MoveToMarker("sg_sentinelActivator"..decrease, "mkr_idle_sentinel_"..decrease)
	end
end

end

-- Checks all the idle Chimeras by Convoy Base (SpawnLocation 1) to see if a driver is next to them & activates if so function Rule_Activate_Chimeras() -- Loop through all idle chimeras for i = 1, g_number_idle_chimera do -- if a driver has reached a chimera that exists & is still idle if Prox_AnySquadNearMarker("sg_chimeraActivator"..i, "mkr_idle_chimera_"..i) == true and SGroup_Count("sg_idle_chimera_"..i) ~= 0 and g_idle_chimera_table[i] == false then -- Set the Chimera to Attack Mode (Order to Attack HQ) g_idle_chimera_table[i] = true

		-- Stop the Shutdown Animation
		Anim_StopSGroupAnim("sg_idle_chimera_"..i, "sp_shutdown" )
		
		Cmd_SetStance("sg_idle_chimera_"..i, STANCE_Attack)			
		Cmd_AttackMoveMarker("sg_idle_chimera_"..i, "mkr_player_mainBase_HQ")

		-- Despawn the Driver
		SGroup_DeSpawn("sg_chimeraActivator"..i)
	end
end		

end

-- Checks all the idle Leman Russ Tanks by Convoy Base (SpawnLocation 4) to see if a driver is next to them & activates if so function Rule_Activate_LemanRussTanks() -- Loop through all idle lemanRussTanks for i = 1, g_number_idle_lemanRussTank do -- if a driver has reached a lemanRussTank that exists & is still idle if Prox_AnySquadNearMarker("sg_lemanRussTankActivator"..i, "mkr_idle_lemanRussTank_"..i) == true and SGroup_Count("sg_idle_lemanRussTank_"..i) ~= 0 and g_idle_lemanRussTank_table[i] == false then -- Set the lemanRussTank to Attack Mode (Order to Atttack HQ) g_idle_lemanRussTank_table[i] = true

		-- Stop the Shutdown Animation
		Anim_StopSGroupAnim("sg_idle_lemanRussTank_"..i, "sp_shutdown" )
		
		Cmd_SetStance("sg_idle_lemanRussTank_"..i, STANCE_Attack)			
		Cmd_AttackMoveMarker("sg_idle_lemanRussTank_"..i, "mkr_player_mainBase_HQ")

		-- Despawn the Driver
		SGroup_DeSpawn("sg_lemanRussTankActivator"..i)
	end
end		

end

-- Checks all the idle Sentinels by Convoy Base (SpawnLocation 2&3) to see if a driver is next to them & activates if so function Rule_Activate_Sentinels() -- Loop through all idle sentinels for i = 1, g_number_idle_sentinel do -- if a driver has reached a sentinel that exists & is still idle if Prox_AnySquadNearMarker("sg_sentinelActivator"..i, "mkr_idle_sentinel_"..i) == true and SGroup_Count("sg_idle_sentinel_"..i) ~= 0 and g_idle_sentinel_table[i] == false then -- Set the Sentinel to Attack Mode (Order to Attack HQ) g_idle_sentinel_table[i] = true

		-- Stop the Shutdown Animation
		Anim_StopSGroupAnim( "sg_idle_sentinel_"..i, "sp_shutdown" )
		
		Cmd_SetStance("sg_idle_sentinel_"..i, STANCE_Attack)			
		Cmd_AttackMoveMarker("sg_idle_sentinel_"..i, "mkr_player_mainBase_HQ")
		
		-- Despawn the Driver
		SGroup_DeSpawn("sg_sentinelActivator"..i)
	end
end		

end

-- Pick the highest numbered Chimera by Convoy Base (SpawnLocation 1) to Activate -- Since Chimeras are arranged with highest in front function Pick_Chimera( ) for i = 1,g_number_idle_chimera do --So loop counts down j = g_number_idle_chimera + 1 - i

	-- if the chimera still exsists (and hasn't gone active yet)
	if SGroup_Count("sg_idle_chimera_"..j) == 1 and
		g_idle_chimera_table[j] == false
	then
		-- incase someone got stuck - -retell them to move to the chimera
		Cmd_MoveToMarker("sg_chimeraActivator"..j, "mkr_idle_chimera_"..j)
		-- return the number of the highest inactive chimera
		return j
	end
end

-- return 0 since we none exsist
return 0

end

-- Pick the lowest numbered Leman Russ Tank by Convoy Base (SpawnLocation 4) to Activate function Pick_LemanRussTank( ) for i = 1,g_number_idle_lemanRussTank do -- if the leman russ tank still exsists (and hasn't gone active yet) if SGroup_Count("sg_idle_lemanRussTank_"..i) == 1 and g_idle_lemanRussTank_table[i] == false then -- return the number of the lowest inactive leman russ tank return i end end

-- return 0 since we none exsist
return 0

end

-- Pick the highest numbered Leman Russ Tank by Convoy Base (SpawnLocation 4) to Activate function Pick_LemanRussTank_Decreasing( ) for i = 1,g_number_idle_lemanRussTank do --So loop counts down j = g_number_idle_lemanRussTank + 1 - i

	-- if the leman russ tank still exsists (and hasn't gone active yet)
	if SGroup_Count("sg_idle_lemanRussTank_"..j) == 1 and
		g_idle_lemanRussTank_table[j] == false
	then
		-- return the number of the highest inactive leman russ tank
		return j
	end
end

-- return 0 since we none exsist
return 0

end

-- Pick the lowest numbered Sentinel by Convoy Base (SpawnLocation 2&) to Activate function Pick_Sentinel_Increasing( ) for i = 1,g_number_idle_sentinel do -- if the sentinel still exsists (and hasn't gone active yet) if SGroup_Count("sg_idle_sentinel_"..i) == 1 and g_idle_sentinel_table[i] == false then -- return the number of the lowest inactive sentinel return i end end

-- return 0 since we none exsist
return 0

end

-- Pick the highest numbered Sentinel by Convoy Base (SpawnLocation 2&3) to Activate function Pick_Sentinel_Decreasing( ) for i = 1,g_number_idle_sentinel do --So loop counts down j = g_number_idle_sentinel + 1 - i

	-- if the sentinel still exsists (and hasn't gone active yet)
	if SGroup_Count("sg_idle_sentinel_"..j) == 1 and
		g_idle_sentinel_table[j] == false
	then
		-- return the number of the highest inactive sentinel
		return j
	end
end

-- return 0 since we none exsist
return 0

end

-- Upgrade all the Entrenched Heavy Weapons Teams Weapons function Rule_Upgrade_Entreched_HeavyWeaponsTeams() -- Loop through and upgrade the Anti Vehicle Heavy Weapons team... for i = 1, g_number_heavyWeapons_AntiInfantry do -- Make sure the SGroup Exsists before trying to upgrade... if SGroup_Count("sg_heavyWeapons_Entrenched_AntiInfantry_"..i) > 0 then --... Upgrade the Team to AutoCannon (Anti Infantry) Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_heavyWeapons_Entrenched_AntiInfantry_"..i), 1),"guard_autocannon_heavy_weapons_team",1) end end

-- Loop through and upgrade the Anti Vehicle Heavy Weapons team...
for i = 1, g_number_heavyWeapons_AntiVehicle do
	-- Make sure the SGroup Exsists before trying to upgrade...
	if SGroup_Count("sg_heavyWeapons_Entrenched_AntiVehicle_"..i) > 0
	then
		--... Upgrade the Team to Laser Gun(AntiVehicle)
		Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_heavyWeapons_Entrenched_AntiVehicle_"..i), 1),"guard_lasgun_heavy_weapons_team",1)
	end
end

end

-- VICTORY / DEFEAT RULES -- Rule_EndGame_Victory() : Checks if the mission has been Won (All Primary Objectives Completed) -- Rule_EndGame_Actual_Victory() : Wins the Mission & Plays the Final NIS -- Rule_EndGame_Defeat() : Checks if mission has been lost (Player Killed) -- Rule_GameOver() : Sets Game Over

-- Checks if the mission has been Won (All Primary Objectives Completed) function Rule_EndGame_Victory() -- If Both Primary Objectives Exists & Are Completed if Event_IsAnyRunning() == false and Objective_Exists(Objective_DestroyImperialGuardHQ.title_id) == true and Objective_Exists(Objective_StopBaneBladeProduction.title_id) == true and Objective_GetState(Objective_DestroyImperialGuardHQ.title_id) == OS_Complete and Objective_GetState(Objective_StopBaneBladeProduction.title_id) == OS_Complete then -- Call the Actual Victory Rule Wins the Mission & Plays FINAL NIS -- The Delay is so it doesn't occur the second you complete the Objectives Rule_AddOneShot(Rule_EndGame_Actual_Victory, 5) Rule_Remove(Rule_EndGame_Victory) end end

-- Wins the Mission & Plays the Final NIS function Rule_EndGame_Actual_Victory() -- Kills all rules (Basically cleans up any extra rules that were running and prepares for scenario complete) Rule_RemoveAll()

-- NIS: Play the mission complete scripted scene
WXP_OpeningNISPreset( )
Util_StartNIS(EVENTS.NIS_Victory)	

Rule_AddInterval(Rule_GameOver, 1)

end

-- Rule for Losing the Game function Rule_EndGame_Defeat()

-- define the "enemy" who will win when the player 'loses'
g_enemy = g_Player2

--Lose because of Player Annihilation (Make sure IE is not playing when check is made)	
if Event_IsAnyRunning() == false and
	Player_HasBuildingsExcept(g_Player1, t_building_exceptions) == false
	--and Player_HasSquadsExcept(g_Player1, t_unit_exceptions) == false
then
	Rule_RemoveAll()
	Fade_Start(4, false)
	World_SetTeamWin( g_enemy, "" )
	Rule_AddInterval(Rule_GameOver,1)
	Rule_Remove( Rule_EndGame_Defeat )
end

end

-- Actually sets the Game Over function Rule_GameOver() if Event_IsAnyRunning() == false then World_SetGameOver() end end

-- END OF ALL " VICTORY / DEFEAT " RULES

Статистика игры
Подписчики
24
Времена
69
Игроки
5
Последние темы
Опубликовано 2 years ago
1 ответ
Модераторы