Mission event file for Imperial Guard Stronghold mission
Guides
/
Mission event file for Imperial Guard Stronghold mission
Updated 3 years ago by Merric

--[[ IMPORTS ]]

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


--[[ GAME SETUP ]]

--[[ the OnGameSetup() function is mandatory! ]] function OnGameSetup()

--[[global variables]] g_firstrun = true g_Win = false g_titan_power = true g_Slagbase_created = false g_Artillery_Destroyed = false g_Artillery_reveal = 0 g_Artillery_control_timer = 10 g_Commisar_Dead = false g_FB_Harrassers_Waves = 0 g_FB_Destroyed = false g_AB_Destroyed = false g_AB_Harrassers_Spawned = 0 g_Titan_Thermos_Destroyed = false g_Canyon_Ambush = false g_Strat_Ambush = false g_Strat_Ambush_Sprung = false g_Chimera_Ambush_Spawn = false g_init_FB = false g_FB_Harasser_Prox1 = false g_FB_Harasser_Prox2 = false g_FB_Harasser_Prox3 = false g_FB_Harasser_Prox4 = false g_FB_Harasser_count = 0 g_FB_Harasser_Special_Ogryn = 1 g_FB_Harasser_Special_Kasrkin = 1 g_FB_spawn_timer = 0 g_FB_Harasser_Limit = 1 g_FB_SG = 1 g_FB_spawning_delay = 30 g_FB_harassers_empty = true g_Artillery_Transfer1 = false g_Artillery_Transfer2 = false g_Artillery_Transfer3 = false g_Freebie_Count = 0 g_Tranfer_Count = 0 g_Artillery_Repaired = false g_Recap_IE_Last_Taunt = 0 g_stronghold_breach_IE = false g_Rebel_IE = 0 g_Rebel_first_attack = true g_FB_obj_added = false g_AB_obj_added = false g_2nd_half_activated = false g_airstrike_value1 = 0 g_airstrike_value2 = 0 g_assassin_timer = 0 g_assassin_IE = false g_assassin_first_spawn = true g_rebel_rally = 1 g_baneblade_patrol = 1 g_skirmisher_special = 0 g_stronghold_perimeter = false g_airstrike_pos = 0 g_Northbridge_Base_Destroyed = false g_Artillery_Designator = "mkr_Artilley_Cluster1_" g_Artillery_rand_tracker = 1 g_Rebels_Defeated = false g_NIS_Timer = 0 g_Stronghold_Kasrkin_Timer = 0 g_Stronghold_Ogryn_Timer = 0 g_artillery_warning_timer = 0 g_Artillery_pings_removed = false g_player_check_first = false

-- Titan cannon varibles. g_Titan_timer = 0 g_Titan_timer_addon = 10 --the increment of time added to the overall timer each time a powerplant is destroyed. g_Titan_Power_Formula = 90 --the default starting timer between cannon shots before modified by slag plants being destroyed

g_Titan_FX_Delay = 2.5 --Delay between FX trigger and when the damage is applied.

g_Titan_Captured = false g_Titan_activated = false g_Titan_FX_timer_Delay = false g_Titan_FX_timer_counter = 4 g_Thermo1_Destroyed = false g_Thermo2_Destroyed = false g_Thermo3_Destroyed = false g_Thermo4_Destroyed = false g_Thermo5_Destroyed = false g_Thermo6_Destroyed = false g_Thermo7_Destroyed = false g_Thermo8_Destroyed = false g_Thermo9_Destroyed = false g_Thermo10_Destroyed = false g_Thermo1 = 0 g_Thermo2 = 0 g_Thermo3 = 0 g_Thermo4 = 0 g_Thermo5 = 0 g_Thermo6 = 0 g_Thermo7 = 0 g_Thermo8 = 0 g_Thermo9 = 0 g_Thermo10 = 0 g_Thermo_Plasma_Plants_Destroyed = 0 g_Titan_Gens_Attacked = false g_Gen_IE_Delay = 0 g_add_button = false g_Titan_Fire_Cost = 1000 g_Titan_button_timer = 0 g_button_first_add = true g_player_has_gens = false g_Thermo_ping_removed = false g_Thermo_ping_removed2 = false

g_ticker = 0 g_strat_capture_IE_timer = 0 g_HQ_Units_iter = 1 g_HQ_Harasser_Count = 1 g_Harasser_iter = 0 g_Armor_Harasser_Count = 1 g_Armor_Harasser_iter = 0 g_Rooftop_Count = 0 g_Rooftop_Start = 0 g_Rooftop_End = 0 g_AI_Infantry = 0 g_AI_Armor = 0 g_Northbridge_Mech_iter = 0 g_Northbridge_Barracks_iter = 0 g_Strat_Capture_Repawn = 0 g_Strat_Reassign_timer = 0 g_Freebie_Artillery = 0

-- Stronghold defense controls g_Stronghold_Invaders_active = false g_Stronghold_Invaders_Entities_active = false g_Stronghold_armor = 0 g_Stronghold_infantry = 0 g_Stronghold_infantry_iter = 0 g_Stronghold_infantry_count = 1 g_Stronghold_Kasrkin_count = 0 g_Stronghold_Ogryn_count = 0 g_Stronghold_Guard_count = 0 g_Stronghold_Kasrkin = 1 g_Stronghold_Ogryn = 1 g_Stronghold_Guard = 1 g_Stronghold_Ogryn_respawn = 0 g_Stronghold_Kasrkin_respawn = 0 g_Stronghold_Ogryn_spawned = false g_Stronghold_Kasrkin_spawned = false g_BaneBlade_respawn = 0 g_BaneBlade_alive = false

g_IG_HQ_Barracks2 = true g_IG_HQ_Barracks1 = true g_SlagBase_Barracks = true g_Island_Defender_count = 0 g_FB_IE_Last_Taunt = 0

-- Bridge defender varibles g_Bridge_Armor_count = 0 g_Bridge_Infantry_count = 0 g_Bridge_triggered = false g_Bridge_Mech1 = true g_Bridge_Mech2 = true g_Bridge_Barracks1 = true g_Bridge_Barracks2 = true g_Bridge_HQ = true

g_gameover = false

g_Chimera_Rush = 1

g_UI_Timer = 0 -- temp for testing purposes - tracks MINUTES played.

g_test = 1

--difficulty variables g_Difficulty = 0

g_territory_index = MetaMap_GetDefendingTerritoryIndex()

g_DBASE = 10 g_DMAX = 15 g_DIFF = MetaMap_GetTerritoryMilitaryStrength(g_territory_index)

--[[defining the name of the player's faction +Players leader blueprint +Race Color]]
if MetaMap_GetPlayerRaceName() == "chaos_marine_race" then
	
	factionname = "$690014"
	g_player_leader = "chaos_squad_lord_advance_sp"
	g_player_color = "default_1"
	
	g_Player_Gen = "chaos_thermo_plasma_generator"
	
	g_Player1 = Setup_Player(0, factionname, MetaMap_GetPlayerRaceName(), 1)
	Misc_PlayerTeamColor(g_Player1, g_player_color)
	
elseif MetaMap_GetPlayerRaceName() == "eldar_race" then
	
	factionname = "$690012"
	g_player_leader = "eldar_squad_farseer_advance_sp"
	g_player_color = "default_5"
	
	g_Player_Gen = "eldar_advanced_warp_generator"
	
	g_Player1 = Setup_Player(0, factionname, MetaMap_GetPlayerRaceName(), 1)
	Misc_PlayerTeamColor(g_Player1, g_player_color)
	
elseif MetaMap_GetPlayerRaceName() == "guard_race" then
	
	factionname = "$690011"
	g_player_leader = "guard_squad_command_squad_advance_sp"
	g_player_color = "liberators"
	
	g_Player_Gen = "guard_thermo_plasma"
	
	g_Player1 = Setup_Player(0, factionname, MetaMap_GetPlayerRaceName(), 1)
	
elseif MetaMap_GetPlayerRaceName() == "ork_race" then
	
	factionname = "$690013"
	g_player_leader = "ork_squad_warboss_advance_sp"
	g_player_color = "default_4"
	
	g_Player_Gen = "ork_bigger_generator"
	
	g_Player1 = Setup_Player(0, factionname, MetaMap_GetPlayerRaceName(), 1)
	Misc_PlayerTeamColor(g_Player1, g_player_color)
	
elseif MetaMap_GetPlayerRaceName() == "space_marine_race" then
	
	factionname = "$690010"
	g_player_leader = "space_marine_squad_force_commander_advance_sp"
	g_player_color = "default_0"
	
	g_Player_Gen = "space_marine_thermo_generator"
	
	g_Player1 = Setup_Player(0, factionname, MetaMap_GetPlayerRaceName(), 1)
	
elseif MetaMap_GetPlayerRaceName() == "tau_race" then
	
	factionname = "$690015"
	g_player_leader = "tau_commander_squad_advance_sp"
	g_player_color = "default_0"
	
	g_Player_Gen = "tau_thermoplasma_generator"
	
	g_Player1 = Setup_Player(0, factionname, MetaMap_GetPlayerRaceName(), 1)
	
elseif MetaMap_GetPlayerRaceName() == "necron_race" then
	
	factionname = "$690016"
	g_player_leader = "necron_lord_squad_advance_sp"
	g_player_color = "default_0"
	
	g_Player_Gen = "necron_thermoplasma_generator"
	
	g_Player1 = Setup_Player(0, factionname, MetaMap_GetPlayerRaceName(), 1)
	
end



g_Player2 = Setup_Player(1, "$690011", "guard_race", 2)
--Misc_PlayerTeamColor(g_Player2, "liberators")

--initial rebel IG team
g_Player3 = Setup_Player(2, "$690011", "guard_race", 2)
--Misc_PlayerTeamColor(g_Player3, "liberators")

--team rebels swap to once the commissar is dead.
g_Player4 = Setup_Player(3, "$2603020", "guard_race", 1)
Misc_PlayerTeamColor(g_Player4, "default_4")

-- neutral team used for objects like the throwers and NIS objects owned by the player that i don't want the AI to shoot at
g_Player5 = Setup_Player(4,"$2603030", "npc_race", TEAM_NEUTRAL)
--Misc_PlayerTeamColor(g_Player5, "liberators")

-- Team used for IG AI attackers - units given to this player will be set to a high difficulty and let loose instead of script controlled.
g_Player6 = Setup_Player(5, "$690011", "guard_race", 2)
--Misc_PlayerTeamColor(g_Player3, "liberators")

-- neutral rebel team used to hold artillery peices and the hacked sentinel for the titan cannon target.  
--This player is so that any player wide orders to the g_Player4 player doesn't effect these special units, but they still appear as rebels.
g_Player7 = Setup_Player(6, "$2603020", "guard_race", 1)
Misc_PlayerTeamColor(g_Player7, "default_4")

Misc_ForceAutoSwitchTeamColor (g_Player1, true) 	
Misc_ForceAutoSwitchTeamColor (g_Player2, true) 
Misc_ForceAutoSwitchTeamColor (g_Player3, true) 
Misc_ForceAutoSwitchTeamColor (g_Player4, true)
Misc_ForceAutoSwitchTeamColor (g_Player7, true)

--[[ DEFINE VARIABLES AND TABLES - define any preset values here for later use]]

--[[difficulty cacluations based on province strength]]

--[[ TBASE + math.floor((DIFFICULTY – DBASE) * ((TMAX - TBASE) / (DMAX - DBASE))) = TARGET

Explanation of terms:

TBASE = The target number you want at the lowest possible difficulty. DIFFICULTY = Difficulty level of the Stronghold. Currently, this is 10 thru 15. DBASE = The lowest possible difficulty setting a Stronghold. Currently, this is 10. TMAX = The target number you want at the highest difficulty. DMAX = The highest possible difficulty setting. TARGET = The number you’re seeking for the given difficulty. math.floor(X) = A lua function that rounds X down to the nearest integer, and returns it. The formula will almost always return a fraction, so this is necessary to give an integer parameter. ]]

--Forward base spawning interval
g_FB_Spawn_Iter = 20 + math.floor((g_DIFF - g_DBASE) * ((10 - 20) / (g_DMAX - g_DBASE)))


--elite guardsmen spawn %chance in streamer waves
g_Streamer_Elite = 15 + math.floor((g_DIFF - g_DBASE) * ((5 - 15) / (g_DMAX - g_DBASE)))


--total plasma rifles carried by streamer troops and initial attack troops
g_Streamer_plasma = 0 + math.floor((g_DIFF - g_DBASE) * ((4 - 0) / (g_DMAX - g_DBASE)))

--total grenade launchers carried by streamer troops and initial attack troops
g_Streamer_grenade = 0 + math.floor((g_DIFF - g_DBASE) * ((2 - 0) / (g_DMAX - g_DBASE)))


--frequency of armor harassers spawning
g_Armor_freq = 180 + math.floor((g_DIFF - g_DBASE) * ((90 - 180) / (g_DMAX - g_DBASE)))


--number of squads of guardsmen in the initial rush on the players base
g_Rush_count = 2 + math.floor((g_DIFF - g_DBASE) * ((3 - 2) / (g_DMAX - g_DBASE)))

--interval between each chimera being sent to players base in the initial rush
g_Rush_Interval = 15 + math.floor((g_DIFF - g_DBASE) * ((2 - 15) / (g_DMAX - g_DBASE)))


--Rule interval time between armor spawns in the stronghold defense rule
g_HQ_Armor_Inter = 180 + math.floor((g_DIFF - g_DBASE) * ((90 - 180) / (g_DMAX - g_DBASE)))

--Rule interval time between infanctry spawns in the stronghold defense rule
g_HQ_Infantry_Inter = 90 + math.floor((g_DIFF - g_DBASE) * ((30 - 60) / (g_DMAX - g_DBASE)))

--[[ define the "enemy" who will win if the player 'loses' ]] g_enemy = g_Player2

--[[Win condition Objective]]

end

--

--[[ the OnGameRestore() function is mandatory!, this will only get called after loading a game ]]

function OnGameRestore()

end


--[[ ON INITIALIZATION ]]

function OnInit()

--[[ RESEARCH LEVEL - sets the research level of the mission, locks researches, squads, and buildings for the appropriate mission number DOW specific!
 sets the research level of the mission, locks researches, squads, and buildings]]
Rule_SetResearchLevel( 4 )


--[[ SET AI - call the function to set the pregame state of the AI 
call the function to set the pregame state of the AI ]]
Rule_PresetAI()	


--[[ GET THE START PLAY MISSION READY TO ROLL ]]
Rule_Add( Rule_GameStart )	

Rule_AddOneShot(Rule_Opening_NIS, 0)


--[[ NIS PRESETS - turn off event cues, set the viewable space to black (faded out) and preset letterboxing 
turn off event cues, set the viewable space to black (faded out) and preset letterboxing ]]
WXP_OpeningNISPreset()


end

--[[ the Scar_AddInit(OnInit) function is mandatory! This registers your init function with scar. ]] Scar_AddInit(OnInit)


--[[ GAME RESTRICTIONS ]]

--[[ Disables, enables, and grants research items ]]

function Rule_SetResearchLevel( resLevel )

--[[ WXP Specific ]]
WXP_Restrict( resLevel )

end


--[[ PRESET AI ]]

function Rule_PresetAI()

--Cpu_EnableAll(false)
Cpu_Enable(g_Player2, true)	
Cpu_Enable(g_Player3, false)
Cpu_Enable(g_Player4, false)	
Cpu_Enable(g_Player5, false)
Cpu_Enable(g_Player6, true)
Cpu_Enable(g_Player7, false)

end


--[[ MUSIC ]]

function Rule_Start_Music()

--set the music	
t_IG_stronghold_music = {	"MU_IG_STR_ImpGd_perc_brass", "MU_IG_STR_ImpGd", "MU_IG_STR_ImpGd_perc", "MU_IG_STR_ImpGd_perc_str", 
											"MU_IG_STR_ImpGd_perc_voice"}

Playlist_Manager( PC_Music, t_IG_stronghold_music, true, true , {2, 4})


--set ambient sounds
t_IG_stronghold_ambient = {"ambient_city"}

Playlist_Manager( PC_Ambient, t_IG_stronghold_ambient, true, true , {5, 15})

end


--[[ START PLAY ]]

--[[ NOW TO KICK OFF THE ACTUAL MISSION ONCE THE OPENING NIS IS DONE ]]

function Rule_GameStart()

if g_firstrun then
	
	--[[ set resources ]]
	--Player_SetAllResources(g_Player1, 1000, 100, 14)  --TAKEN OUT,  apparently it messes up the "Industrial Production bonus".
		
	--[[ PREACTION ]]
	Rule_AddOneShot(Rule_Despawner, 0)
	
	--[[ DIFFICULTY LEVEL - gets the difficulty level from the UI and passes it into the function]]
	Rule_SetDifficultyLevel( Difficulty_Get() )
	
	--[[ Get the AI doing whatever after the NIS is over ]]
	Rule_StartAI()
	
	--[[creating Guard buildings]]
	Rule_AddOneShot(Rule_Create_HQ_Buildings,1)
	Rule_AddOneShot(Rule_Create_ForwardBase_Buildings,1)
	Rule_AddOneShot(Rule_Create_Islandbase_Buildings,1)
	Rule_AddOneShot(Rule_Create_Bridge_Buildings,1)
	Rule_AddOneShot(Rule_Create_NorthBridge_Buildings,1)
	Rule_AddOneShot(Rule_Upgrade_IG_List_Posts, 1)
	Rule_AddOneShot(Rule_Upgrade_IG_Turrets, 10)
	Rule_AddOneShot(Rule_Create_Armor_Buildings, 1)
	
	Rule_AddOneShot(Rule_Create_Island_Units, 0)
	
	--[[ Music ]]
	Rule_AddOneShot(Rule_Start_Music, 0)
	
	--[[exeptional rules that need to be activated here and not in the NIS]]
	Rule_AddIntervalDelay(Rule_Armor_Harrassers,g_Armor_freq,600)
	
	--[[Added to the End of the opening NIS
	--[[create Guard units]]
	Rule_AddOneShot(Rule_Create_Bridge_Units, 1)
	Rule_AddOneShot(Rule_Create_River_Guardsmen, 1)
	Rule_AddIntervalDelay(Rule_FB_Spawn_Infantry_Check, 30,5)		
	
	
	--[[create Player buildings]]
	Rule_AddOneShot(Rule_Create_Player_Buildings, 1)
	
	--[[create Player units]]
	Rule_AddOneShot(Rule_Create_Player_Units, 1)
	
	--[[Init Gameplay Rules]]
	Rule_AddOneShot(Rule_Initial_Rush_Step1, 15)
	
	Rule_AddOneShot(Rule_Lock_Relic,1)
	
	Rule_AddOneShot(Rule_CPU_Build_Restrictions, 1)
	
	Rule_AddIntervalExDelay(Rule_FB_Harasser_Spawning, 15, g_FB_Harasser_Limit, 60) 
	
	Rule_AddOneShot(Rule_Rooftop_Patrol_Spawner_OneShot,1)
	Rule_AddIntervalDelay(Rule_FB_Squad_Patrol2,10,35)		
	Rule_AddIntervalDelay(Rule_2nd_Half_Activation,2,30)
	
	Rule_AddIntervalDelay(Rule_Strat_Capture_Squad_Manager,10,180)
	Rule_AddIntervalDelay(Rule_Engineer_Spawner,90, 300)
	Rule_AddInterval(Rule_FB_Detection, 2)
	Rule_AddInterval(Rule_Armor_Base_Detect, 2)
	Rule_AddInterval(Rule_River_Checker, 1)
	
	Rule_AddOneShot(Rule_Create_Heavy_Weapons_Squads, 20)
	
	Rule_AddIntervalDelay(Rule_Airstrike_Checker, 2, 60)
	Rule_AddIntervalDelay(Rule_Airstrike_Control, 180, 300)
	
	Rule_AddIntervalDelay(Rule_Assassin_Manager, 20, 900)
	
	Rule_AddIntervalDelay(Rule_Research_Step_3, 60, 600)
	
	--[[Assign Inital Objectives]]
	Rule_AddIntervalDelay(Rule_Objective_Conquer_Stronghold,5,10)
	
	--[[IE Triggers]]
	Rule_AddOneShot(Rule_Opening_Discussion,5)
	
	--[[ Setup Game Timers]]
	Rule_AddOneShot(Rule_UI_Timer,1)
	Rule_AddInterval(Rule_Timer,1)
	
	--[[ Set Endgame checks]]
	Rule_AddIntervalDelay(Rule_EndGame_Lose,5,60)]]
	
	Player_GrantResearch(g_Player2, "guard_research_assassin_infiltrate")
	
	
	--[[ Clean up ]]
	Rule_Remove(Rule_GameStart)
	
	
	--[[ TEST INITS ]]
	--Rule_AddIntervalDelay(test, 20, 15)		
	
	
	--FOW_RevealAll()
	
end

end


--[[ DIFFICULTY ]]

function Rule_SetDifficultyLevel( difficultyLevel )

--[[ STATIC MODIFIERS ]]
-- Use this space to set any Static Modifiers. ifiers that will not change with the difficulty setting.

--Difficulty_SetForAll( difficultyLevel )
--Difficulty_SetForPlayer(g_Player1, difficultyLevel)
--Difficulty_SetForPlayer(g_Player2, difficultyLevel)


--[[ DIFFICULTY GENERAL RULES ]]
--[[ Types of things that can me done	include: 
a) adding resource values
b) changing variables for the number of starting units a player recieves 
b) or even activating new objectives (although we refrained from this in DoW as the increased testing requirements it dictates)
]]	
-- easy
if difficultyLevel == DIFFICULTY_EASY then
	
	g_Difficulty = 1
	
-- medium
elseif difficultyLevel == DIFFICULTY_NORMAL then
	
	g_Difficulty = 2
	
-- hard
elseif difficultyLevel == DIFFICULTY_HARD then
	
	g_Difficulty = 3
	
end

end


--[[AI Restrictions]]


--[[Precaching]]


--[[ AI ]]

function Rule_StartAI()

Cpu_Enable(g_Player2, true)	

Cpu_EnableComponent(g_Player2, true, CT_Resourcing)
Cpu_EnableComponent(g_Player2, false, CT_BuildBuildings)
Cpu_EnableComponent(g_Player2, false, CT_BuildUnits)
Cpu_EnableComponent(g_Player2, false, CT_BuildResearch)
Cpu_EnableComponent(g_Player2, false, CT_BuildAddOns)
Cpu_EnableComponent(g_Player2, true, CT_Tactics)


Cpu_Enable(g_Player3, true)	

Cpu_EnableComponent(g_Player3, false, CT_Resourcing)
Cpu_EnableComponent(g_Player3, false, CT_BuildBuildings)
Cpu_EnableComponent(g_Player3, false, CT_BuildUnits)
Cpu_EnableComponent(g_Player3, false, CT_BuildResearch)
Cpu_EnableComponent(g_Player3, false, CT_BuildAddOns)
Cpu_EnableComponent(g_Player3, true, CT_Tactics)

--rebel Attacker AI
Cpu_Enable(g_Player4, false)

--Cpu_SetDifficulty(g_Player4, AD_Insane)

Cpu_EnableComponent(g_Player4, false, CT_Resourcing)
Cpu_EnableComponent(g_Player4, false, CT_BuildBuildings)
Cpu_EnableComponent(g_Player4, false, CT_BuildUnits)
Cpu_EnableComponent(g_Player4, false, CT_BuildResearch)
Cpu_EnableComponent(g_Player4, false, CT_BuildAddOns)
Cpu_EnableComponent(g_Player4, false, CT_Tactics)
Cpu_EnableComponent(g_Player4, false, CT_Attacking)

-- Main IG attacker AI
Cpu_Enable(g_Player6, true)

Cpu_SetDifficulty(g_Player6, AD_Insane)

Cpu_EnableComponent(g_Player6, false, CT_Resourcing)
Cpu_EnableComponent(g_Player6, false, CT_BuildBuildings)
Cpu_EnableComponent(g_Player6, false, CT_BuildUnits)
Cpu_EnableComponent(g_Player6, false, CT_BuildResearch)
Cpu_EnableComponent(g_Player6, false, CT_BuildAddOns)
Cpu_EnableComponent(g_Player6, true, CT_Tactics)
Cpu_EnableComponent(g_Player6, true, CT_Attacking)

end

function Rule_Give_AI_Research()

Player_GrantResearch(g_Player2,"guard_upgrade_guardsmen_range")
Player_GrantResearch(g_Player2,"guard_upgrade_power_2")
Player_GrantResearch(g_Player2,"guard_upgrade_requisition_2")
Player_GrantResearch(g_Player2,"guard_research_command_squad_size")
Player_GrantResearch(g_Player2,"guard_full_scale_war")
Player_GrantResearch(g_Player2,"guard_enable_strafing_run")

end

function Rule_Give_AI_Research_Step2()

Player_GrantResearch(g_Player2,"guard_upgrade_weapon_specialization")
Player_GrantResearch(g_Player2,"guard_guardsman_morale_2")
Player_GrantResearch(g_Player2,"guard_upgrade_guardsmen_health")

end

function Rule_Give_AI_Research_Step3()

Player_GrantResearch(g_Player2,"guard_research_kasrkin_armor")
Player_GrantResearch(g_Player2,"guard_research_kasrkin_speed")
Player_GrantResearch(g_Player2,"guard_enable_leader_accuracy_bonus")
Player_GrantResearch(g_Player2,"guard_upgrade_ogryn_melee")

end


--[[ TRACK PERSISTENT CHARACTERS ]]

-- this section keeps track of the characters, and controls losing when they die. function Rule_TrackCharacters()

end



--[[ CORE GAME ]]


function Rule_Despawner()

EGroup_DeSpawn("eg_Outro_Leman_Fires")
EGroup_DeSpawn("eg_Mid_NIS_fires")

--despawn explosion entities
for i = 1,5 do
	
	EGroup_DeSpawn("eg_Titan_Explosion"..i)
	
end

end

--turns on various prox checks and other rules exclusive to the second half of the map. Activation take place when the player successfully crosses the river. function Rule_2nd_Half_Activation() for i = 1,5 do

	if Player_AreSquadsNearMarker(g_Player1,"mkr_BridgeHead_North"..i) then
		
		Rule_AddOneShot(Rule_Second_Half_IE,1)
		
		Rule_AddOneShot(Rule_Create_HQ_Buildings, 1)
		Rule_AddOneShot(Rule_Upgrade_HQ_Turrets, 5)
		Rule_AddOneShot(Rule_Create_HQ_Units,5)
		Rule_AddInterval(Rule_Stronghold_Defense,3)
		
		Rule_AddInterval(Rule_IG_Troops_Streamer, 30)
		
		--Rule_AddIntervalDelay(Rule_EndGame_Win,5,60)
		
		Rule_AddInterval(Rule_Baneblade_Respawn,10)
		Rule_AddIntervalDelay(Rule_Baneblade_Patrol_Movement_Handler, 60, 10)
		
		Rule_AddOneShot(Rule_Create_Rebel_Buildings,1)
		Rule_AddOneShot(Rule_Create_Rebel_Units, 5)
		Rule_AddInterval(Rule_Rebel_Base_Prox_Check,2)		
		
		Rule_AddOneShot(Rule_Engineer_oneshot, 30)
		
		Rule_AddOneShot(Rule_Create_Gen_Defenders, 3)
		
		--[[Titan Firing controls]]
		Rule_AddInterval(Rule_Titan_Power,1)
		Rule_AddInterval(Rule_Titan_Fire_Control, 3)
		
		if g_Slagbase_created == false then
			
			Rule_AddOneShot(Rule_Create_Slagbase_Buildings,1)
			Rule_AddOneShot(Rule_Create_Slagbase_Units, 2)
			
			g_Slagbase_created = true
			
		end
		
		Rule_Remove(Rule_2nd_Half_Activation)
		
		g_2nd_half_activated = true
		
		break
		
	end
	
end

end

function Rule_CPU_Build_Restrictions()

t_CPU_Players = {--[[1]] g_Player2, --[[2]] g_Player3, --[[3]] g_Player4, --[[4]]g_Player6}

--brute force solution to ensure the AI players cannot build anything but listening posts.
t_CPU_Building_Rectrictions = {	"guard_hq", "guard_infantry", "guard_mechanized", "guard_mines", "guard_mars_pattern", "guard_plasma_generator", 
													"guard_tactica", "guard_thermo_plasma", "guard_turret_heavy_bolter"}

for i = 1,table.getn(t_CPU_Players) do
	
	Player_RestrictBuildingList(t_CPU_Players[i], t_CPU_Building_Rectrictions)
	
end

end

function Rule_Research_Step_3()

if g_ticker >= 2700 then
	
	Rule_AddOneShot(Rule_Give_AI_Research_Step3, 60)
	
	Rule_Remove(Rule_Research_Step_3)
	
end

end

function Rule_River_Checker()

if g_Slagbase_created == false then
	
	if Player_AreSquadsNearMarker(g_Player1, "mkr_River_Checker") then
		
		Rule_AddOneShot(Rule_Create_Slagbase_Buildings,1)
		Rule_AddOneShot(Rule_Create_Slagbase_Units, 2)
		
		Rule_Remove(Rule_River_Checker)
		
		g_Slagbase_created = true
		
	end
	
else
	
	Rule_Remove(Rule_River_Checker)
	
end

end

function Rule_UI_Timer()

UI_ShowCount("Game_Timer", g_Player1, 2630000, g_UI_Timer)

Rule_AddInterval(Rule_UI_Timer_Tick, 60)

end

function Rule_UI_Timer_Tick()

g_UI_Timer = g_UI_Timer + 1
UI_ShowCountUpdateDxp("Game_Timer", g_UI_Timer, 2630000)

end

function Rule_Timer()

-- general count up timer.
g_ticker = g_ticker + 1

-- reduces the time left before a new sg group can spawn to recaputre strategic points in Rule_Create_Capture_Squad
if g_Strat_Capture_Repawn > 0 then
	
	g_Strat_Capture_Repawn = g_Strat_Capture_Repawn - 1
	
end


--Titan Cannon controls
if g_Titan_activated == true then
	
	--if not delaying for firing effects, tick down refire timer
	if g_Titan_FX_timer_Delay == false then
		
		if g_Titan_timer > 0 then
			
			g_Titan_timer = g_Titan_timer - 1
			UI_ShowCountUpdateDxp("Titan_Refire_Timer", g_Titan_timer, 2630010)
			
			if g_Titan_timer == 8 and g_titan_power == true then
				
				Anim_PlayEGroupAnim(EGroup_FromName("eg_Titan_Audio_Warning"), "audio_warning")
				
				--turn on the visual idle (puts fire and smoke in the barrels)
				Anim_PlayEGroupAnim(EGroup_FromName("eg_Titan_Mega"), "idle")	
				
			end
			
		end
		
	--delay for titan firing effects
	else 
		
		if g_Titan_FX_timer_counter > 0 then
			g_Titan_FX_timer_counter = g_Titan_FX_timer_counter - 1
		end
		
		--delay done, set time and global varible to allow countdown to start. reset delay value.
		if g_Titan_FX_timer_counter == 0 then
			
			g_Titan_FX_timer_Delay = false
			
			g_Titan_timer = g_Titan_Power_Formula --[[90 second by default, modified in Rule_Titan_Power_Formula]]
			
			g_Titan_FX_timer_counter = 4
			
		end
		
	end
	
end


--delay timer for Artillery warning audio
if g_artillery_warning_timer > 0 then
	
	g_artillery_warning_timer = g_artillery_warning_timer - 1
	
end


--NIS play timer - If this value is above 0, it will stop other events from messing with any NIS that are playing
if g_NIS_Timer > 0 then
	
	g_NIS_Timer = g_NIS_Timer - 1
	
end

--stronghold defender kasrkin respawn delay timer
if g_Stronghold_Kasrkin_Timer > 0 then
	
	g_Stronghold_Kasrkin_Timer = g_Stronghold_Kasrkin_Timer - 1
	
end

--stronghold defender ogryn respawn delay timer
if g_Stronghold_Ogryn_Timer > 0 then
	
	g_Stronghold_Ogryn_Timer = g_Stronghold_Ogryn_Timer - 1
	
end

--titan player fire button delay Timer
if g_Titan_button_timer > 0 and g_player_has_gens == true then
	
	g_Titan_button_timer = g_Titan_button_timer - 1
	
	UI_ShowCountUpdateDxp("Titan_Button_Refire_Timer", g_Titan_button_timer, 2630010)
	
	if g_Titan_button_timer == 8 then
		
		Anim_PlayEGroupAnim(EGroup_FromName("eg_Titan_Audio_Warning"), "audio_warning")
		
		--turn on the visual idle (puts fire and smoke in the barrels)
		Anim_PlayEGroupAnim(EGroup_FromName("eg_Titan_Mega"), "idle")
		
	end
	
end

--artillery controler timer
if g_Artillery_control_timer > 0 then
	
	g_Artillery_control_timer = g_Artillery_control_timer - 1
	
end

--IG Skirmisher troop special unit spawn limiter
if g_skirmisher_special > 0 then
	
	g_skirmisher_special = g_skirmisher_special -1
	
end

--assassin spawn limiter
if g_assassin_timer > 0 then
	
	g_assassin_timer = g_assassin_timer - 1
	
end

--rebel IE limiter
if g_Rebel_IE > 0 then
	
	g_Rebel_IE = g_Rebel_IE - 1
	
end	

--titan gens IE delay Timer
if g_Gen_IE_Delay > 0 then
	
	g_Gen_IE_Delay = g_Gen_IE_Delay - 1
	
end

--strategic point recapture IE delay timer
if g_strat_capture_IE_timer > 0 then
	
	g_strat_capture_IE_timer = g_strat_capture_IE_timer - 1
	
end

-- stronghold kasrkin spawn limiter
if g_Stronghold_Kasrkin_spawned == true then
	
	if g_Stronghold_Kasrkin_respawn > 0 then
		
		g_Stronghold_Kasrkin_respawn = g_Stronghold_Kasrkin_respawn - 1
		
	end
	
	if g_Stronghold_Kasrkin_respawn == 0 then
		
		g_Stronghold_Kasrkin_spawned = false
		
	end
	
	
end

-- stronghold ogryn spawn limiter
if g_Stronghold_Ogryn_spawned == true then
	
	if g_Stronghold_Ogryn_respawn > 0 then
		
		g_Stronghold_Ogryn_respawn = g_Stronghold_Ogryn_respawn - 1
		
	end
	
	if g_Stronghold_Ogryn_respawn == 0 then
		
		g_Stronghold_Ogryn_spawned = false
		
	end
	
	
end

--Stronghold baneblade limiter
if g_BaneBlade_respawn > 0 then
	
	g_BaneBlade_respawn = g_BaneBlade_respawn - 1
	
end

end

function Rule_Initial_Rush_Step1()

if g_DIFF > 13 then
	
	g_rush_spawn_iter = 4
	
else
	
	g_rush_spawn_iter = 3
	
end

g_elite_spawn = false
g_rush_kasrkin = false

--create chimeras and infantry, then load them.
for i = 1,g_rush_spawn_iter do
	
	Util_CreateSquadsAtMarker(g_Player2, "sg_Rush_Chimera"..i, "guard_squad_chimera", "mkr_Chimera_Spawn"..i, 1)
	Cpu_LockSGroupAcrossPlayers("sg_Rush_Chimera"..i)
	Cmd_SetStance("sg_Rush_Chimera"..i, STANCE_Attack)
	
	local rand_squadsize = World_GetRand(6,8)
	
	for k = 1,g_Rush_count do
		
		--insert an elite squad into the 2nd and 4th chimera to make 15 really tough
		if k == 3 and g_DIFF == 15 then
			
			if g_elite_spawn == true then
				
				--toggle the variable back so the next spawn will be guardsmen
				g_elite_spawn = false
				
				--first elite squad is kasrkin
				if g_rush_kasrkin == false then
					
					JMUtil_Spawn_Upgraded_Kasrkin(g_Player2, "sg_Rush_Infantry_SG"..i..k, "mkr_Rush_Spawn"..i, rand_squadsize, g_Streamer_plasma, g_Streamer_grenade, false, STANCE_Attack, false)
					SGroup_AddGroup(SGroup_CreateIfNotFound("sg_Rush_Infantry"..i), "sg_Rush_Infantry_SG"..i..k)
					
					g_rush_kasrkin = true
					
				--second elite squad is ogryn
				elseif g_rush_kasrkin == true then
					
					Util_CreateSquadsAtMarkerEx(g_Player2, "sg_Rush_Infantry_SG"..i..k, "guard_squad_ogryns", "mkr_Rush_Spawn"..i, 1, 6)
					Cmd_SetStance("sg_Rush_Infantry_SG"..i..k, STANCE_Attack)
					Cmd_SetMeleeStance("sg_Rush_Infantry_SG"..i..k, MSTANCE_Assault)
					SGroup_AddGroup(SGroup_CreateIfNotFound("sg_Rush_Infantry"..i), "sg_Rush_Infantry_SG"..i..k)
					
					--destroy the last guardsmen squad made so the ogryn can fit in the chimera - ogryn take two slots in a chimera instead of one slot like guardsmen.
					SGroup_DeSpawn("sg_Rush_Infantry_SG"..i..k-1)
					
				end
				
			elseif g_elite_spawn == false then
				
				--uses up a spawn with regular guardmens and toggles the variable so the next spawn will be elite.
				g_elite_spawn = true
				
				JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Rush_Infantry_SG"..i..k, "mkr_Rush_Spawn"..i, rand_squadsize, g_Streamer_plasma, g_Streamer_grenade, false, STANCE_Attack, false)
				SGroup_AddGroup(SGroup_CreateIfNotFound("sg_Rush_Infantry"..i), "sg_Rush_Infantry_SG"..i..k)
				
			end
			
		else
			
			JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Rush_Infantry_SG"..i..k, "mkr_Rush_Spawn"..i, rand_squadsize, g_Streamer_plasma, g_Streamer_grenade, false, STANCE_Attack, false)
			SGroup_AddGroup(SGroup_CreateIfNotFound("sg_Rush_Infantry"..i), "sg_Rush_Infantry_SG"..i..k)
			
		end
		
	end
	--Util_CreateSquadsAtMarkerEx(g_Player2, "sg_Rush_Infantry"..i, "guard_squad_guardsmen", "mkr_Rush_Spawn"..i, g_Rush_count, 8)
	Cpu_LockSGroupAcrossPlayers("sg_Rush_Infantry"..i)
	Cmd_SetStance("sg_Rush_Infantry"..i, STANCE_Attack)
	
	Cmd_EnterTransport( "sg_Rush_Infantry"..i, "sg_Rush_Chimera"..i)
	
end

Rule_AddOneShot(Rule_Initial_Rush_Step2, 5)

end

function Rule_Initial_Rush_Step2()

--move the chimera forward a slight distance.  
--In certain instances guardsmen get stuck on the chimera while trying to load up,  moving the chimeras forwards a slight amount allows them to correct themselves and load.
for i = 1,g_rush_spawn_iter do
	
	Cmd_MoveToMarker("sg_Rush_Chimera"..i, "mkr_Chimera_Safety"..i)
	
end

--call the final movement rule.  3 intervals dynamically spaced apart (based on military strength of province),  with another 5 second delay before the rule starts to allow any reamining guardsmen to load.
Rule_AddIntervalExDelay(Rule_Initial_Rush_Step3, g_Rush_Interval, g_rush_spawn_iter, 5)

end

function Rule_Initial_Rush_Step3()

Cmd_EmptyTransport("sg_Rush_Chimera"..g_Chimera_Rush, Marker_GetPosition(Marker_FromName("mkr_Rush_Point"..g_Chimera_Rush, "basic_marker")))

g_Chimera_Rush = g_Chimera_Rush + 1

end

function Rule_Lock_Relic()

Cpu_LockEGroup(g_Player3, "eg_Relic")
Cpu_LockEGroup(g_Player4, "eg_Relic")

end

function Rule_Baneblade_Respawn()

if EGroup_Exists("eg_IG_HQ_Mars") and EGroup_IsEmpty("eg_IG_HQ_Mars") == false then
	
	if g_BaneBlade_alive == false then
		
		if g_BaneBlade_respawn == 0 then
			
			Util_CreateSquadsAtMarker(g_Player2, "sg_HQ_BaneBlade", "guard_squad_baneblade", "mkr_HQ_Mars_Spawn", 1)
			
			Cpu_LockSGroupAcrossPlayers("sg_HQ_BaneBlade")
			
			Cmd_AttackMoveMarker("sg_HQ_BaneBlade", "mkr_HQ_Door2")
			
			g_BaneBlade_alive = true
			
			Rule_Remove(Rule_Baneblade_Respawn)
			
		end
		
	end
	
else
	
	Rule_Remove(Rule_Baneblade_Respawn)
	Rule_Remove(Rule_Baneblade_Patrol_Movement_Handler)
	
end

end

function Rule_Baneblade_Patrol_Movement_Handler()

if SGroup_Exists("sg_HQ_BaneBlade") and SGroup_IsEmpty("sg_HQ_BaneBlade") == false then
	
	Cmd_SetStance("sg_HQ_BaneBlade", STANCE_Attack)
	
	--Baneblade won't move if they are currently fighting someone.
	if not (Squad_GetActiveCommand(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_HQ_BaneBlade"), 1)) == SQUADSTATEID_Combat) then
		
		--assign new  marker positions to move to.
		Cmd_AttackMoveMarker("sg_HQ_BaneBlade", "mkr_HQ_Patrol"..g_baneblade_patrol)
		
		g_baneblade_patrol = g_baneblade_patrol + 1
		
	end
	
	if g_baneblade_patrol > 4 then
		
		g_baneblade_patrol = 1
		
	end
	
end

--if the Baneblade has been destroyed, set the counter and launch the respawn rule
if SGroup_Exists("sg_HQ_BaneBlade") == false or SGroup_Exists("sg_HQ_BaneBlade") and SGroup_IsEmpty("sg_HQ_BaneBlade") then
	
	if Rule_Exists(Rule_Baneblade_Respawn) == false then
		
		g_BaneBlade_respawn = 450
		
		Rule_AddInterval(Rule_Baneblade_Respawn,1)
		
		g_BaneBlade_alive = false
		
	end
	
end

end

function Rule_FB_Detection()

if Player_AreSquadsNearMarker(g_Player1, "mkr_FB_Prox") then
	
	Rule_AddOneShot(Rule_FB_Detect_IE,1)
	
	--add objective
	Rule_AddInterval(Rule_Objective_Destroy_Forward_Base,10)
	
	Rule_Remove(Rule_FB_Detection)
	
end

end

function Rule_FB_Harasser_Manager()

if SGroup_Exists("sg_FB_Harasser") and SGroup_IsEmpty("sg_FB_Harasser") == false then
	
	--run movement logic
	Rule_AddOneShot(Rule_FB_Harasser_Mover,1)
	
elseif SGroup_Exists("sg_FB_Harasser") == false or SGroup_Exists("sg_FB_Harasser") and SGroup_IsEmpty("sg_FB_Harasser") then
	
	if g_FB_Destroyed == false then
		
		if Rule_Exists(Rule_FB_Harasser_Spawning) == false then
			
			--run squad creation at increaseing intervals to ramp up difficulty.
			Rule_AddIntervalExDelay(Rule_FB_Harasser_Spawning, g_FB_Spawn_Iter, g_FB_Harasser_Limit, g_FB_spawning_delay) 
			
			--shorten the spawn delay each time a new wave is ordered to be created. Starts at 30 seconds.
			if g_FB_spawning_delay > 0 then
				
				g_FB_spawning_delay = g_FB_spawning_delay - 10
				
			end
			
		end
		
		Rule_Remove(Rule_FB_Harasser_Manager)
		
	end
	
end

end

--Forward base spawning waves of infantry to harass the players HQ function Rule_FB_Harasser_Spawning()

SGroup_CreateIfNotFound("sg_FB_Harasser")

for i = 1,2 do
	
	if EGroup_IsEmpty("eg_IG_FB_Barracks"..i) == false then
		
		SGroup_CreateIfNotFound("sg_FB_Harasser")
		
		--spawn guardsmen squad into the harrasser group.
		
		local randSS = World_GetRand(6,8)
		
		JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_FB_HarasserSG"..g_FB_SG, "mkr_NPC_FB_Spawn"..i, randSS, 0, 0, true, STANCE_Attack, false)
		SGroup_AddGroup("sg_FB_Harasser", "sg_FB_HarasserSG"..g_FB_SG)
		
		--toggle guardsman squads (at random during spawn) to fight melee to help mix up the action.
		JMUtil_Random_Melee_Stance(4, "sg_FB_HarasserSG"..g_FB_SG)
		
		g_FB_SG = g_FB_SG + 1
		
		--add sergeants from the third wave on.
		if g_FB_Harrassers_Waves > 2 then
			
			SGroup_AddLeaders("sg_FB_Harasser")
			
		end
		
		--add a half sized ogryn or kasrkin squad (with seargent) at random
		if g_FB_Harrassers_Waves  >= 7 and Rule_Exists(Rule_FB_Spawn_Special) == false then
			
			Rule_AddOneShot(Rule_FB_Spawn_Special, 10)
			
		end			
		
		--do not repeat if the first pass was successful
		break
		
	end
	
end

--once the spawn limit has been hit, launch the manager rule and increase the limit for the next batch of spawns if needed.
if SGroup_CountSpawned("sg_FB_Harasser") == g_FB_Harasser_Limit then
	
	if Rule_Exists(Rule_FB_Harasser_Manager) == false then
		Rule_AddInterval(Rule_FB_Harasser_Manager, 10)
	end
	
	--ramp up the harasser squad count size to a maximum of 4 squads
	if g_FB_Harasser_Limit  < 4 then
		
		g_FB_Harasser_Limit = g_FB_Harasser_Limit + 1
		
	end
	
	-- add to the count of the number of harrassers waves spawned
	g_FB_Harrassers_Waves = g_FB_Harrassers_Waves + 1
	
	g_FB_SG = 1
	
end

end

function Rule_FB_Spawn_Special()

SGroup_CreateIfNotFound("sg_FB_Harasser_Special")

no_barracks = false

-- used to determine whether ogryn or kasrkins are spawned in the wave.  33%  chance from the 3rd wave onwards.  
local randspawn = World_GetRand(1,3)

if EGroup_IsEmpty("eg_IG_FB_Barracks2") == false then
	
	spawn_mkr = "mkr_NPC_FB_Spawn2"
	
elseif EGroup_IsEmpty("eg_IG_FB_Barracks1") == false then
	
	spawn_mkr = "mkr_NPC_FB_Spawn1"
	
else
	
	no_barracks = true
	
end

if no_barracks == false then
	
	--create ogryns
	if randspawn == 1 and SGroup_IsEmpty("sg_FB_Harasser_Special") then
		
		Util_CreateSquadsAtMarkerEx(g_Player2, "sg_FB_Harasser_Special", "guard_squad_ogryns", spawn_mkr, 1, g_FB_Harasser_Special_Ogryn)
		SGroup_AddLeaders("sg_FB_Harasser_Special")
		Cpu_LockSGroupAcrossPlayers("sg_FB_Harasser_Special")
		SGroup_AddGroup("sg_FB_Harasser", "sg_FB_Harasser_Special")
		
		--ramp up the ogryns spawned each time to a maximum of 3
		if g_FB_Harasser_Special_Ogryn < 3 then
			
			g_FB_Harasser_Special_Ogryn = g_FB_Harasser_Special_Ogryn + 1
			
		end
		
	--create kasrkin
	elseif randspawn == 2 and SGroup_IsEmpty("sg_FB_Harasser_Special") then
		
		Util_CreateSquadsAtMarkerEx(g_Player2, "sg_FB_Harasser_Special", "guard_squad_kasrkin", spawn_mkr, 1, g_FB_Harasser_Special_Kasrkin)
		SGroup_AddLeaders("sg_FB_Harasser_Special")
		Cpu_LockSGroupAcrossPlayers("sg_FB_Harasser_Special")
		SGroup_AddGroup("sg_FB_Harasser", "sg_FB_Harasser_Special")
		
		--ramp up the kasrkin spawned each time to a maximum of 3
		if g_FB_Harasser_Special_Kasrkin < 3 then
			
			g_FB_Harasser_Special_Kasrkin = g_FB_Harasser_Special_Kasrkin + 1
			
		end
		
	end
	
end

end

function Rule_FB_Harasser_Mover()

--resets the global variables used to tell if the harassers are stuck in the field
g_FB_Harasser_Prox1 = false
g_FB_Harasser_Prox2 = false
g_FB_Harasser_Prox3 = false
g_FB_Harasser_Prox4 = false

--used to generate random marker location for harassers to attack at player's HQ
local rand1 = World_GetRand(1,3)

--random chance to activate a IE, returning 1 triggers the IE.
local rand4 = World_GetRand(1,2)

--assign the first move order if the units have been created and are idleing in the base
if Prox_AnySquadNearMarker("sg_FB_Harasser", "mkr_NPC_FB_Spawn1") and SGroup_CheckActiveCommand("sg_FB_Harasser", SQUADSTATEID_Idle, false) then
	
	Cmd_AttackMoveMarker("sg_FB_Harasser","mkr_Harasser_Attack_Point_Rally"..rand1)
	
elseif Prox_AnySquadNearMarker("sg_FB_Harasser", "mkr_NPC_FB_Spawn2") and SGroup_CheckActiveCommand("sg_FB_Harasser", SQUADSTATEID_Idle, false) then
	
	Cmd_AttackMoveMarker("sg_FB_Harasser","mkr_Harasser_Attack_Point_Rally"..rand1)
	
elseif Prox_AnySquadNearMarker("sg_FB_Harasser", "mkr_Harasser_Attack_Point_Rally1") then
	
	Cmd_AttackMoveMarker("sg_FB_Harasser","mkr_Harasser_Attack_Point1")
	
	if Rule_Exists(Rule_FB_IE_Taunts) == false then
		--launch the random IE taunt event
		Rule_AddOneShot(Rule_FB_IE_Taunts, 15)
		
	end
	
	g_FB_Harasser_Prox1 = true
	g_FB_Harasser_count = 0
	
elseif Prox_AnySquadNearMarker("sg_FB_Harasser", "mkr_Harasser_Attack_Point_Rally2") then
	
	local rand2 = World_GetRand(1,2)
	
	g_FB_Harasser_Prox2 = true
	g_FB_Harasser_count = 0
	
	-- sqaud may either move to point 2 or 3 from here, chosen at random.  This is mainly a geo constraint workaround.
	if rand2 == 1 then
		
		Cmd_AttackMoveMarker("sg_FB_Harasser","mkr_Harasser_Attack_Point2")
		
	elseif rand2 == 2 then
		
		Cmd_AttackMoveMarker("sg_FB_Harasser","mkr_Harasser_Attack_Point3")
		
	end		
	
	if rand4 == 1 then
		
		if Rule_Exists(Rule_FB_IE_Taunts) == false then
			--launch the random IE taunt event
			Rule_AddOneShot(Rule_FB_IE_Taunts, 15)
			
		end
		
	end
	
elseif Prox_AnySquadNearMarker("sg_FB_Harasser", "mkr_Harasser_Attack_Point_Rally3") then
	
	Cmd_AttackMoveMarker("sg_FB_Harasser","mkr_Harasser_Attack_Point4")
	
	if rand4 == 1 then
		
		if Rule_Exists(Rule_FB_IE_Taunts) == false then
			--launch the random IE taunt event
			Rule_AddOneShot(Rule_FB_IE_Taunts, 15)
			
		end
		
	end
	
	g_FB_Harasser_Prox3 = true
	g_FB_Harasser_count = 0
	
--move randomly around the players base.  Avoids the harassers hanging around just out of range of things to attack, keeping them active and lifelike.
elseif Prox_AnySquadNearMarker("sg_FB_Harasser", "mkr_Player_Base_Grabber") then
	
	Util_AttackMoveMarkerRandomRadius("sg_FB_Harasser", "mkr_Player_Base_Grabber")
	
	g_FB_Harasser_Prox4 = true
	g_FB_Harasser_count = 0
	
elseif g_FB_Harasser_Prox1 == false and g_FB_Harasser_Prox2 == false and g_FB_Harasser_Prox3 == false and g_FB_Harasser_Prox4 == false then
	
	g_FB_Harasser_count = g_FB_Harasser_count + 1
	
end

local rand3 = World_GetRand(1,4)

--if the counter has registered an existing group in the field that hasn't moved for some time, then it assumes they are "stuck" and gives them a move command
if 	g_FB_Harasser_count >= 2 then
	
	if SGroup_IsEmpty("sg_FB_Harasser") == false then
		
		Cmd_AttackMoveMarker("sg_FB_Harasser","mkr_Harasser_Attack_Point"..rand3)
		
	end
	
end

if EGroup_IsEmpty("eg_IG_FB_Barracks1") and EGroup_IsEmpty("eg_IG_FB_Barracks2") then
	
	--move any remaining squads in the field under the control of this rule to the player1 HQ.
	if SGroup_IsEmpty("sg_FB_Harasser") == false then
		
		Cmd_AttackMoveMarker("sg_FB_Harasser","mkr_Harasser_Attack_Point"..rand3)
		
	end
	
	--remove manager when the forward base has been destroyed.
	if Rule_Exists(Rule_FB_Harasser_Manager) then
		
		Rule_Remove(Rule_FB_Harasser_Manager)
		
	end
	
end

end

function Rule_Assassin_Manager()

if SGroup_Exists("sg_Assassin") and SGroup_IsEmpty("sg_Assassin") == false then
	
	--run movement logic
	Rule_AddOneShot(Rule_Assassin_Mover,1)
	
elseif SGroup_Exists("sg_Assassin") == false or SGroup_Exists("sg_Assassin") and SGroup_IsEmpty("sg_Assassin") then
	
	if g_assassin_timer == 0 then
		
		if g_assassin_first_spawn == true then
			
			if Rule_Exists(Rule_Player_leader_checker) == false then
				
				Rule_AddInterval(Rule_Player_leader_checker, 5)
				
			end
			
			g_assassin_first_spawn = false
			
		--only spawn when a commander is on the field.
		elseif SGroup_Exists("sg_leader") and SGroup_Count("sg_leader") > 0 then
			
			--run squad creation. 
			Rule_AddOneShot(Rule_Assassin_Spawning,1)
			
			g_assassin_timer = 900
			
		end
		
	end
	
end

end

function Rule_Player_leader_checker()

local blueprinttable = Util_MakeBlueprintTable(g_player_leader)

--clear out the potentials group as a precaution, if it exists.
if SGroup_Exists("sg_potential_leader") then
	
	SGroup_Clear("sg_potential_leader")
	
end

--add all player units to the master SG for checking.
SGroup_AddGroup(SGroup_CreateIfNotFound("sg_leader_check"),Player_GetSquads(g_Player1))

--check for presence of leader unit
if SGroup_ContainsBlueprints("sg_leader_check", blueprinttable, false) then
	
	--must count spawned to avoid trying to access despawned units
	local count = SGroup_CountSpawned("sg_leader_check")
	
	--sift through all units to find the leader unit. Once found, add to identifying SG so the assassin can attack it.
	for i = 1,count do
		
		SGroup_Add(SGroup_CreateIfNotFound("sg_potential_leader"),SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_leader_check"), i))
		
		if SGroup_ContainsBlueprints("sg_potential_leader", blueprinttable, true) then
			
			SGroup_AddGroup(SGroup_CreateIfNotFound("sg_leader"), "sg_potential_leader")
			
			SGroup_Clear("sg_potential_leader")
			
			--Now that it is established that the commander exists, add a check to trigger the commander death IE when he is killed.
			if Rule_Exists(Rule_Leader_Death_Check) == false then
				
				Rule_AddInterval(Rule_Leader_Death_Check, 1)
				
			end
			
			break
			
		else
			
			SGroup_Clear("sg_potential_leader")
			
		end
		
	end
	
end

end

function Rule_Leader_Death_Check()

if SGroup_Exists("sg_leader") == false or SGroup_Exists("sg_leader") and SGroup_IsEmpty("sg_leader") then
	
	Util_StartIntel(EVENTS.IE_Assassinate_Complete)
	
	Rule_Remove(Rule_Leader_Death_Check)
	
	Rule_Remove(Rule_Assassin_Manager)
	
	if Rule_Exists(Rule_Assassin_Restart) == false then
		Rule_AddOneShot(Rule_Assassin_Restart, 10)
	end
	
end

end

function Rule_Assassin_Mover()

if SGroup_Exists("sg_leader") and SGroup_IsEmpty("sg_leader") == false then
	
	if SGroup_Exists("sg_Assassin") and SGroup_IsEmpty("sg_Assassin") == false then
		
		Cmd_SetStance("sg_Assassin", STANCE_Hold)
		
		--order the hit
		Cmd_AttackSGroup("sg_Assassin", "sg_leader")
		
		--if the IE hasn't been played for this assassin, run it and toggle the flag to prevent it from playing again until the next assassin is spawned.
		if g_assassin_IE == false then
			
			Util_StartIntel(EVENTS.IE_Assassinate)
			
			g_assassin_IE = true
			
		end
		
	end
	
--if the Leader doesn't exist, order the assassin to a central point on the map to wait unit a leader is created
else
	
	if SGroup_Exists("sg_Assassin") and SGroup_IsEmpty("sg_Assassin") == false then
		
		Cmd_SetStance("sg_Assassin", STANCE_CeaseFire)
		
		--retreat back to the northbridge base if it exists
		if EGroup_Exists("eg_NorthBridge_HQ") and EGroup_IsEmpty("eg_NorthBridge_HQ") == false then
			
			Util_AttackMoveMarkerRandomRadius("sg_Assassin", "mkr_assassin_rally1")
			
		--retreat back to the Stronghold if not.
		else
			
			Util_AttackMoveMarkerRandomRadius("sg_Assassin", "mkr_assassin_rally2")
			
		end
		
	end
	
end

end

function Rule_Assassin_Spawning()

--if the 2nd half hasn't been activated yet, the HQ EG won't exist, so alternate spawning rules apply that spawn the assassin at the Bridge base.
if EGroup_Exists("eg_NorthBridge_HQ") and EGroup_IsEmpty("eg_NorthBridge_HQ") == false then
	
	Util_CreateSquadsAtMarker(g_Player2, "sg_Assassin", "guard_squad_assassin", "mkr_NorthBridge_HQ_spawn", 1)
	
	Cmd_SetStance("sg_Assassin", STANCE_StandGround)
	
	Cpu_LockSGroupAcrossPlayers("sg_Assassin")
	
	--reset the IE trigger variable.  Each new assassin will run the IE once.
	g_assassin_IE = false
	
else
	
	if EGroup_Exists("eg_IG_HQ") and EGroup_IsEmpty("eg_IG_HQ") == false then
		
		Util_CreateSquadsAtMarker(g_Player2, "sg_Assassin", "guard_squad_assassin", "mkr_NPC_HQ_Spawn", 1)
		
		Cmd_SetStance("sg_Assassin", STANCE_StandGround)
		
		Cpu_LockSGroupAcrossPlayers("sg_Assassin")
		
		--reset the IE trigger variable.  Each new assassin will run the IE once.
		g_assassin_IE = false
		
	else
		
		if Rule_Exists(Rule_Assassin_Manager) == true then
			
			Rule_Remove(Rule_Assassin_Manager)
			
		end
		
	end
	
end

end

function Rule_Assassin_Restart()

g_assassin_first_spawn = true

Rule_AddIntervalExDelay(Rule_Assassin_Mover, 10, 5, 1)

local rand_restart = World_GetRand(600, 1200)

Rule_AddIntervalDelay(Rule_Assassin_Manager, 20, rand_restart)

end

function Rule_HQ_Harasser_Spawning()

local rand = World_GetRand(1,4)

SGroup_CreateIfNotFound("sg_HQ_Harasser")

for i = 1,2 do
	
	if EGroup_IsEmpty("eg_IG_HQ_Barracks"..i) == false then
		
		SGroup_CreateIfNotFound("sg_HQ_Harasser")
		
		if SGroup_IsEmpty("sg_HQ_Harasser") and g_Harasser_iter == 0 then 
			
			for j = 1,g_HQ_Harasser_Count do
				
				JMUtil_Spawn_Upgraded_Kasrkin(g_Player2, "sg_HQ_HarasserSG"..j, "mkr_HQ_Barracks_Spawn"..i, 8, 6, 2, true, STANCE_Attack, false)
				SGroup_AddGroup(SGroup_CreateIfNotFound("sg_HQ_Harasser"), "sg_HQ_HarasserSG"..j)
				
			end
			
			Cmd_AttackMoveMarker("sg_HQ_Harasser","mkr_Harasser_Attack_Point"..rand)
			
			--limit the for loop to a single pass if both barracks exist
			g_Harasser_iter =  g_Harasser_iter + 1
			
			--ramp up the harasser squad count size to a maximum of 3 squads
			if g_HQ_Harasser_Count  < 3 then
				
				g_HQ_Harasser_Count = g_HQ_Harasser_Count + 1
				
			end
			
		-- incase harassers are stuck in the field somewhere, this will re-assign a move order.  Alternatively it will also make the troops seem more active in combat situations.
		elseif SGroup_IsEmpty("sg_HQ_Harasser") == false then
			
			Cmd_AttackMoveMarker("sg_HQ_Harasser","mkr_Harasser_Attack_Point"..rand)
			
		end
		
	elseif EGroup_IsEmpty("eg_IG_HQ_Barracks1") and EGroup_IsEmpty("eg_IG_HQ_Barracks2") and SGroup_Exists("sg_HQ_Harasser") == false then
		
		Rule_Remove(Rule_HQ_Harasser_Spawning)
		
	end
	
end

g_Harasser_iter = 0

end

function Rule_Armor_Harrassers()

--pick a random attack marker
local rand = World_GetRand(1,2)

SGroup_CreateIfNotFound("sg_Armor_Harassers")

for i = 1,2 do
	
	if EGroup_Exists("eg_Bridgebase_Mech"..i) and EGroup_IsEmpty("eg_Bridgebase_Mech"..i) == false then
		
		if SGroup_IsEmpty("sg_Armor_Harassers") and g_Armor_Harasser_iter == 0 then 
			
			for j = 1,g_Armor_Harasser_Count do
				
				local blueprinttable = Util_MakeBlueprintTable("guard_squad_lemanruss")
				
				t_armor_BP = { --[[1]]"guard_squad_chimera", --[[2]]"guard_squad_hellhound", --[[3]]"guard_squad_sentinel", --[[4]]"guard_squad_lemanruss"}
				
				--limit the sg to 1 leman russ with this if/elseif spawn argument.  I don't want an entire wave of lemans,  too much firepower there.  fisrt chance at a leman spawn only after 10 minutes
				
				if g_ticker >= 1200 then
					if SGroup_ContainsBlueprints("sg_Armor_Harassers", blueprinttable, false) == false then
						
						randV = World_GetRand(1,4)
						
					elseif SGroup_ContainsBlueprints("sg_Armor_Harassers", blueprinttable, false) then
						
						randV = World_GetRand(1,3)
						
					end
					
				elseif g_ticker < 1200 then
					
					randV = World_GetRand(1,3)
					
				end
				
				Util_CreateSquadsAtMarker(g_Player2, "sg_Armor_HarassersSG"..j, t_armor_BP[randV], "mkr_BB_Mech_Spawn"..i, 1)
				SGroup_AddGroup(SGroup_CreateIfNotFound("sg_Armor_Harassers"), "sg_Armor_HarassersSG"..j)
				
				Cpu_LockSGroupAcrossPlayers("sg_Armor_HarassersSG"..j)
				Cpu_LockSGroupAcrossPlayers("sg_Armor_Harassers")
				
				Cmd_SetStance("sg_Armor_HarassersSG"..j, STANCE_Attack)
				
			end
			
			Cmd_AttackMoveMarker("sg_Armor_Harassers","mkr_Harasser_Attack_Point"..rand)
			
			--limit the for loop to a single pass if both barracks exist
			g_Armor_Harasser_iter = 1
			
			--ramp up the harasser squad count size to a maximum of 2 squads
			if g_Armor_Harasser_Count < 2 and g_ticker > 900 then
				
				g_Armor_Harasser_Count = g_Armor_Harasser_Count + 1
				
			end
			
			-- add to the count of the number of harrassers waves spawned
			g_AB_Harrassers_Spawned = g_AB_Harrassers_Spawned + 1
			
		-- incase harassers are stuck in the field somewhere, this will re-assign a move order.  Alternatively it will also make the troops seem more active in combat situations.
		elseif SGroup_IsEmpty("sg_Armor_Harassers") == false then
			
			Cmd_AttackMoveMarker("sg_Armor_Harassers","mkr_Harasser_Attack_Point"..rand)
			
		end
		
	elseif EGroup_IsEmpty("eg_Bridgebase_Mech1") and EGroup_IsEmpty("eg_Bridgebase_Mech2") and SGroup_Exists("sg_Armor_Harassers") == false then
		
		Rule_Remove(Rule_Armor_Harrassers)
		
	end
	
end

g_Armor_Harasser_iter = 0

end

function Rule_Armor_Base_Detect()

if Player_AreSquadsNearMarker(g_Player1, "mkr_Armor_Base") then
	
	Rule_AddOneShot(Rule_Armor_Base_Detect_IE,1)
	
	Rule_AddInterval(Rule_Mech_defenders_static_patrol, 15)
	
	--add objective
	Rule_AddInterval(Rule_Objective_Destroy_Armor_Base,10)
	
	Rule_Remove(Rule_Armor_Base_Detect)
	
end

end

function Rule_Mech_defenders_static_patrol()

local patrol_count = 0

for i = 1,3 do
	
	if SGroup_Exists("sg_Mechbase_infantry"..i) and SGroup_CountSpawned("sg_Mechbase_infantry"..i) > 0 then
		
		Util_AttackMoveMarkerRandomRadius("sg_Mechbase_infantry"..i, "mkr_Armorbase_static_patrol")
		
	else 
		
		--tally how many patrols no longer exist
		patrol_count = patrol_count + 1
		
	end
	
end

--if all three patrol squads are dead, then remove the rule
if patrol_count >=3 then
	
	Rule_Remove(Rule_Mech_defenders_static_patrol)
	
end

end

function Rule_Slagbase_static_patrol()

local patrol_count = 0

for i = 1,3 do
	
	if SGroup_Exists("sg_SlagBase_Defenders"..i) and SGroup_CountSpawned("sg_SlagBase_Defenders"..i) > 0 then
		
		Util_AttackMoveMarkerRandomRadius("sg_SlagBase_Defenders"..i, "mkr_Stronghold_Detect"..i + 2)  -- 'i' must be plus two because markers 3 - 5 are being used.
		
	else 
		
		--tally how many patrols no longer exist
		patrol_count = patrol_count + 1
		
	end
	
end

--if all three patrol squads are dead, then remove the rule
if patrol_count >=3 then
	
	Rule_Remove(Rule_Slagbase_static_patrol)
	
end

end

--Titan Cannon power checker looks for the slag deposits generators. If they are present, then the cannon will fire. function Rule_Titan_Power()

if EGroup_Exists("eg_Titan_Thermos") == false or EGroup_Exists("eg_Titan_Thermos") and EGroup_IsEmpty("eg_Titan_Thermos") then
	
	g_titan_power = false
	UI_HideCount("Titan_Refire_Timer")
	
	Anim_PlayEGroupAnim(EGroup_FromName("eg_Titan_Mega"), "idle_deactivated")
	
end


--[[Intel Events]]	
if EGroup_IsUnderAttack("eg_Titan_Thermos", false) and g_Titan_Gens_Attacked == false then
	
	--toggle first time attack flag to true so that the first time IE event won't play again.
	g_Titan_Gens_Attacked = true
	
	Util_StartIntel(EVENTS.IE_Titan_Gens_First_Attack)
	
	g_Gen_IE_Delay = 45
	
elseif EGroup_IsUnderAttack("eg_Titan_Thermos", false) and g_Titan_Gens_Attacked == true then
	
	if g_Gen_IE_Delay == 0 then
		
		--add an artificial delay between IE's to prevent this IE from being spammed while the player attacks the gens.
		g_Gen_IE_Delay = 30
		
		Util_StartIntel(EVENTS.IE_Titan_Gens_Under_Attack)
		
	end
	
elseif g_titan_power == false then
	
	Util_StartIntel(EVENTS.IE_Titan_Gens_Destroyed)
	
	Rule_Remove(Rule_Titan_Power)
	
	Rule_AddOneShot(Rule_Button_Setup, 1)
	
end

end

function Rule_Titan_Fire_Control()

if g_titan_power == true then
	
	for i = 1,10 do
		
		if Player_AreSquadsNearMarker(g_Player1,"mkr_Cannon_Blast"..i) then
			
			--reveal the cannon in all it's uber-glory!
			for k = 1,3 do
				
				FOW_RevealMarker("mkr_Cannon_Reveal"..k, -1)
				
			end
			
			--[[reveal the canyon temporarily to allow effect to display.
			for j = 1,10 do
				
				FOW_RevealMarker("mkr_Cannon_Blast"..j, 3)
				
			end]]
			
			--Anim_PlayEGroupAnim(EGroup_FromName("eg_Titan_Mega"), "firing")
			
			Util_StartNIS( EVENTS.NIS_MidMission )
			
			g_NIS_Timer = 120
			
			g_Titan_FX_timer_Delay = true
			
			Rule_Remove(Rule_Titan_Fire_Control)
			
			g_Titan_activated = true
			
			break
			
		end
		
	end
	
end

end

function Rule_Titan_Pickup_controller()

--Rule_AddOneShot(Rule_Titan_Impact,0)
Rule_AddInterval(Rule_Titan_Fire_Repeater,1)
Rule_AddInterval(Rule_Titan_Power_Formula, 1)

Rule_AddInterval(Rule_Objective_Disable_Titan_Cannon,5)

UI_ShowCount("Titan_Refire_Timer", g_Player1, 2630010, g_Titan_timer)

end

function Rule_Titan_Fire_Repeater()

if g_titan_power == true then
	
	if g_Titan_timer == 0 and g_Titan_FX_timer_Delay == false then
		
		--[[reveal the canyon temporarily to allow effect to display.
		for i = 1,10 do
			
			FOW_RevealMarker("mkr_Cannon_Blast"..i, 3)
			
		end]]
		
		--Command_EntitySquad(g_Player2, EGroup_FromName("eg_Titan_Mega"), CMD_DefaultAction, "sg_Titan_Target")
		
		Anim_PlayEGroupAnim(EGroup_FromName("eg_Titan_Mega"), "firing")
		
		g_Titan_FX_timer_Delay = true
		
		Rule_AddOneShot(Rule_Titan_Impact,g_Titan_FX_Delay)
		
	end
	
elseif g_titan_power == false then
	
	Rule_Remove(Rule_Titan_Fire_Repeater)
	
end

end

--used for developing the timer for the titan gun refire rate. t_Titan_flags = {

	destroyed = {g_Thermo1_Destroyed, 
							g_Thermo2_Destroyed,
							g_Thermo3_Destroyed,
							g_Thermo4_Destroyed,
							g_Thermo5_Destroyed,
							g_Thermo6_Destroyed,
							g_Thermo7_Destroyed,
							g_Thermo8_Destroyed,
							g_Thermo9_Destroyed,
							g_Thermo10_Destroyed},
	
	varibles = {g_Thermo1,
					g_Thermo2,
					g_Thermo3,
					g_Thermo4,
					g_Thermo5,
					g_Thermo6,
					g_Thermo7,
					g_Thermo8,
					g_Thermo9,
					g_Thermo10}
}

function Rule_Titan_Power_Formula()

--check if each plant is alive.  if destroyed, toggle destroyed flag and add the global timer increase value to each g_thermo varible to increase the refire time.  
for i = 1,10 do
	
	if t_Titan_flags.destroyed[i] == false then
		
		if EGroup_Exists("eg_Thermo_Plasma"..i) == false or EGroup_Exists("eg_Thermo_Plasma"..i) and EGroup_IsEmpty("eg_Thermo_Plasma"..i) then
			
			t_Titan_flags.varibles[i] = g_Titan_timer_addon
			
			t_Titan_flags.destroyed[i] = true
			
			g_Titan_Power_Formula = g_Titan_Power_Formula + t_Titan_flags.varibles[i]
			
			--Add the global timer increase value to the current countdown timer
			g_Titan_timer = g_Titan_timer + g_Titan_timer_addon
			
			-- add to total plants detroyed count
			g_Thermo_Plasma_Plants_Destroyed = g_Thermo_Plasma_Plants_Destroyed + 1
			
		end			
		
	end
	
end

--g_Titan_Power_Formula = g_Titan_Power_Formula + g_Thermo1 + g_Thermo2 + g_Thermo3 + g_Thermo4 + g_Thermo5 + g_Thermo6 + g_Thermo7 + g_Thermo8 + g_Thermo9 + g_Thermo10

--when all 10 plants have been destroyed, remove rule.
if g_Thermo_Plasma_Plants_Destroyed == 10 then
	
	Rule_Remove(Rule_Titan_Power_Formula)
	
end

end

function Rule_Titan_Impact()

--[[t_fired_on_players = {g_Player1, g_Player2, g_Player3, g_Player4, g_Player6}  --g_Player7

for i = 1,table.getn(t_fired_on_players) do
	
	for k = 1,10 do
		
		Player_GetAllEntitiesNearMarker(t_fired_on_players[i], "eg_Titan_Fodder", "mkr_Cannon_Blast"..k)
		Player_GetAllSquadsNearMarker(t_fired_on_players[i], "sg_Titan_Fodder", "mkr_Cannon_Blast"..k)
		
	end
	
end]]

local pos1 = Marker_GetPosition (Marker_FromName("mkr_Cannon_Blast1", "basic_marker" ))
local pos2 = Marker_GetPosition (Marker_FromName("mkr_Cannon_Blast2", "basic_marker" ))
local pos3 = Marker_GetPosition (Marker_FromName("mkr_Cannon_Blast3", "basic_marker" ))
local pos4 = Marker_GetPosition (Marker_FromName("mkr_Cannon_Blast4", "basic_marker" ))
local pos5 = Marker_GetPosition (Marker_FromName("mkr_Cannon_Blast5", "basic_marker" ))
local pos6 = Marker_GetPosition (Marker_FromName("mkr_Cannon_Blast6", "basic_marker" ))
local pos7 = Marker_GetPosition (Marker_FromName("mkr_Cannon_Blast7", "basic_marker" ))
local pos8 = Marker_GetPosition (Marker_FromName("mkr_Cannon_Blast8", "basic_marker" ))
local pos9 = Marker_GetPosition (Marker_FromName("mkr_Cannon_Blast9", "basic_marker" ))
local pos10 = Marker_GetPosition (Marker_FromName("mkr_Cannon_Blast10", "basic_marker" ))

Cmd_EntityCastAbilityPos("eg_Thrower1", "sp_dxp_abilities_throw_extra_large", pos1)
Cmd_EntityCastAbilityPos("eg_Thrower2", "sp_dxp_abilities_throw_extra_large", pos2)
Cmd_EntityCastAbilityPos("eg_Thrower3", "sp_dxp_abilities_throw_extra_large", pos3)
Cmd_EntityCastAbilityPos("eg_Thrower4", "sp_dxp_abilities_throw_extra_large", pos4)
Cmd_EntityCastAbilityPos("eg_Thrower5", "sp_dxp_abilities_throw_extra_large", pos5)
Cmd_EntityCastAbilityPos("eg_Thrower6", "sp_dxp_abilities_throw_extra_large", pos6)
Cmd_EntityCastAbilityPos("eg_Thrower7", "sp_dxp_abilities_throw_extra_large", pos7)
Cmd_EntityCastAbilityPos("eg_Thrower8", "sp_dxp_abilities_throw_extra_large", pos8)
Cmd_EntityCastAbilityPos("eg_Thrower9", "sp_dxp_abilities_throw_extra_large", pos9)
Cmd_EntityCastAbilityPos("eg_Thrower10", "sp_dxp_abilities_throw_extra_large", pos10)

--Rule_AddOneShot(Rule_Titan_Fodder_Despawn,0.25)

end

function Rule_Titan_Fodder_Despawn()

--EGroup_Destroy("eg_Titan_Fodder")
--SGroup_Destroy("sg_Titan_Fodder")

EGroup_DeSpawn("eg_Titan_Fodder")
EGroup_DestroyAllEntities("eg_Titan_Fodder")

SGroup_DeSpawn("sg_Titan_Fodder")
SGroup_DestroyAllSquads("sg_Titan_Fodder")

end

function Rule_Button_Setup()

t_Titan_firing = {
	button_icon = {--[[1]]"Scar_buttons/Titan_weapon", --[[2]]"Scar_buttons/Titan_weapon", --[[3]]"Scar_buttons/Titan_weapon"},
	button_description = {--[[1]]"$2630100", --[[2]]"$2630110"}, 
}

g_button_spawn = Util_AbilityButton_Create(t_Titan_firing.button_icon, t_Titan_firing.button_description, true)

--add checks for button usage ongoing.
Rule_AddInterval(Rule_Player_Titan_Check, 0.5)
Rule_AddIntervalDelay(Rule_Button_Pressed, 1, 1)

end

function Rule_Player_Titan_Check()

t_Gen_table = Util_MakeBlueprintTable(	"chaos_thermo_plasma_generator", "eldar_advanced_warp_generator", "guard_thermo_plasma", "ork_bigger_generator", 
																"space_marine_thermo_generator", "tau_thermoplasma_generator", "necron_thermoplasma_generator")

--check to see if the player has gens to power the gun. If so, the button visibility varible is toggled true, else false.
Player_GetAllEntitiesNearMarker(g_Player1, "eg_slag_Gen_check", "mkr_slag_gen_check")

--if any slag gens have been found then deal with button assignment
if EGroup_Exists("eg_slag_Gen_check") and EGroup_Count("eg_slag_Gen_check") > 0 and EGroup_ContainsBlueprints("eg_slag_Gen_check", t_Gen_table, false) then
	
	g_player_has_gens = true
	
	if g_player_check_first == false then
		
		g_player_check_first = true
		Anim_PlayEGroupAnim(EGroup_FromName("eg_Titan_Mega"), "o_activation")
		
	end
	
	--reveal the cannon's LoS as long as the player has control of it.
	for i = 1,10 do
		
		FOW_RevealMarker("mkr_Cannon_Blast"..i, 3)
		
	end
	
	--play an IE informing the player they now have control of the titan cannon.  This only plays the very first time the button is added.
	if g_button_first_add == true then
		
		Util_StartIntel(EVENTS.IE_Player_Controls_Titan_Cannon)
		
		g_button_first_add = false
		
	end
	
	--determine the firing button's state
	local player_power = Player_GetResource(g_Player1, RT_Power)
	
	if g_Titan_button_timer == 0 and player_power > g_Titan_Fire_Cost then
		
		--enable the button
		Button_SetEnabled(g_button_spawn, true)
		
		UI_HideCount("Titan_Button_Refire_Timer")
		
	else
		
		--disable the button
		Button_SetEnabled(g_button_spawn, false)
		
	end
	
	Misc_GetSelectedEntities(EGroup_CreateIfNotFound("eg_Potential_Gen"))
	
	--determine if the player has a fully contructed generator selected, anf if so, display the firing button.
	if EGroup_Count(EGroup_CreateIfNotFound("eg_Potential_Gen")) > 0 and
	(Entity_GetBlueprintName(EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_Potential_Gen"), 1)) == g_Player_Gen) and 
	(Entity_GetBuildingProgress(EGroup_GetSpawnedEntityAt(EGroup_FromName("eg_Potential_Gen"), 1)) == 1) then 
	
	--if the player has one or more slag gens built, then check for enabled or diabled button state.
	--if EGroup_Count("eg_slag_Gen_check") > 0 and EGroup_IsSelected("eg_Slag_Gens") then
		
		if g_add_button == true then
			
			Util_ButtonManagerUpdateAll()
			
		else
			
			Util_EGroupAbilityButton_Add2Manager(g_button_spawn, "eg_Potential_Gen")
			
			g_add_button = true
			
		end
		
		
	else
		
		if Button_Exists(g_button_spawn) then
			
			Util_EGroupAbilityButton_Remove(g_button_spawn)
			
			Util_ButtonManagerUpdateAll()
			
			g_add_button = false
			
		end		
		
	end
	
else 
	
	g_player_has_gens = false
	
	UI_HideCount("Titan_Button_Refire_Timer")
	
end

end

function Rule_Button_Pressed()

if Button_GetPressed(g_button_spawn) == true then
	
	g_Titan_Captured = true
	
	--reduce players power total to reflect spending enegry to fire the cannon
	local inital_power = Player_GetResource(g_Player1, RT_Power)
	local new_power = inital_power - g_Titan_Fire_Cost
	
	Player_SetResource(g_Player1, RT_Power, new_power)
	
	--fire the cannon
	Anim_PlayEGroupAnim(EGroup_FromName("eg_Titan_Mega"), "firing")
	
	--Create damage in canyon
	Rule_AddOneShot(Rule_Titan_Impact,g_Titan_FX_Delay)
	
	--disable the button
	Button_SetEnabled(g_button_spawn, false)
	
	--set refire delay timer
	g_Titan_button_timer = 30
	
	UI_ShowCount("Titan_Button_Refire_Timer", g_Player1, 2630010, g_Titan_button_timer)
	
end

end

--removes airstrikes from play when the associated HQ in the mech base has been destroyed. function Rule_Airstrike_Checker()

if EGroup_Exists("eg_Airstrike_HQ") == false or EGroup_Exists("eg_Airstrike_HQ") and EGroup_IsEmpty("eg_Airstrike_HQ") then
	
	Rule_Remove(Rule_Airstrike_Control)
	Rule_Remove(Rule_Airstrike_Checker)
	
	Util_StartIntel(EVENTS.IE_Airstrike_Disabled)
	
end

end

function Rule_Airstrike_Control()

if g_NIS_Timer == 0 then
	
	if EGroup_Exists("eg_Airstrike_HQ") and EGroup_CountSpawned("eg_Airstrike_HQ") > 0 then
		
		--control the random chance of the airstrikes based on if the player has triggered the 2nd half of the map.
		if g_2nd_half_activated == false then
			
			chance_var = 4
			
		elseif g_2nd_half_activated == true then
			
			chance_var = 2
			
		end
		
		--% chance to call an airstrike
		local airstrike_chance = World_GetRand(1,chance_var)
		
		if airstrike_chance == 1 then
			
			SGroup_AddGroup(SGroup_CreateIfNotFound("sg_all_units_airstrike"), Player_GetSquads(g_Player1))
			
			Player_GetAllSquadsNearMarker(g_Player1, "sg_player_HQ_units", "mkr_Player_Base_Grabber")
			
			--count all units in the starting area
			local squad_size_check1 = SGroup_Count("sg_player_HQ_units")
			
			local test = SGroup_Count("sg_all_units_airstrike")
			
			--remove all units near the players starting area from the potential untis to be hit by the airstrike.  
			--**I don't want the airstrikes coming down directly on the HQ, since there is no way from the player to avoid or deactivate them... the HQ area should be exempt from their wrath.**
			if SGroup_IsEmpty("sg_player_HQ_units") == false then
				
				for i = 1,squad_size_check1 do
					
					SGroup_Remove("sg_all_units_airstrike", SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_player_HQ_units"), i))
					
				end
				
				--clear out the HQ units sgroup for the next use
				SGroup_Clear("sg_player_HQ_units")
				
			end
			
			--take all remaining units and add each to an individual sgroup
			--if SGroup_IsEmpty("sg_all_units_airstrike") == false then
			if SGroup_CountSpawned("sg_all_units_airstrike") > 0 then
				
				--count units remaining in the potential sgroup for airstrike targeting
				local squad_size_check2 = SGroup_CountSpawned("sg_all_units_airstrike")
				
				--generate a random number based on the total remaining airstrike targets
				local rand_strike = World_GetRand(1,squad_size_check2)
				
				--saftey check to ensure that the chosen squad still exist.  
				--If the index being assigned has become invalid (which technically shouldn't happen), then the airstike is aborted, the player none the wiser.
				if Squad_Exists(Squad_GetGameID(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_all_units_airstrike"), rand_strike))) then
					
					--check to make sure the squad is not currenlty stealthed...  otherwise calling an airstrike on it would feel very cheap to the player.
					if Squad_IsInfiltrated(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_all_units_airstrike"), rand_strike)) == false then
						
						--assign a position for the airstrike based on the random value picking one of the avilible squads in the target group.
						g_airstrike_pos = Squad_GetPosition(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_all_units_airstrike"), rand_strike))
						
						--paint the cursor where the strike is going to hit
						g_Airstrike_FX1 = World_FXEvent("data:Art/Events/Guard/Abilities/Strafe_ordered_target", g_airstrike_pos)
						
						--bombs away!
						Cmd_EntityCastAbilityPos("eg_Thrower1", "guard_strafing_run_stronghold_sp", g_airstrike_pos)	
						
						--call IE
						Util_StartIntel(EVENTS.IE_Airstrike)
						
					end
					
				end
				
			end
			
		end
		
		--clear out the master potential sgroup for the next use
		SGroup_Clear(SGroup_CreateIfNotFound("sg_all_units_airstrike"))
		
	--if the HQ in the "vehicle base" doesn't exist, remove the air strikes.  
	else
		
		Rule_Remove(Rule_Airstrike_Control)
		
	end
	
end

end

function Rule_HQ_Health_Monitor()

if EGroup_GetAvgHealth("eg_IG_HQ") < 0.05 then
	
	g_Win = true
	
	Rule_AddOneShot(Rule_Closing_NIS, 4)
	
	Rule_Remove(Rule_HQ_Health_Monitor)
	
end

end

function Rule_Stronghold_Defense()

--check each of the markers
for i = 1,5 do
	
	if Player_AreSquadsNearMarker(g_Player1, "mkr_Stronghold_Detect"..i) then
		
		g_stronghold_perimeter = true
		
		Player_GetAllSquadsNearMarker(g_Player1, "sg_Stronghold_Invaders", "mkr_Stronghold_Detect"..i)
		
		if Rule_Exists(Rule_Stronghold_Armor) == false then
			
			Rule_AddInterval(Rule_Stronghold_Armor, g_HQ_Armor_Inter)
			
		end
		
		if Rule_Exists(Rule_Stronghold_Infantry) == false then
			
			Rule_AddInterval(Rule_Stronghold_Infantry, g_HQ_Infantry_Inter)
			
		end
		
		--trigger breach IE
		if i == 1  and g_stronghold_breach_IE == false then
			
			g_stronghold_breach_IE = true
			
			Rule_AddOneShot(Rule_Stronghold_Breach_IE,1)
			
			--trigger HQ health detection Rule
			if Rule_Exists(Rule_HQ_Health_Monitor) == false then
				Rule_AddInterval(Rule_HQ_Health_Monitor, 0.5)
			end
			
		end
		
		break
		
	else
		
		g_stronghold_perimeter = false
		
	end
	
	Player_GetAllEntitiesNearMarker(g_Player1, "eg_Stronghold_Invader_entities", "mkr_Stronghold_Detect"..i)
	
end

if SGroup_Exists("sg_Stronghold_Invaders") and SGroup_CountSpawned("sg_Stronghold_Invaders") > 0 then
	
	g_Stronghold_Invaders_active = true
	
elseif SGroup_Exists("sg_Stronghold_Invaders") == false or SGroup_Exists("sg_Stronghold_Invaders") and SGroup_CountSpawned("sg_Stronghold_Invaders") == 0 then
	
	g_Stronghold_Invaders_active = false
	
end

if EGroup_Exists("eg_Stronghold_Invader_entities") and EGroup_CountSpawned("eg_Stronghold_Invader_entities") > 0 then
	
	g_Stronghold_Invaders_Entities_active = true
	
elseif EGroup_Exists("eg_Stronghold_Invader_entities") == false or EGroup_Exists("eg_Stronghold_Invader_entities") and EGroup_CountSpawned("eg_Stronghold_Invader_entities") == 0 then
	
	g_Stronghold_Invaders_Entities_active = false
	
end

end

function Rule_Stronghold_Armor()

SGroup_CreateIfNotFound("sg_Stronghold_Armor")

g_Stronghold_armor = SGroup_Count("sg_Stronghold_Armor")

if g_Stronghold_Invaders_active == true or g_Stronghold_Invaders_Entities_active == true then
	
	if g_Stronghold_armor < 3 then
		
		if SGroup_Exists("sg_Stronghold_Invaders") and SGroup_IsEmpty ("sg_Stronghold_Invaders") == false then
			
			local blueprinttable = Util_MakeBlueprintTable("guard_squad_lemanruss")
			
			t_HQ_armor_BP = { --[[1]]"guard_squad_chimera", --[[2]]"guard_squad_hellhound", --[[3]]"guard_squad_sentinel", --[[4]]"guard_squad_lemanruss"}
			
			if SGroup_ContainsBlueprints("sg_Stronghold_Armor", blueprinttable, false) == false then
				
				randVHQ = World_GetRand(1,4)
				
			elseif SGroup_ContainsBlueprints("sg_Stronghold_Armor", blueprinttable, false) then
				
				randVHQ = World_GetRand(1,3)
				
			end
			
			if EGroup_Exists("eg_IG_HQ_Mech2") and EGroup_CountSpawned("eg_IG_HQ_Mech2") > 0 then
				
				Util_CreateSquadsAtMarker(g_Player2, "sg_Stronghold_Armor", t_HQ_armor_BP[randVHQ], "mkr_HQ_MechShop_Spawn2", 1)
				
			elseif EGroup_Exists("eg_IG_HQ_Mech1") and EGroup_CountSpawned("eg_IG_HQ_Mech1") > 0 then
				
				Util_CreateSquadsAtMarker(g_Player2, "sg_Stronghold_Armor", t_HQ_armor_BP[randVHQ], "mkr_HQ_MechShop_Spawn1", 1)
				
			end
			
			if EGroup_Exists("eg_Slagbase_Mech") and EGroup_CountSpawned("eg_Slagbase_Mech") > 0 then
				
				Util_CreateSquadsAtMarker(g_Player2, "sg_Stronghold_Armor", t_HQ_armor_BP[randVHQ], "mkr_Slag_Mech_Spawn", 1)
				
			end
			
			Cpu_LockSGroupAcrossPlayers("sg_Stronghold_Armor")
			
			Cmd_SetStance("sg_Stronghold_Armor", STANCE_Attack)
			
			--attack squads first, entities second
			if g_Stronghold_Invaders_active == true then
				
				Cmd_AttackSGroup("sg_Stronghold_Armor","sg_Stronghold_Invaders")
				
			elseif g_Stronghold_Invaders_Entities_active == true then
				
				Cmd_AttackEGroup("sg_Stronghold_Armor", "eg_Stronghold_Invader_entities")
				
			else
				
				Cmd_AttackMoveMarker("sg_Stronghold_Armor", "mkr_HQ_Door2")
				
			end
			
		end
		
	end
	
end

end

function Rule_Stronghold_Infantry()

SGroup_CreateIfNotFound("sg_Stronghold_Infantry")
SGroup_CreateIfNotFound("sg_Stronghold_Kasrkin")
SGroup_CreateIfNotFound("sg_Stronghold_Ogryn")
SGroup_CreateIfNotFound("sg_Stronghold_Guard")


local randSS = World_GetRand(6,8)
local randOgrynsize = World_GetRand(4,6)
local randplasma = World_GetRand(2,3)
local randgrenade = 0 --[[World_GetRand(1,2)]]

if g_Stronghold_Invaders_active == true then
	
	for i = 1,2 do
		
		g_Stronghold_Kasrkin_count = SGroup_Count("sg_Stronghold_Kasrkin")
		g_Stronghold_Ogryn_count = SGroup_Count("sg_Stronghold_Ogryn")
		g_Stronghold_Guard_count = SGroup_Count("sg_Stronghold_Guard")
		
		-- determine the spawn location based on the iteration of i
		if i == 1 then
			
			--spawn at barracks2 if possible before using barracks1
			if EGroup_Exists("eg_IG_HQ_Barracks2") and EGroup_CountSpawned("eg_IG_HQ_Barracks2") > 0 then
			--if g_IG_HQ_Barracks2 == true then
				
				HQ_Barracks = "mkr_HQ_Barracks_Spawn2"
				
			elseif EGroup_Exists("eg_IG_HQ_Barracks1") and EGroup_CountSpawned("eg_IG_HQ_Barracks1") > 0 then
			--elseif g_IG_HQ_Barracks2 == false and g_IG_HQ_Barracks1 == true then
				
				HQ_Barracks = "mkr_HQ_Barracks_Spawn1"
				
			--if both stronghold barracks are destroyed
			elseif EGroup_Exists("eg_IG_HQ_Barracks1") == false and EGroup_Exists("eg_IG_HQ_Barracks2") == false or EGroup_Exists("eg_IG_HQ_Barracks1") 
			and EGroup_CountSpawned("eg_IG_HQ_Barracks1") == 0 and EGroup_Exists("eg_IG_HQ_Barracks2") and EGroup_CountSpawned("eg_IG_HQ_Barracks2") == 0 then
			--elseif g_IG_HQ_Barracks2 == false and g_IG_HQ_Barracks1 == false then
				
				HQ_Barracks = "mkr_NPC_HQ_Spawn"
				
			end
			
		--second loop of i generates a spawn at the slag base barracks.
		else
			
			if g_SlagBase_Barracks == true then
				
				HQ_Barracks = "mkr_Slag_Barracks_Spawn"
				
			-- if the slag base barracks is destroyed then break from the rule.
			else
				
				break
				
			end
			
		end
		
		--spawn infantry.  Kasrkins and Ogryns limited to 1 unit each.  If they are already spawned, then it will pump out guardsmen.
		if g_Stronghold_Kasrkin_count == 0 and g_Stronghold_Kasrkin_spawned == false and g_Stronghold_Kasrkin_Timer == 0 then
			
			g_Stronghold_Kasrkin_Timer = 180
			
			JMUtil_Spawn_Upgraded_Kasrkin(g_Player2, "sg_Stronghold_Kasrkin"..g_Stronghold_Kasrkin, HQ_Barracks, randSS, randplasma, randgrenade, true, STANCE_Attack, false)
			
			SGroup_AddLeaders("sg_Stronghold_Kasrkin"..g_Stronghold_Kasrkin)
			
			JMUtil_Random_Leader_Spawn(g_Player2, "sg_Stronghold_Kasrkin"..g_Stronghold_Kasrkin, HQ_Barracks, "sg_Stronghold_Kasrkin_Leader"..g_Stronghold_Kasrkin, true)
			
			JMUtil_Random_Melee_Stance(10 --[[10%]], "sg_Stronghold_Kasrkin"..g_Stronghold_Kasrkin)
			
			SGroup_AddGroup("sg_Stronghold_Infantry", "sg_Stronghold_Kasrkin"..g_Stronghold_Kasrkin)
			SGroup_AddGroup("sg_Stronghold_Kasrkin", "sg_Stronghold_Kasrkin"..g_Stronghold_Kasrkin)
			
			g_Stronghold_Kasrkin = g_Stronghold_Kasrkin + 1
			g_Stronghold_Kasrkin_spawned = true
			g_Stronghold_Kasrkin_respawn = 45
			
		elseif g_Stronghold_Ogryn_count == 0 and g_Stronghold_Ogryn_spawned == false and g_Stronghold_Ogryn_Timer == 0 then
			
			g_Stronghold_Ogryn_Timer = 180
			
			Util_CreateSquadsAtMarkerEx(g_Player2, "sg_Stronghold_Ogryn"..g_Stronghold_Ogryn, "guard_squad_ogryns", HQ_Barracks, 1, randOgrynsize)
			Cpu_LockSGroupAcrossPlayers("sg_Stronghold_Ogryn")
			
			SGroup_AddLeaders("sg_Stronghold_Ogryn"..g_Stronghold_Ogryn)
			
			JMUtil_Random_Leader_Spawn(g_Player2, "sg_Stronghold_Ogryn"..g_Stronghold_Ogryn, HQ_Barracks, "sg_Stronghold_Ogryn_Leader"..g_Stronghold_Ogryn, true)
			
			SGroup_AddGroup("sg_Stronghold_Infantry", "sg_Stronghold_Ogryn"..g_Stronghold_Ogryn)
			SGroup_AddGroup("sg_Stronghold_Ogryn", "sg_Stronghold_Ogryn"..g_Stronghold_Ogryn)
			
			g_Stronghold_Ogryn = g_Stronghold_Ogryn + 1
			g_Stronghold_Ogryn_spawned = true
			g_Stronghold_Ogryn_respawn = 45
			
		elseif g_Stronghold_Guard_count < 6 then
			
			JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Stronghold_Guard"..g_Stronghold_Guard, HQ_Barracks, randSS, randplasma, randgrenade, true, STANCE_Attack, true)
			
			SGroup_AddLeaders("sg_Stronghold_Guard"..g_Stronghold_Guard)
			
			JMUtil_Random_Leader_Spawn(g_Player2, "sg_Stronghold_Guard"..g_Stronghold_Guard, HQ_Barracks, "sg_Stronghold_Guard_Leader"..g_Stronghold_Guard, true)
			
			JMUtil_Random_Melee_Stance(2 --[[50%]], "sg_Stronghold_Guard"..g_Stronghold_Guard)
			
			SGroup_AddGroup("sg_Stronghold_Infantry", "sg_Stronghold_Guard"..g_Stronghold_Guard)
			SGroup_AddGroup("sg_Stronghold_Guard", "sg_Stronghold_Guard"..g_Stronghold_Guard)
			
			g_Stronghold_Guard = g_Stronghold_Guard + 1
			
		end
		
	end
	
end

if Rule_Exists(Rule_Stronghold_Infantry_Mover) == false then
	
	Rule_AddInterval(Rule_Stronghold_Infantry_Mover,3)
	
end

if Rule_Exists(Rule_Stronghold_Barracks_Checker) == false then
	
	Rule_AddInterval(Rule_Stronghold_Barracks_Checker, 0.5)
	
end

end

function Rule_Stronghold_Infantry_Mover()

--attack squads first, entities second
if g_Stronghold_Invaders_active == true then
	
	Cmd_AttackSGroup("sg_Stronghold_Infantry","sg_Stronghold_Invaders")
	
elseif g_Stronghold_Invaders_Entities_active == true then
	
	Cmd_AttackEGroup("sg_Stronghold_Infantry", "eg_Stronghold_Invader_entities")
	
elseif g_Stronghold_Invaders_active == false and g_Stronghold_Invaders_Entities_active then
	
	Rule_Remove(Rule_Stronghold_Infantry_Mover)
	
end

end

function Rule_Stronghold_Barracks_Checker()

if EGroup_Exists("eg_IG_HQ_Barracks2") == false or  EGroup_Exists("eg_IG_HQ_Barracks2") and EGroup_CountSpawned("eg_IG_HQ_Barracks2") == 0 then
	
	g_IG_HQ_Barracks2 = false
	
end

if EGroup_Exists("eg_IG_HQ_Barracks1") == false or  EGroup_Exists("eg_IG_HQ_Barracks1") and EGroup_CountSpawned("eg_IG_HQ_Barracks1") == 0 then
	
	g_IG_HQ_Barracks1 = false
	
end

if EGroup_Exists("eg_SlagBase_Barracks1") == false or  EGroup_Exists("eg_SlagBase_Barracks1") and EGroup_CountSpawned("eg_SlagBase_Barracks1") == 0 then
	
	g_SlagBase_Barracks = false
	
end

end

function Rule_Rebel_Base_Prox_Check()

if Player_AreSquadsNearMarker(g_Player1,"mkr_Rebel_Base_Proximity") then
	
	Rule_AddInterval(Rule_Objective_Kill_Rebel_Officer,5)
	Rule_AddInterval(Rule_Commissar_Death,1)
	Rule_Remove(Rule_Rebel_Base_Prox_Check)
	
end

end

function Rule_Commissar_Death()

if SGroup_Exists("sg_Rebel_Commissar") == false or SGroup_IsEmpty("sg_Rebel_Commissar") then
	
	--give all rebel buildings to allied g_Player4
	EGroup_SetPlayerOwner("eg_All_Rebel_Buildings", g_Player4)
	
	if EGroup_Exists("eg_HQ_List_Post4") and EGroup_IsEmpty("eg_HQ_List_Post4") == false then
		
		EGroup_SetPlayerOwner("eg_All_Rebel_Buildings",g_Player4)
		
	end
	
	--give all remaining rebel units to g_Player4 if any exist
	if SGroup_Exists("sg_All_Rebel_Units") and SGroup_IsEmpty("sg_All_Rebel_Units") == false then
		
		SGroup_SetPlayerOwner("sg_All_Rebel_Units",g_Player4)
		
	end
	
	--transfer any remaining artillery to the neutral team.
	--[[DEFUNCT
	if SGroup_Exists("sg_Freebie_Rebel_Units") == true then
		
		SGroup_SetPlayerOwner("sg_Freebie_Rebel_Units", g_Player7)
		
		--Saftey lock....   They seem to drop their locked state and stances when switching players.
		Cpu_LockSGroupAcrossPlayers("sg_Freebie1")
		Cpu_LockSGroupAcrossPlayers("sg_Freebie2")
		Cpu_LockSGroupAcrossPlayers("sg_Freebie3")
		Cpu_LockSGroupAcrossPlayers("sg_Freebie_Rebel_Units")
		
		Cmd_SetStance("sg_Freebie1", STANCE_CeaseFire)
		Cmd_SetStance("sg_Freebie2", STANCE_CeaseFire)
		Cmd_SetStance("sg_Freebie3", STANCE_CeaseFire)
		Cmd_SetStance("sg_Freebie_Rebel_Units",STANCE_CeaseFire)
		
	end]]
	
	Cpu_LockSGroupAcrossPlayers(Player_GetSquads(g_Player4))
	
	SGroup_AddGroup(SGroup_CreateIfNotFound("sg_Rebel_Troops"), Player_GetSquads(g_Player4))
	
	Rule_AddOneShot(Rule_Set_Rebel_Pop_Caps, 1)
	Rule_AddInterval(Rule_AI_Resource_Checker, 60)
	Rule_AddInterval(Rule_Initial_Rebel_Controller, 10)
	
	Rule_AddOneShot(Rule_Commissar_Death_IE,1)
	Rule_Remove(Rule_Commissar_Death)
	g_Commisar_Dead = true
	
end

end

function Rule_Initial_Rebel_Controller()

if g_Rebel_Initial_Controller == false then
	
	Rule_AddOneShot(Rule_Rebel_Controller, 1)
	
	g_Rebel_Initial_Controller = true
	
else
	
	Rule_AddInterval(Rule_Rebel_Controller, 20)
	
	Rule_Remove(Rule_Initial_Rebel_Controller)
	
end

end

function Rule_Set_Rebel_Pop_Caps()

Player_SetMaxSquadCap(g_Player4, 20)
Player_SetMaxSupportCap(g_Player4, 20)

end

function Rule_Rebel_Controller()

t_rebel_IE = {EVENTS.IE_Rebel_Charge_1, EVENTS.IE_Rebel_Charge_2, EVENTS.IE_Rebel_Charge_3, EVENTS.IE_Rebel_Charge_4}

local rebel_count = SGroup_Count(SGroup_CreateIfNotFound("sg_Rebel_Troops"))
local attacker_count = SGroup_Count(SGroup_CreateIfNotFound("sg_Rebel_attackers"))
local attack_size = 6 --used to determine the nessasary SG size needed to trigger an attack on the stronghold

--% chance to toggle spawned squad to melee stance
local rand_melee = World_GetRand(1,4)

if EGroup_Exists("eg_Rebel_Barracks") == false or EGroup_IsEmpty("eg_Rebel_Barracks") then
	
	g_Rebels_Defeated = true
	
	Rule_Remove(Rule_Rebel_Controller)
	
--if the spawning group is still less than the attack size determined above then spawn another guardsmen squad
elseif rebel_count < attack_size then
	
	--don't spawn until the attacking SG has been reduced to 2 squads or less.
	if attacker_count <= 1 then
		
		JMUtil_Spawn_Upgraded_Guardmen(g_Player4, "sg_Rebel_Troops_temp", "mkr_Rebel_Spawn", 3, 0, 1, false, STANCE_Hold, false)
		
		if rand_melee == 1 then
			
			Cmd_SetMeleeStance("sg_Rebel_Troops_temp", MSTANCE_Assault)
			
		end
		
		--move into position
		Cmd_AttackMoveMarker("sg_Rebel_Troops_temp", "mkr_rebel_rally_point"..g_rebel_rally)
		
		--transfer squad in the temp group into main controller group
		SGroup_AddGroup("sg_Rebel_Troops", "sg_Rebel_Troops_temp")
		
		--clear out temp group for next use
		SGroup_Clear("sg_Rebel_Troops_temp")
		
		Cmd_ReinforceTrooper("sg_Rebel_Troops", 1)
		
		g_rebel_rally = g_rebel_rally + 1
		
		if g_rebel_rally > 6 then
			
			g_rebel_rally = 1
			
		end
		
	end
	
else
	
	--launch attack when the delay has passed and there are the predetermined guardsmen spawned
	if g_Rebel_IE == 0 and rebel_count == attack_size then
		
		--if this is the first attack on the IG base (just shortly after the rebels have been liberated), then the attack order is for a marker deep in the stronhold territory
		--this will take advantage of the pathing AI and make most, if not all of the rebel forces head down the canyon and get blasted.
		if g_Rebel_first_attack == true then
			
			Cmd_AttackMoveMarker("sg_Rebel_Troops", "mkr_HQ_Door2")
			
			--add to unique SG to help with movement issues this initial attack has (stopping in the canyon and sitting around, VERY unrealistic).
			SGroup_AddGroup(SGroup_CreateIfNotFound("sg_Rebel_attackers_1stwave"), "sg_Rebel_Troops")
			
			Rule_AddInterval(Rule_rebel_first_wave_controller, 5)
			
			SGroup_Clear("sg_Rebel_Troops")
			
		--attack marker is now set in a shallow position relative to the stronghold.  this will make the pathing AI steer the rebels through the ruined building area instead of the canyon (for the most part)
		else
			
			Cmd_SetStance("sg_Rebel_Troops", STANCE_Attack)
			
			Cmd_AttackMoveMarker("sg_Rebel_Troops", "mkr_Rebel_Attack_Point")
			
			SGroup_AddGroup(SGroup_CreateIfNotFound("sg_Rebel_attackers"), "sg_Rebel_Troops")
			
			SGroup_Clear("sg_Rebel_Troops")
			
			--add in the IG skirmisher spawner rule that run simmilar to this.
			if Rule_Exists(Rule_IG_Skirmishers) == false then
				
				Rule_AddIntervalDelay(Rule_IG_Skirmishers, 20, 90)
				
			end
			
		end
		
		if Rule_Exists(Rule_Rebel_Attackers) == false then
			
			Rule_AddIntervalDelay(Rule_Rebel_Attackers, 5, 20)
			
		end
		
		if g_Rebel_first_attack == true then
			
			randIE = 1
			
			g_Rebel_first_attack = false
			
		else
			
			local randIE = World_GetRand(1,table.getn(t_rebel_IE))
			
		end
		
		Util_StartIntel(t_rebel_IE[randIE])
		
		g_Rebel_IE = 120
		
	end
	
end

end

function Rule_Rebel_Attackers()

if SGroup_Exists("sg_Rebel_attackers") and SGroup_IsEmpty("sg_Rebel_attackers") == false then
	
	Cmd_AttackMoveMarker("sg_Rebel_attackers", "mkr_HQ_Door2")
	
	Cmd_ReinforceTrooper("sg_Rebel_attackers", 1)
	
else
	
	Rule_Remove(Rule_Rebel_Attackers)
	
end

end

function Rule_rebel_first_wave_controller()

Cpu_LockSGroupAcrossPlayers("sg_Rebel_attackers_1stwave")

Cmd_AttackMoveMarker("sg_Rebel_attackers_1stwave", "mkr_HQ_Door2")

--SGroup_Clear("sg_Rebel_attackers_1stwave")

if SGroup_IsEmpty("sg_Rebel_attackers_1stwave") or SGroup_Exists("sg_Rebel_attackers_1stwave") == false then
	
	Rule_Remove(Rule_rebel_first_wave_controller)
	
end

end

function Rule_AI_Resource_Checker()

local Rebel_Req_Count = Player_GetResource(g_Player4, RT_Requisition)
local Rebel_Power_Count = Player_GetResource(g_Player4, RT_Power)

local IG1_Req_Count = Player_GetResource(g_Player2, RT_Requisition)
local IG1_Power_Count = Player_GetResource(g_Player2, RT_Power)

local IG2_Req_Count = Player_GetResource(g_Player6, RT_Requisition)
local IG2_Power_Count = Player_GetResource(g_Player6, RT_Power)

if Rebel_Req_Count < 5000 then
	
	local add_req = Rebel_Req_Count + 1000
	
	Player_SetResource(g_Player4, RT_Requisition, add_req)
	
end

if Rebel_Power_Count < 5000 then
	
	local add_power = Rebel_Power_Count + 1000
	
	Player_SetResource(g_Player4, RT_Requisition, add_power)
	
end


if IG1_Req_Count < 5000 then
	
	local add_req = Rebel_Req_Count + 1000
	
	Player_SetResource(g_Player2, RT_Requisition, add_req)
	
end

if IG1_Power_Count < 5000 then
	
	local add_power = Rebel_Power_Count + 1000
	
	Player_SetResource(g_Player2, RT_Requisition, add_power)
	
end


if IG2_Req_Count < 5000 then
	
	local add_req = Rebel_Req_Count + 1000
	
	Player_SetResource(g_Player6, RT_Requisition, add_req)
	
end

if IG2_Power_Count < 5000 then
	
	local add_power = Rebel_Power_Count + 1000
	
	Player_SetResource(g_Player6, RT_Requisition, add_power)
	
end

end

function Rule_IG_Skirmishers()

local skirmisher_count = SGroup_Count(SGroup_CreateIfNotFound("sg_skirmisher_Troops"))
local attacker_count = SGroup_Count(SGroup_CreateIfNotFound("sg_skirmisher_attackers"))
local attack_size = 4 --used to determine the nessasary SG size needed to trigger an attack

if EGroup_Exists("eg_IG_HQ_Barracks2") and EGroup_CountSpawned("eg_IG_HQ_Barracks2") > 0 then
	
	spawn_mkr = "mkr_HQ_Barracks_Spawn2"
	
elseif EGroup_Exists("eg_IG_HQ_Barracks1")  and EGroup_CountSpawned("eg_IG_HQ_Barracks1") > 0 then
	
	spawn_mkr = "mkr_HQ_Barracks_Spawn1"
	
end

if EGroup_CountSpawned("eg_IG_HQ_Barracks1") == 0 and EGroup_CountSpawned("eg_IG_HQ_Barracks2") == 0 or g_Rebels_Defeated == true then
	
	Rule_Remove(Rule_IG_Skirmishers)
	
	--send any remaining skirmishers at the main player HQ.
	if SGroup_IsEmpty("sg_skirmisher_Troops") == false then
		
		Util_AttackMoveMarkerRandomRadius("sg_skirmisher_Troops", "mkr_Player_Base_Grabber")
		
	end
	
elseif skirmisher_count < attack_size then
	
	--do not spawn skirmishers is the player is in the stronghoild perimiter, or else there is too many troops being spawned
	if g_stronghold_perimeter == false then
		
		if attacker_count == 0 then
			
			if skirmisher_count == 0 and g_skirmisher_special == 0 then
				
				Util_CreateSquadsAtMarker(g_Player2, "sg_skirmisher_Troops_temp", "guard_squad_ogryns", spawn_mkr, 1)
				
				g_skirmisher_special = 60
				
			else
				
				JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_skirmisher_Troops_temp", spawn_mkr, 6, 0, 0, false, STANCE_Attack, false)
				
			end
			
			Cmd_AttackMoveMarker("sg_skirmisher_Troops_temp", "mkr_IG_staging_point")
			
			--add temp spawning group to controller group
			SGroup_AddGroup("sg_skirmisher_Troops", "sg_skirmisher_Troops_temp")
			
			--set group lockout and stance, this will make sure each new unit added to the group is properly set and locked out form AI control
			Cpu_LockSGroupAcrossPlayers("sg_skirmisher_Troops")
			Cmd_SetStance("sg_skirmisher_Troops", STANCE_Attack)
			
			--clear out temp spawning group
			SGroup_Clear("sg_skirmisher_Troops_temp")
			
		end
		
	end
	
else
	
	if skirmisher_count == attack_size then
		
		Cmd_AttackMoveMarker("sg_skirmisher_Troops", "mkr_IG_Attack_Point")
		
		SGroup_AddGroup(SGroup_CreateIfNotFound("sg_skirmisher_attackers"), "sg_skirmisher_Troops")
		
		SGroup_Clear("sg_skirmisher_Troops")
		
		if Rule_Exists(Rule_Skirmisher_Attackers) == false then
			
			Rule_AddIntervalDelay(Rule_Skirmisher_Attackers, 10, 20)
			
		end
		
	end
	
end

end

function Rule_Skirmisher_Attackers()

if SGroup_Exists("sg_skirmisher_attackers") and SGroup_IsEmpty("sg_skirmisher_attackers") == false and g_Rebels_Defeated == false then
	
	if EGroup_Exists("eg_All_Rebel_Buildings") and EGroup_IsEmpty("eg_All_Rebel_Buildings") == false then
		
		Cmd_AttackMoveMarker("sg_skirmisher_attackers", "mkr_skirmisher_attack_point")
		
	end
	
--if the SG is empty, remove rule.
else
	
	Rule_Remove(Rule_Skirmisher_Attackers)
	
end
	

end

--[[DEFUNCT function Rule_Create_Freebie_Artillery()

if g_Freebie_Artillery < 3 then
	
	g_Freebie_Artillery = g_Freebie_Artillery + 1
	
	Util_CreateSquadsAtMarker(g_Player3,"sg_Freebie"..g_Freebie_Artillery,"guard_squad_basilisk","mkr_Freebie_Rebel_Unit"..g_Freebie_Artillery,1)
	SGroup_AddGroup(SGroup_CreateIfNotFound("sg_Freebie_Rebel_Units"),"sg_Freebie"..g_Freebie_Artillery)
	Cpu_LockSGroupAcrossPlayers("sg_Freebie"..g_Freebie_Artillery)
	Cmd_SetStance("sg_Freebie"..g_Freebie_Artillery, STANCE_CeaseFire)
	
	--set health down so that the artiller is in "disrepair".  That is why it is left behind when the rebels rush the stronghold.
	SGroup_SetAvgHealth("sg_Freebie"..g_Freebie_Artillery, 0.01)
	
	Cpu_LockSGroupAcrossPlayers("sg_Freebie_Rebel_Units")
	Cmd_SetStance("sg_Freebie_Rebel_Units",STANCE_CeaseFire)
	
	--face "forward" to look like there are parked orderly.
	SGroup_FaceMarker("sg_Freebie"..g_Freebie_Artillery,"mkr_Freebie_Facing_"..g_Freebie_Artillery)
	
	
end

--give the freebie armor units to g_Player1
if g_Freebie_Artillery >= 3 then
	
	Rule_Remove(Rule_Create_Freebie_Artillery)
	
end

end

--determine if any artillery exist, the # that do exist and post the objective. function Rule_Freebie_Artillery_Objective()

g_Freebie_Count = SGroup_Count("sg_Freebie_Rebel_Units")

if g_Freebie_Count > 0 then
	
	Rule_AddInterval(Rule_Objective_Repair_Artillery,5)
	
	Rule_AddInterval(Rule_Freebie_Health_Check,1)
	
end

end

--check to see if the player has repaired any of the artillery, and tranfer ownership at 100% health. function Rule_Freebie_Health_Check()

g_Artillery1 = SGroup_Exists("sg_Freebie1")
g_Artillery2 = SGroup_Exists("sg_Freebie2")
g_Artillery3 = SGroup_Exists("sg_Freebie3")

--if artillery1 hasn't been transfered, check health and tranfer when health = 1
if g_Artillery_Transfer1 == false then
	
	if g_Artillery1 == true then
		
		if SGroup_GetAvgHealth("sg_Freebie1") == 1 then
			
			Cmd_SetStance("sg_Freebie1", STANCE_Hold)
			SGroup_SetPlayerOwner("sg_Freebie1", g_Player1)
			
			g_Artillery_Transfer1 = true
			
			g_Tranfer_Count = g_Tranfer_Count + 1
			
		end
		
	end
	
end

--if artillery2 hasn't been transfered, check health and tranfer when health = 1
if g_Artillery_Transfer2 == false then
	
	if g_Artillery2 == true then
		
		if SGroup_GetAvgHealth("sg_Freebie2") == 1 then
			
			Cmd_SetStance("sg_Freebie2", STANCE_Hold)
			SGroup_SetPlayerOwner("sg_Freebie2", g_Player1)
			
			g_Artillery_Transfer2 = true
			
			g_Tranfer_Count = g_Tranfer_Count + 1
			
		end
		
	end
	
end

--if artillery3 hasn't been transfered, check health and tranfer when health = 1
if g_Artillery_Transfer3 == false then
	
	if g_Artillery3 == true then
		
		if SGroup_GetAvgHealth("sg_Freebie3") == 1 then
			
			Cmd_SetStance("sg_Freebie3", STANCE_Hold)
			SGroup_SetPlayerOwner("sg_Freebie3", g_Player1)
			
			g_Artillery_Transfer3 = true
			
			g_Tranfer_Count = g_Tranfer_Count + 1
			
		end
		
	end
	
end

--check to see if all artillery have been transfered.  If so, do clean up.
if g_Tranfer_Count == g_Freebie_Count then	
	
	Rule_Remove(Rule_Freebie_Health_Check)
	
	g_Artillery_Repaired = true
	
end

end]]

-- if the players are approaching the bridge, trigger various bridge area rules function Rule_Bridge_Area_Check()

t_artillery_triggers = {--[[1"mkr_Advanced_Artillery_Trigger1", 
								--[[2]] "mkr_Advanced_Artillery_Trigger2",]]
								--[[3]] "mkr_Artillery_Trigger1",
								--[[4]] "mkr_Artillery_Trigger2",
								--[[5]] "mkr_Artillery_Trigger3",
								--[[6]] "mkr_Artillery_Trigger4",
								--[[7]] "mkr_Artillery_Trigger5",
								--[[8]] "mkr_Artillery_Trigger6",
								--[[9]] "mkr_Artillery_Trigger7",
								--[[10]] "mkr_Artillery_Trigger8"}

for i = 1,table.getn(t_artillery_triggers) do
	
	if Player_AreSquadsNearMarker(g_Player1, t_artillery_triggers[i]) then
		
		--run an initial firing sequence right of the mark
		Rule_AddOneShot(Rule_Artillery_Support1, 0)
		
		--start artillery firing sequence
		Rule_AddIntervalDelay(Rule_Artillery_Control, 5, 5)
		
		--run IE sequence to vocalize firing sequence has started.
		Rule_AddOneShot(Rule_First_Artillery_Strike_IE,0)
		
		--add island defense rule
		Rule_AddInterval(Rule_Island_Defense_Checker, 2)
		
		--add bridge defense rule
		Rule_AddInterval(Rule_Bridge_Defense_Checker, 2)
		
		--create untis at the mechbase
		Rule_AddOneShot(Rule_Create_Mech_Base_Units, 1)
		
		Rule_Remove(Rule_Bridge_Area_Check)
		
		break
		
	end
	
end

end

function Rule_Bridge_Defense_Checker()

if Player_AreSquadsNearMarker(g_Player1,"mkr_BridgeHead_South") and g_Bridge_triggered == false then
	
	if Rule_Exists(Rule_Bridge_Armor_spawner) == false then
		
		Rule_AddInterval(Rule_Bridge_Armor_spawner, 60)
		
	end
	
	Rule_AddOneShot(Rule_South_Bridge_IE, 1)
	
	g_Bridge_triggered = true
	
end

if g_Bridge_Mech1 == true then
	
	if EGroup_Exists("eg_NorthBridge_Mech1") == false or EGroup_Exists("eg_NorthBridge_Mech1") and EGroup_IsEmpty("eg_NorthBridge_Mech1") then
		
		g_Bridge_Mech1 = false
		
	end
	
end

if g_Bridge_Mech2 == true then
	
	if EGroup_Exists("eg_NorthBridge_Mech2") == false or EGroup_Exists("eg_NorthBridge_Mech2") and EGroup_IsEmpty("eg_NorthBridge_Mech2") then
		
		g_Bridge_Mech2 = false
		
	end
	
end

if g_Bridge_Barracks1 == true then
	
	if EGroup_Exists("eg_NorthBridge_Barracks1") == false or EGroup_Exists("eg_NorthBridge_Barracks1") and EGroup_IsEmpty("eg_NorthBridge_Barracks1") then
		
		g_Bridge_Barracks1 = false
		
	end
	
end

if g_Bridge_Barracks2 == true then
	
	if EGroup_Exists("eg_NorthBridge_Barracks2") == false or EGroup_Exists("eg_NorthBridge_Barracks2") and EGroup_IsEmpty("eg_NorthBridge_Barracks2") then
		
		g_Bridge_Barracks2 = false
		
	end
	
end

if g_Bridge_HQ == true then
	
	if EGroup_Exists("eg_NorthBridge_HQ") == false or EGroup_Exists("eg_NorthBridge_HQ") and EGroup_IsEmpty("eg_NorthBridge_HQ") then
		
		g_Bridge_HQ = false
		
	end
	
end

--if all the buildings are destroyed, remove checking rule
if g_Bridge_Mech1 == false and g_Bridge_Mech2 == false and g_Bridge_Barracks1 == false and g_Bridge_Barracks1 == false and g_Bridge_HQ == false then
	
	Rule_Remove(Rule_Bridge_Defense_Checker)
	
end

end

function Rule_Bridge_Armor_spawner()

g_Bridge_Armor_count = SGroup_Count("sg_NorthBridge_defense")

if g_Bridge_Armor_count < 3 then
	
	if EGroup_Exists("eg_NorthBridge_Mech1") == false or EGroup_Exists("eg_NorthBridge_Mech1") and EGroup_IsEmpty("eg_NorthBridge_Mech1") then
		
		g_Bridge_Mech1 = false
		
	else
		
		local randtype = World_GetRand(1,2)
		
		if randtype == 1 then
			Util_CreateSquadsAtMarker(g_Player2, "sg_NorthBridge_defense", "guard_squad_sentinel", "mkr_NorthBridge_Mech_Spawn1", 1)
		elseif randtype == 2 then
			Util_CreateSquadsAtMarker(g_Player2, "sg_NorthBridge_defense", "guard_squad_hellhound", "mkr_NorthBridge_Mech_Spawn1", 1)
		end
		
	end
	
	if EGroup_Exists("eg_NorthBridge_Mech2") == false or EGroup_Exists("eg_NorthBridge_Mech2") and EGroup_IsEmpty("eg_NorthBridge_Mech2") then
		
		g_Bridge_Mech2 = false
		
	else
		
		local randtype = World_GetRand(1,2)
		
		if randtype == 1 then
			Util_CreateSquadsAtMarker(g_Player2, "sg_NorthBridge_defense", "guard_squad_sentinel", "mkr_NorthBridge_Mech_Spawn2", 1)
		elseif randtype == 2 then
			Util_CreateSquadsAtMarker(g_Player2, "sg_NorthBridge_defense", "guard_squad_hellhound", "mkr_NorthBridge_Mech_Spawn2", 1)
		end
		
	end
	
end

if SGroup_IsEmpty("sg_NorthBridge_defense") == false then
	
	Cmd_SetStance("sg_NorthBridge_defense", STANCE_Attack)
	Cmd_AttackMoveMarker("sg_NorthBridge_defense", "mkr_BridgeHead_North1")
	
end

--if the mech shops are destroyed, remove the rule
if g_Bridge_Mech1 == false and g_Bridge_Mech2 == false then
	
	Rule_Remove(Rule_Bridge_Armor_spawner)
	
end

end

function Rule_Bridge_Infantry_spawner()

SGroup_CreateIfNotFound("sg_NorthBridge_Infantry")
SGroup_CreateIfNotFound("sg_NorthBridge_Infantry1")
SGroup_CreateIfNotFound("sg_NorthBridge_Infantry2")
SGroup_CreateIfNotFound("sg_NorthBridge_Infantry3")
SGroup_CreateIfNotFound("sg_NorthBridge_Infantry_Leader1")
SGroup_CreateIfNotFound("sg_NorthBridge_Infantry_Leader2")
SGroup_CreateIfNotFound("sg_NorthBridge_Infantry_Leader3")


local randSS = World_GetRand(6,8)
local randplasma = World_GetRand(2,4)
local randgrenade = World_GetRand(0,2)

elite_outcome = false

--assign the spawn point based on what
if EGroup_Exists("eg_NorthBridge_Barracks1") == false or EGroup_Exists("eg_NorthBridge_Barracks1") and EGroup_IsEmpty("eg_NorthBridge_Barracks1") then
	
	g_Bridge_Barracks1 = false
	
else
	
	if SGroup_Exists("sg_NorthBridge_Infantry1") == false or SGroup_IsEmpty("sg_NorthBridge_Infantry1") then
		
		--random chance of creating an elite unit
		local randelite = World_GetRand(1,10)
		
		if randelite == 1 then
			
			elite_outcome = true
			
		else
			
			elite_outcome = false
			
		end
		
		JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_NorthBridge_Infantry1", "mkr_NorthBridge_Barracks_Spawn1", randSS, randplasma, randgrenade, true, STANCE_Attack, elite_outcome)
		
		--spawn leader and attach to group
		if SGroup_Exists("sg_NorthBridge_Infantry_Leader1") == false or SGroup_IsEmpty("sg_NorthBridge_Infantry_Leader1") then
			
			JMUtil_Random_Leader_Spawn(g_Player2, "sg_NorthBridge_Infantry1", "mkr_NorthBridge_Barracks_Spawn1", "sg_NorthBridge_Infantry_Leader1", true)
			
		--if a previous leader is still alive, attach it instead
		elseif SGroup_Exists("sg_NorthBridge_Infantry_Leader1") and SGroup_IsEmpty("sg_NorthBridge_Infantry_Leader1") == false then
			
			Cmd_AttachSquads("sg_NorthBridge_Infantry1", "sg_NorthBridge_Infantry_Leader1")
			
		end
		
		SGroup_AddGroup("sg_NorthBridge_Infantry", "sg_NorthBridge_Infantry1")
		
	end
	
end

if EGroup_Exists("eg_NorthBridge_Barracks2") == false or EGroup_Exists("eg_NorthBridge_Barracks2") and EGroup_IsEmpty("eg_NorthBridge_Barracks2") then
	
	g_Bridge_Barracks2 = false
	
else
	
	if SGroup_Exists("sg_NorthBridge_Infantry2") == false or SGroup_IsEmpty("sg_NorthBridge_Infantry2") then
		
		--random chance of creating an elite unit
		local randelite = World_GetRand(1,10)
		
		if elite_outcome == false then
			
			if randelite == 1 then
				
				elite_outcome = true
				
			else
				
				elite_outcome = false
				
			end
			
		end
		
		JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_NorthBridge_Infantry2", "mkr_NorthBridge_Barracks_Spawn2", randSS, randplasma, randgrenade, true, STANCE_Attack, elite_outcome)
		
		--spawn leader and attach to group
		if SGroup_Exists("sg_NorthBridge_Infantry_Leader2") == false or SGroup_IsEmpty("sg_NorthBridge_Infantry_Leader2") then
			
			JMUtil_Random_Leader_Spawn(g_Player2, "sg_NorthBridge_Infantry2", "mkr_NorthBridge_Barracks_Spawn2", "sg_NorthBridge_Infantry_Leader2", true)
			
		--if a previous leader is still alive, attach it instead
		elseif SGroup_Exists("sg_NorthBridge_Infantry_Leader2") and SGroup_IsEmpty("sg_NorthBridge_Infantry_Leader2") == false then
			
			Cmd_AttachSquads("sg_NorthBridge_Infantry2", "sg_NorthBridge_Infantry_Leader2")
			
		end
		
		SGroup_AddGroup("sg_NorthBridge_Infantry", "sg_NorthBridge_Infantry2")
		
	end
	
end

if EGroup_Exists("eg_NorthBridge_HQ") == false or EGroup_Exists("eg_NorthBridge_HQ") and EGroup_IsEmpty("eg_NorthBridge_HQ") then
	
	g_Bridge_HQ = false
	
else
	
	if SGroup_Exists("sg_NorthBridge_Infantry1") == false or SGroup_IsEmpty("sg_NorthBridge_Infantry1") then
		
		--random chance of creating an elite unit
		local randelite = World_GetRand(1,10)
		
		if elite_outcome == false then
			
			if randelite == 1 then
				
				elite_outcome = true
				
			else
				
				elite_outcome = false
				
			end
			
		end
		
		JMUtil_Spawn_Upgraded_Kasrkin(g_Player2, "sg_NorthBridge_Infantry3", "mkr_NorthBridge_HQ_spawn", randSS, randplasma, randgrenade, true, STANCE_Attack, elite_outcome)
		
		--spawn leader and attach to group
		if SGroup_Exists("sg_NorthBridge_Infantry_Leader3") == false or SGroup_IsEmpty("sg_NorthBridge_Infantry_Leader3") then
			
			JMUtil_Random_Leader_Spawn(g_Player2, "sg_NorthBridge_Infantry3", "mkr_NorthBridge_HQ_spawn", "sg_NorthBridge_Infantry_Leader3", true)
			
		--if a previous leader is still alive, attach it instead
		elseif SGroup_Exists("sg_NorthBridge_Infantry_Leader3") and SGroup_IsEmpty("sg_NorthBridge_Infantry_Leader3") == false then
			
			Cmd_AttachSquads("sg_NorthBridge_Infantry3", "sg_NorthBridge_Infantry_Leader3")
			
		end
		
		SGroup_AddGroup("sg_NorthBridge_Infantry", "sg_NorthBridge_Infantry3")
		
	end
	
end


RebelBase_Entity = Player_GetAllEntitiesNearMarker(g_Player1, "eg_RebelBase_count", "mkr_Rebel_Base_Proximity")
RebelBase_Squad = Player_GetAllSquadsNearMarker(g_Player1, "sg_RebelBase_count", "mkr_Rebel_Base_Proximity")
RebelBase_ECount = EGroup_Count("eg_RebelBase_count")
RebelBase_SCount = SGroup_Count("sg_RebelBase_count")

--assign movement location.  If player has wrapped around and made it to the gens without destroying bridgebase, spawned units need to attack there instead of the players HQ area.
if SGroup_IsEmpty("sg_NorthBridge_Infantry") == false then
	
	if RebelBase_ECount > 0 or RebelBase_SCount > 0 then
		
		Cmd_AttackMoveMarker("sg_NorthBridge_Infantry", "mkr_Rebel_Base_Proximity")
		
	else
		
		local rand_mkr = World_GetRand(1,4)
		
		Cmd_AttackMoveMarker("sg_NorthBridge_Infantry", "mkr_Harasser_Attack_Point"..rand_mkr)
		
	end
	
end

--if the barracks and HQ are destroyed, remove the rule.
if g_Bridge_Mech1 == false and g_Bridge_Mech2 == false and g_Bridge_HQ == false then
	
	Rule_Remove(Rule_Bridge_Infantry_spawner)
	
end

end

function Rule_Island_Defense_Checker()

if Player_AreSquadsNearMarker(g_Player1,"mkr_Artillery_Trigger4") then
	
	Rule_AddInterval(Rule_Island_Defense, 30)
	
	Util_CreateSquadsAtMarker(g_Player2, "sg_Island_defenders", "guard_squad_hellhound", "mkr_Island_Mech_Spawn", 1)
	Util_CreateSquadsAtMarker(g_Player2, "sg_Island_defenders", "guard_squad_sentinel", "mkr_Island_Mech_Spawn", 1)
	Cmd_SetStance("sg_Island_defenders", STANCE_Attack)
	
	Cmd_AttackMoveMarker("sg_Island_defenders", "mkr_Island_Defense")
	
	Rule_Remove(Rule_Island_Defense_Checker)
	
elseif EGroup_Exists("eg_IG_Island_MechShop") == false or EGroup_Exists("eg_IG_Island_MechShop") and EGroup_IsEmpty("eg_IG_Island_MechShop") then
	
	Rule_Remove(Rule_Island_Defense_Checker)
	
end

end

function Rule_Island_Defense()

local randtype = World_GetRand(1,2)

g_Island_Defender_count = SGroup_Count("sg_Island_defenders")

if EGroup_Exists("eg_IG_Island_MechShop") and EGroup_IsEmpty("eg_IG_Island_MechShop") == false then
	
	if g_Island_Defender_count < 3 then
		
		if randtype == 1 then
			Util_CreateSquadsAtMarker(g_Player2, "sg_Island_defenders", "guard_squad_sentinel", "mkr_Island_Mech_Spawn", 1)
		elseif randtype == 2 then
			Util_CreateSquadsAtMarker(g_Player2, "sg_Island_defenders", "guard_squad_hellhound", "mkr_Island_Mech_Spawn", 1)
		end
		
		Cmd_SetStance("sg_Island_defenders", STANCE_Attack)
		Cmd_AttackMoveMarker("sg_Island_defenders", "mkr_Island_Defense")
		
	end
	
elseif EGroup_Exists("eg_IG_Island_MechShop") == false or EGroup_Exists("eg_IG_Island_MechShop") and EGroup_IsEmpty("eg_IG_Island_MechShop") then
	
	Rule_Remove(Rule_Island_Defense)
	
end

end

function Rule_Artillery_Control()

if g_Artillery_control_timer == 0 then
	
	Rule_AddOneShot(Rule_Artillery_Support1, 0)
	
	g_Artillery_control_timer = 20
	
end

if g_Artillery_Destroyed == true then
	
	Rule_Remove(Rule_Artillery_Control)
	
end

end

function Rule_Artillery_Fire_Stagger()

if g_Artillery_rand_tracker == 1 then
	
	Util_AttackGroundMarkerRandomRadius_Custom("sg_NPC_Island_ArtillerySG1", g_Artillery_Designator..1)
	Util_AttackGroundMarkerRandomRadius_Custom("sg_NPC_Island_ArtillerySG2", g_Artillery_Designator..2)
	
	g_Artillery_rand_tracker = 2
	
elseif g_Artillery_rand_tracker == 2 then
	
	Util_AttackGroundMarkerRandomRadius_Custom("sg_NPC_Island_ArtillerySG3", g_Artillery_Designator..3)
	Util_AttackGroundMarkerRandomRadius_Custom("sg_NPC_Island_ArtillerySG4", g_Artillery_Designator..4)
	
	g_Artillery_rand_tracker = 3
	
elseif g_Artillery_rand_tracker == 3 then

	Util_AttackGroundMarkerRandomRadius_Custom("sg_NPC_Island_ArtillerySG5", g_Artillery_Designator..5)
	Util_AttackGroundMarkerRandomRadius_Custom("sg_NPC_Island_ArtillerySG6", g_Artillery_Designator..6)
	
	g_Artillery_rand_tracker = 4
	
elseif g_Artillery_rand_tracker == 4 then
	
	Util_AttackGroundMarkerRandomRadius_Custom("sg_NPC_Island_ArtillerySG7", g_Artillery_Designator..7)
	Util_AttackGroundMarkerRandomRadius_Custom("sg_NPC_Island_ArtillerySG8", g_Artillery_Designator..8)
	
	g_Artillery_rand_tracker = 5
	
elseif g_Artillery_rand_tracker == 5 then
	
	Util_AttackGroundMarkerRandomRadius_Custom("sg_NPC_Island_ArtillerySG9", g_Artillery_Designator..9)
	Util_AttackGroundMarkerRandomRadius_Custom("sg_NPC_Island_ArtillerySG10", g_Artillery_Designator..10)
	
	g_Artillery_rand_tracker = 1
	
end

end

function Rule_Artillery_Warning_Audio()

if g_artillery_warning_timer == 0 then
	
	Anim_PlayEGroupAnim(EGroup_FromName(g_artillery_warning), "audio_warning")
	
	Rule_Remove(Rule_Artillery_Warning_Audio)
	
end

end

--Artillery Fire control. "j"applies artillery targets to specific artillery. "k" applies artillery targets to the bridge entrance only --[[DO NOT COMPRESS these if statements into a single for loop! it's difficult to make the artillery behave properly if you do.]] function Rule_Artillery_Support1()

if SGroup_Exists("sg_NPC_Island_Artillery") and SGroup_IsEmpty("sg_NPC_Island_Artillery") == false then
	
	if Player_AreSquadsNearMarker(g_Player1,"mkr_Artillery_Trigger1") then
		
		g_Artillery_Designator = "mkr_Artilley_Cluster1_"
		
		if Rule_Exists(Rule_Artillery_Fire_Stagger) == false then
			
			Rule_AddIntervalEx(Rule_Artillery_Fire_Stagger, 0.5, 5)
			
			--designate which warning audo entity to use
			g_artillery_warning = "eg_Artillery_Audio_Warning1"
			
			--add the delay timer
			g_artillery_warning_timer = 8
			
			--add rule to start audio warning once the delay timer has elapsed
			if Rule_Exists(Rule_Artillery_Warning_Audio) == false then
				Rule_AddInterval(Rule_Artillery_Warning_Audio, 0.5)
			end
			
		end
		
	elseif Player_AreSquadsNearMarker(g_Player1,"mkr_Artillery_Trigger2") then
		
		g_Artillery_Designator = "mkr_Artilley_Cluster2_"
		
		if Rule_Exists(Rule_Artillery_Fire_Stagger) == false then
			
			Rule_AddIntervalEx(Rule_Artillery_Fire_Stagger, 0.5, 5)
			
			--designate which warning audo entity to use
			g_artillery_warning = "eg_Artillery_Audio_Warning2"
			
			--add the delay timer
			g_artillery_warning_timer = 8
			
			--add rule to start audio warning once the delay timer has elapsed
			if Rule_Exists(Rule_Artillery_Warning_Audio) == false then
				Rule_AddInterval(Rule_Artillery_Warning_Audio, 0.5)
			end
			
		end
		
	elseif Player_AreSquadsNearMarker(g_Player1,"mkr_Artillery_Trigger3") then
		
		g_Artillery_Designator = "mkr_Artilley_Cluster3_"
		
		if Rule_Exists(Rule_Artillery_Fire_Stagger) == false then
			
			Rule_AddIntervalEx(Rule_Artillery_Fire_Stagger, 0.5, 5)
			
			--designate which warning audo entity to use
			g_artillery_warning = "eg_Artillery_Audio_Warning3"
			
			--add the delay timer
			g_artillery_warning_timer = 8
			
			--add rule to start audio warning once the delay timer has elapsed
			if Rule_Exists(Rule_Artillery_Warning_Audio) == false then
				Rule_AddInterval(Rule_Artillery_Warning_Audio, 0.5)
			end
			
		end
		
	elseif Player_AreSquadsNearMarker(g_Player1,"mkr_Artillery_Trigger4") then
		
		g_Artillery_Designator = "mkr_Artilley_Cluster4_"
		
		if Rule_Exists(Rule_Artillery_Fire_Stagger) == false then
			
			Rule_AddIntervalEx(Rule_Artillery_Fire_Stagger, 0.5, 5)
			
			--designate which warning audo entity to use
			g_artillery_warning = "eg_Artillery_Audio_Warning4"
			
			--add the delay timer
			g_artillery_warning_timer = 8
			
			--add rule to start audio warning once the delay timer has elapsed
			if Rule_Exists(Rule_Artillery_Warning_Audio) == false then
				Rule_AddInterval(Rule_Artillery_Warning_Audio, 0.5)
			end
			
		end
		
	elseif Player_AreSquadsNearMarker(g_Player1,"mkr_Artillery_Trigger5") then
		
		g_Artillery_Designator = "mkr_Artilley_Cluster5_"
		
		if Rule_Exists(Rule_Artillery_Fire_Stagger) == false then
			
			Rule_AddIntervalEx(Rule_Artillery_Fire_Stagger, 0.5, 5)
			
			--designate which warning audo entity to use
			g_artillery_warning = "eg_Artillery_Audio_Warning5"
			
			--add the delay timer
			g_artillery_warning_timer = 8
			
			--add rule to start audio warning once the delay timer has elapsed
			if Rule_Exists(Rule_Artillery_Warning_Audio) == false then
				Rule_AddInterval(Rule_Artillery_Warning_Audio, 0.5)
			end
			
		end
		
		g_Artillery_reveal = g_Artillery_reveal + 1
		
	else
		
		-- default to shelling the entrance to the bridge.	
		g_Artillery_Designator = "mkr_Artilley_Cluster6_"
		
		if Rule_Exists(Rule_Artillery_Fire_Stagger) == false then
			
			Rule_AddIntervalEx(Rule_Artillery_Fire_Stagger, 0.5, 5)
			
			--designate which warning audo entity to use
			g_artillery_warning = "eg_Artillery_Audio_Warning6"
			
			--add the delay timer
			g_artillery_warning_timer = 8
			
			--add rule to start audio warning once the delay timer has elapsed
			if Rule_Exists(Rule_Artillery_Warning_Audio) == false then
				Rule_AddInterval(Rule_Artillery_Warning_Audio, 0.5)
			end
			
		end
		
		g_Artillery_reveal = g_Artillery_reveal + 1
		
	end
	
else
	
	Rule_Remove(Rule_Artillery_Support1)
	g_Artillery_Destroyed = true
	
end

if g_Artillery_reveal == 1 and Rule_Exists(Rule_Objective_Destroy_Artillery) == false then
	
	Rule_AddInterval(Rule_Objective_Destroy_Artillery,5)
	
end


end

--[[util function to randomize the firing at ground markers so that it doesn't look so scripted. Lifted from Berger's Space marine Stronghold]] function Util_AttackGroundMarkerRandomRadius_Custom( squadgroupname, markername)

--saftey check, if the called group doesn't exist then nothing happens and there isn't a scar crash.
if SGroup_Exists(squadgroupname) and SGroup_IsEmpty(squadgroupname) == false 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 attackpos = World_Pos( xrand + pos.x, pos.y, zrand + pos.z )
	
	--Cmd_AttackGroundPos(squadgroupname, attackpos)
	
	
	
	Cmd_CastAbilityPos(squadgroupname, "earthshaker_round_stronghold", attackpos)
	
end

end

-- FB Rooftop patrol spawner, fired once to place rooftop patrols in initial positions function Rule_Rooftop_Patrol_Spawner_OneShot()

SGroup_CreateIfNotFound("sg_Rooftop_Patrol_Group")

for i = 1,3 do
	
	SGroup_CreateIfNotFound("sg_Rooftop_SG"..i)
	SGroup_AddGroup("sg_Rooftop_Patrol_Group","sg_Rooftop_SG"..i)
	
end

--create SG1 in initial position
JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Rooftop_SG1", "mkr_Roof_Patrol1", 8, 2, 1, true, STANCE_StandGround, false)

--create SG2 in initial position
JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Rooftop_SG2", "mkr_Roof_Patrol3", 8, 2, 1, true, STANCE_StandGround, false)

--create SG3 in initial position
JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Rooftop_SG1", "mkr_Roof_Patrol4", 8, 2, 1, true, STANCE_StandGround, false)

Rule_AddInterval(Rule_Rooftop_Patrol_Spawner,60)

end

-- FB Rooftop patrol spawner function Rule_Rooftop_Patrol_Spawner()

SGroup_CreateIfNotFound("sg_Rooftop_Patrol_Group")

--used for picking marker to move new SG's to
local rand = World_GetRand(1,5)

local emptysg = "sg_Rooftop_SG1"

--determine the number of squads currently patroling
g_Rooftop_Count = SGroup_Count("sg_Rooftop_Patrol_Group")

--will spawn a maximum of 2 separate SG's to patrol the rooftops if their are empty SG's in the patrol group
if g_Rooftop_Count < 2 then
	
	--create a SG at each barracks (if they exist)
	for k = 1,2 do
		
		if EGroup_Exists("eg_IG_FB_Barracks"..k) and EGroup_IsEmpty("eg_IG_FB_Barracks"..k) == false then
			
			if SGroup_IsEmpty("sg_Rooftop_SG"..k) then
				
				JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Rooftop_SG"..k, "mkr_NPC_FB_Spawn"..k, 8, 2, 1, true, STANCE_StandGround, false)
				SGroup_AddGroup("sg_Rooftop_Patrol_Group","sg_Rooftop_SG"..k)
				
				Cmd_AttackMoveMarker("sg_Rooftop_SG"..k,"mkr_Roof_Patrol"..rand)
				
			end
			
		end
		
	end
	
end


--if both FB barracks have been destroyed, stop spawning rooftop patrollers
if EGroup_IsEmpty("eg_IG_FB_Barracks1") and EGroup_IsEmpty("eg_IG_FB_Barracks2") then
	
	if Rule_Exists(Rule_Rooftop_Patrol_Spawner) then
		
		Rule_Remove(Rule_Rooftop_Patrol_Spawner)
		
	end
	
end

--start the patrol movement handler
if Rule_Exists(Rule_Rooftop_Patrol_Movement_Handler) == false then
	
	Rule_AddIntervalDelay(Rule_Rooftop_Patrol_Movement_Handler,60, 5)
	
end

end

function Rule_Rooftop_Patrol_Movement_Handler()

--used to pick a random marker position to move patrols to.
local rand = World_GetRand(1,5)
local randmrk = "mkr_Roof_Patrol"..rand

--used to pick a random squad to move
local randsg = World_GetRand(1,2)

if SGroup_Exists("sg_Rooftop_SG"..randsg) and SGroup_IsEmpty("sg_Rooftop_SG"..randsg) == false then
	
	--squads won't move if they are currently fighting someone since the have the highground and the streets below are negative cover.
	if SGroup_IsUnderAttack("sg_Rooftop_SG"..randsg, false) == false then
		
		--assign new empty marker positions to move existing squads to.  Two patrol squads should not share a marker.
		if Prox_AnySquadNearMarker("sg_Rooftop_Patrol_Group", randmrk) == false then
			
			Cmd_AttackMoveMarker("sg_Rooftop_SG"..randsg, randmrk)
			
		end
		
	end
	
end



--if the patrol parent group remains empty for more than 10 passes (overkill just to be safe) of the handler, then it is assumed that the FB barracks have been destroyed and the rule is removed.
if SGroup_IsEmpty("sg_Rooftop_Patrol_Group") then
	
	g_Rooftop_Start = g_Rooftop_Start + 1
	
	if g_Rooftop_Start > 10 then
		
		Rule_Remove(Rule_Rooftop_Patrol_Movement_Handler)
		
	end
	
end

end

--FB squad patrol control rules function Rule_FB_Squad_Patrol2()

if SGroup_Exists("sg_FB_Infantry2") and SGroup_IsEmpty("sg_FB_Infantry2") == false then
	
	if Prox_AnySquadNearMarker("sg_FB_Infantry2","mkr_FB_DefensePoint3") then
		
		Cmd_AttackMoveMarker("sg_FB_Infantry2","mkr_FB_PatrolPoint1")
		
	elseif Prox_AnySquadNearMarker("sg_FB_Infantry2","mkr_FB_PatrolPoint1") then
		
		Cmd_AttackMoveMarker("sg_FB_Infantry2","mkr_FB_PatrolPoint2")
		
	elseif Prox_AnySquadNearMarker("sg_FB_Infantry2","mkr_FB_PatrolPoint2") then
		
		Cmd_AttackMoveMarker("sg_FB_Infantry2","mkr_FB_PatrolPoint3")
		
	elseif Prox_AnySquadNearMarker("sg_FB_Infantry2","mkr_FB_PatrolPoint3") then
		
		Cmd_AttackMoveMarker("sg_FB_Infantry2","mkr_FB_DefensePoint2")
		
	elseif Prox_AnySquadNearMarker("sg_FB_Infantry2","mkr_FB_DefensePoint2") then
		
		Cmd_AttackMoveMarker("sg_FB_Infantry2","mkr_FB_DefensePoint3")
		
	--incase they are stuck in the field, this will get them back in the loop.	
	--[[else
		
		Cmd_AttackMoveMarker("sg_FB_Infantry2","mkr_FB_PatrolPoint2")]]
		
	end
	
elseif EGroup_CountSpawned("eg_IG_FB_Barracks2") == 0 and SGroup_Count("sg_FB_Infantry2") == 0 and SGroup_Exists("sg_FB_Infantry2") == false then
	
	Rule_Remove(Rule_FB_Squad_Patrol2)
	
elseif EGroup_CountSpawned("eg_IG_FB_Barracks2") == 0 and SGroup_Count("sg_FB_Infantry2") == 0 and SGroup_Exists("sg_FB_Infantry2") and SGroup_IsEmpty("sg_FB_Infantry2") then
	
	Rule_Remove(Rule_FB_Squad_Patrol2)
	
end

end

function Rule_Engineer_oneshot()

Util_CreateSquadsAtMarker(g_Player2, "sg_Thermo_Engineer", "guard_squad_enginseer", "mkr_Engineer_Patrol1", 1)

Cpu_LockSGroupAcrossPlayers("sg_Thermo_Engineer")

Rule_AddInterval(Rule_Engineer_Repair_Patrol,10)

end

function Rule_Engineer_Repair_Patrol()

--check for damage on any of the slag deposit plants, send the engineer to repair the first one with damage.
if SGroup_IsEmpty("sg_Thermo_Engineer") == false then
	
	for i = 1,6 do
		
		if EGroup_Exists("eg_Thermo_Plasma"..i) then
			
			health = EGroup_GetAvgHealth("eg_Thermo_Plasma"..i)
			
			if health < 1 then
				
				Command_SquadEntity(g_Player2, "sg_Thermo_Engineer", SCMD_Repair, "eg_Thermo_Plasma"..i)
			break	
			end
			
		end
		
	end
	
elseif SGroup_IsEmpty("sg_Thermo_Engineer") then
	
	Rule_Remove(Rule_Engineer_Repair_Patrol)
	
end

end

-- controler rule for the squad that recaptures strategic points function Rule_Strat_Capture_Squad_Manager()

if SGroup_Exists("sg_Strat_Capture_SG") and SGroup_IsEmpty("sg_Strat_Capture_SG") == false then
	
	--run movement logic
	Rule_AddOneShot(Rule_Strat_Capture_Mover,1)
	
elseif SGroup_Exists("sg_Strat_Capture_SG") == false or SGroup_Exists("sg_Strat_Capture_SG") and SGroup_IsEmpty("sg_Strat_Capture_SG") then
	
	-- run squad creation.  **Note that the squad creation is limited by a repawn timer, so it won't continously pump out aggressive guys.
	Rule_AddOneShot(Rule_Create_Capture_Squad,1)
	
end

if EGroup_Exists("eg_Northbridge_Base") == false or EGroup_Exists("eg_Northbridge_Base") and EGroup_IsEmpty("eg_Northbridge_Base") then
	
	Rule_Remove(Rule_Strat_Capture_Squad_Manager)
	
	g_Northbridge_Base_Destroyed = true
	
end

end

-- handles movement and strategic point target aquisition for the squad function Rule_Strat_Capture_Mover()

for i = 1,10 do
	
	if EGroup_IsCapturedByPlayer("eg_Strat_Point"..i, g_Player2, true) == false then
		
		-- if there are buildings in the area of the strategic point, then the entire squad will attack those
		if EGroup_HasStrategicPointWithStructure("eg_Strat_Point"..i) then
			
			Player_GetAllEntitiesNearMarker(g_Player1, "eg_Strat_Point_Entites"..i, "mkr_List_Post"..i)
			
			Cmd_AttackGroundMarker("sg_Strat_Capture_SG","mkr_List_Post"..i)
			
			--trigger IE event
			if g_strat_capture_IE_timer == 0 and Rule_Exists(Rule_Strat_Recapture_IE) == false then
				
				Rule_AddOneShot(Rule_Strat_Recapture_IE,1)
				
				--set an artificial delay before another IE can be called - reduces IE spam.
				g_strat_capture_IE_timer = 60
				
			end
			
		--if there are no buildings the squad will capture the point.
		elseif EGroup_HasStrategicPointWithStructure("eg_Strat_Point"..i) == false then
			
			Cmd_Capture("sg_Strat_Capture_SG", "eg_Strat_Point"..i)
			
			--if the sentinels exist, issue an attack order to the corresponding marker. Sometimes they do not move, usually when a strat point is neutral and the capture order doesn't apply to them.
			if SGroup_Exists("sg_Strat_Capture_Armor") then
				
				Cmd_AttackMoveMarker( "sg_Strat_Capture_Armor", "mkr_List_Post"..i)
				
			end
			
			--trigger IE event
			if g_strat_capture_IE_timer == 0 and Rule_Exists(Rule_Strat_Recapture_IE) == false then
				
				Rule_AddOneShot(Rule_Strat_Recapture_IE,1)
				
				--set an artificial delay before another IE can be called - reduces IE spam.
				g_strat_capture_IE_timer = 60
				
			end
			
		end
		
		break
		
	end
	
end

end

--called to generate a mixed squad of IG to recapture strategic points from the player function Rule_Create_Capture_Squad()

-- clear the iteration varibles to zero or else nothing will spawn the second time through the rule
g_Northbridge_Mech_iter = 0
g_Northbridge_Barracks_iter = 0

--used to chose either 1 or 2 support sentinels for the squad.
local randV = World_GetRand(1,2)

SGroup_CreateIfNotFound("sg_Strat_Capture_SG")

if g_Strat_Capture_Repawn ==  0 then
	
	--don't spawn sentinels until the time limit on the general timer has been reached.
	if g_ticker > 1200 then
		
		--check to see if a mech shop exists to spawn the sentinels from
		for j = 1,2 do
			
			if EGroup_IsEmpty("eg_NorthBridge_Mech"..j) == false and g_Northbridge_Mech_iter == 0 then
				
				-- do random 1 to 2 sentinel spawn
				Util_CreateSquadsAtMarker(g_Player2, "sg_Strat_Capture_Armor", "guard_squad_sentinel", "mkr_NorthBridge_Mech_Spawn"..j, randV)
				SGroup_AddGroup("sg_Strat_Capture_SG","sg_Strat_Capture_Armor")
				
				Cmd_SetStance("sg_Strat_Capture_Armor", STANCE_Attack)
				
				Cpu_LockSGroupAcrossPlayers("sg_Strat_Capture_Armor")
				
				g_Northbridge_Mech_iter = 1
				
			end
			
		end
		
	end
	
	--check to see if a barracks exists to spawn the infantry from
	for k = 1,2 do
		
		-- do mixed infantry and leader spawn
		if EGroup_IsEmpty("eg_NorthBridge_Barracks"..k) == false and g_Northbridge_Barracks_iter == 0 then
			
			for l = 1,2 do
				
				--a bunch of iterated random vaibles to change out the weapon loud out and squad size slightly for each squad spawned
				local randSS = World_GetRand(6,8)
				local randplasma = World_GetRand(2,3)
				local randgrenade = World_GetRand(1,2)
				
				JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Strat_Capture_Infantry"..l, "mkr_NorthBridge_Barracks_Spawn"..k, randSS, randplasma, randgrenade, true, STANCE_Attack, false)
				SGroup_AddGroup("sg_Strat_Capture_SG","sg_Strat_Capture_Infantry"..l)
				
				--JMUtil_Random_Leader_Spawn(g_Player2, "sg_Strat_Capture_Infantry_Leader"..l, "mkr_NorthBridge_Barracks_Spawn"..k, "sg_Strat_Capture_Infantry"..l, true)
				--SGroup_AddGroup("sg_Strat_Capture_SG","sg_Strat_Capture_Infantry_Leader"..l)
				
			end
			
			g_Northbridge_Barracks_iter = 1
			
		end
		
	end
	
	g_Strat_Capture_Repawn = 600
	
end

end

function Rule_IG_Troops_Streamer()

t_armor_streamers_BP = {--[[1]] "guard_squad_sentinel", --[[2]] "guard_squad_hellhound", --[[3]] "guard_squad_sentinel_advance_sp"} 

local armor_count = SGroup_Count(SGroup_CreateIfNotFound("sg_Armor_Streamers"))
local infantry_count = SGroup_Count(SGroup_CreateIfNotFound("sg_Infantry_Streamers"))

SGroup_CreateIfNotFound("sg_Streamer_Parent")

--streamers will only spawn once the northbridge is destroyed.  This prevents overwhelming forces being loosed on the player.
if g_Northbridge_Base_Destroyed == true then
	
	-- if the perimiter of the stronghold currently does not contain player units, create streamers.  This avoids rediculous amounts of units being created when the player is in the stronghold area.
	if g_stronghold_perimeter == false then
		
		--create more armor
		if armor_count < 2 then
			
			if EGroup_Exists("eg_IG_HQ_Mech2") and EGroup_CountSpawned("eg_IG_HQ_Mech2") > 0 then
				
				--each spawn determines rand again to help vary the waves.
				local rand = World_GetRand(1,3)
				
				Util_CreateSquadsAtMarker(g_Player2, "sg_Armor_Streamers", t_armor_streamers_BP[rand], "mkr_HQ_MechShop_Spawn2", 1)
				
			elseif EGroup_Exists("eg_IG_HQ_Mech1") and EGroup_CountSpawned("eg_IG_HQ_Mech1") > 0 then
				
				--each spawn determines rand again to help vary the waves.
				local rand = World_GetRand(1,3)
				
				Util_CreateSquadsAtMarker(g_Player2, "sg_Armor_Streamers", t_armor_streamers_BP[rand], "mkr_HQ_MechShop_Spawn2", 1)
				
			end
			
			if EGroup_Exists("eg_Slagbase_Mech") and EGroup_CountSpawned("eg_Slagbase_Mech") > 0 then
				
				--each spawn determines rand again to help vary the waves.
				local rand = World_GetRand(1,3)
				
				Util_CreateSquadsAtMarker(g_Player2, "sg_Armor_Streamers", t_armor_streamers_BP[rand], "mkr_Slag_Mech_Spawn", 1)
				
			end
			
			if EGroup_Exists("eg_Rebel_Mech1") and EGroup_CountSpawned("eg_Rebel_Mech1") > 0 then
				
				if Player_OwnsEGroup(g_Player3, "eg_Rebel_Mech1") then
					
					--each spawn determines rand again to help vary the waves.
					local rand = World_GetRand(1,3)
					
					Util_CreateSquadsAtMarker(g_Player2, "sg_Armor_Streamers", t_armor_streamers_BP[rand], "mkr_Rebel_Mech_Spawn", 1)
					
				end
				
			end
			
			SGroup_AddGroup("sg_Streamer_Parent", "sg_Armor_Streamers")
			
		end
		
		--create more infantry
		if infantry_count < 2  then
			
			if EGroup_Exists("eg_IG_HQ_Barracks1") and EGroup_CountSpawned("eg_IG_HQ_Barracks1") > 0 then
				
				local rand_elite1 = World_GetRand(1,g_Streamer_Elite) -- %chance to spawn an elite guardsmen squad
				
				if rand_elite1 == 1 then
					
					elite_outcome = true
					
				else
					
					elite_outcome = false
					
				end
				
				JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Infantry_Streamers_temp", "mkr_HQ_Barracks_Spawn1", 8, g_Streamer_plasma, g_Streamer_grenade, true, STANCE_Attack, elite_outcome)
				
				local rand = World_GetRand(1,2) -- %chance to spawn a leader for the group
				
				if rand == 1 then
					
					JMUtil_Random_Leader_Spawn(g_Player2, "sg_Infantry_Streamers_temp", "mkr_HQ_Barracks_Spawn1", "sg_Infantry_Streamers_temp_leader", true)
					
					SGroup_Clear("sg_Infantry_Streamers_temp_leader")
					
				end
				
				SGroup_AddGroup("sg_Infantry_Streamers", "sg_Infantry_Streamers_temp")
				
				SGroup_Clear("sg_Infantry_Streamers_temp")
				
			end
			
			if EGroup_Exists("eg_IG_HQ_Barracks2") and EGroup_CountSpawned("eg_IG_HQ_Barracks2") > 0 then
				
				local rand_elite2 = World_GetRand(1,g_Streamer_Elite) -- %chance to spawn an elite guardsmen squad
				
				if rand_elite2 == 1 then
					
					elite_outcome = true
					
				else
					
					elite_outcome = false
					
				end
				
				JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Infantry_Streamers_temp", "mkr_HQ_Barracks_Spawn2", 8, g_Streamer_plasma, g_Streamer_grenade, true, STANCE_Attack, elite_outcome)
				
				local rand = World_GetRand(1,2) -- %chance to spawn a leader for the group
				
				if rand == 1 then
					
					JMUtil_Random_Leader_Spawn(g_Player2, "sg_Infantry_Streamers_temp", "mkr_HQ_Barracks_Spawn2", "sg_Infantry_Streamers_temp_leader", true)
					
					SGroup_Clear("sg_Infantry_Streamers_temp_leader")
					
				end
				
				SGroup_AddGroup("sg_Infantry_Streamers", "sg_Infantry_Streamers_temp")
				
				SGroup_Clear("sg_Infantry_Streamers_temp")
				
			end
			
			if EGroup_Exists("eg_SlagBase_Barracks") and EGroup_CountSpawned("eg_SlagBase_Barracks") > 0 then
				
				local rand_elite3 = World_GetRand(1,g_Streamer_Elite) -- %chance to spawn an elite guardsmen squad
				
				if rand_elite3 == 1 then
					
					elite_outcome = true
					
				else
					
					elite_outcome = false
					
				end
				
				JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Infantry_Streamers_temp", "mkr_Slag_Barracks_Spawn", 8, g_Streamer_plasma, g_Streamer_grenade, true, STANCE_Attack, elite_outcome)
				
				local rand = World_GetRand(1,2) -- %chance to spawn a leader for the group
				
				if rand == 1 then
					
					JMUtil_Random_Leader_Spawn(g_Player2, "sg_Infantry_Streamers_temp", "mkr_Slag_Barracks_Spawn", "sg_Infantry_Streamers_temp_leader", true)
					
					SGroup_Clear("sg_Infantry_Streamers_temp_leader")
					
				end
				
				SGroup_AddGroup("sg_Infantry_Streamers", "sg_Infantry_Streamers_temp")
				
				SGroup_Clear("sg_Infantry_Streamers_temp")
				
			end
			
			if EGroup_Exists("eg_Rebel_Barracks") and EGroup_CountSpawned("eg_Rebel_Barracks") > 0 then 
				
				if Player_OwnsEGroup(g_Player3, "eg_Rebel_Barracks") then
					
					local rand_elite4 = World_GetRand(1,g_Streamer_Elite) -- %chance to spawn an elite guardsmen squad
					
					if rand_elite4 == 1 then
						
						elite_outcome = true
						
					else
						
						elite_outcome = false
						
					end
					
					JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Infantry_Streamers_temp", "mkr_Rebel_Spawn", 8, g_Streamer_plasma, g_Streamer_grenade, true, STANCE_Attack, elite_outcome)
					
					local rand = World_GetRand(1,2) -- %chance to spawn a leader for the group
					
					if rand == 1 then
						
						JMUtil_Random_Leader_Spawn(g_Player2, "sg_Infantry_Streamers_temp", "mkr_Rebel_Spawn", "sg_Infantry_Streamers_temp_leader", true)
						
						SGroup_Clear("sg_Infantry_Streamers_temp_leader")
						
					end
					
					SGroup_AddGroup("sg_Infantry_Streamers", "sg_Infantry_Streamers_temp")
					
					SGroup_Clear("sg_Infantry_Streamers_temp")
					
				end
				
			end
			
			SGroup_AddGroup("sg_Streamer_Parent", "sg_Infantry_Streamers")
			
		end
		
		--check to see if the player has gens to power the gun. If so, the button visibility varible is toggled true, else false.
		Slag_check = Player_GetAllEntitiesNearMarker(g_Player1, "eg_slag_check", "mkr_slag_gen_check")
		Slag_count = EGroup_Count("eg_slag_check")
		
		--if the titan gens are in the players control, divert streamers to harass them. (This will put more men in the canyon for the player to shoot with the cannon and emphasize the generator defense)
		if Slag_count > 0 then
			
			Util_AttackMoveMarkerRandomRadius("sg_Streamer_Parent", "mkr_slag_gen_check")
			
		else
			
			--move streamers along the "front line".
			RebelBase_Entity = Player_GetAllEntitiesNearMarker(g_Player1, "eg_RebelBase_count", "mkr_Rebel_Base_Proximity")
			RebelBase_Squad = Player_GetAllSquadsNearMarker(g_Player1, "sg_RebelBase_count", "mkr_Rebel_Base_Proximity")
			RebelBase_ECount = EGroup_Count("eg_RebelBase_count")
			RebelBase_SCount = SGroup_Count("sg_RebelBase_count")
			
			Bridge_Entity = Player_GetAllEntitiesNearMarker(g_Player1, "eg_Bridge_count", "mkr_Bridge_counter")
			Bridge_Squad = Player_GetAllSquadsNearMarker(g_Player1, "sg_Bridge_count", "mkr_Bridge_counter")
			Bridge_ECount = EGroup_Count("eg_Bridge_count")
			Bridge_SCount = SGroup_Count("sg_Bridge_count")
			
			Armor_Entity = Player_GetAllEntitiesNearMarker(g_Player1, "eg_Armor_count", "mkr_Armor_Base")
			Armor_Squad = Player_GetAllSquadsNearMarker(g_Player1, "sg_Armor_count", "mkr_Armor_Base")
			Armor_ECount = EGroup_Count("eg_Armor_count")
			Armor_SCount = SGroup_Count("sg_Armor_count")
			
			if RebelBase_ECount > 0 or RebelBase_SCount > 0 then
				
				Cmd_AttackMoveMarker("sg_Streamer_Parent", "mkr_slag_gen_check")
				
			elseif Bridge_ECount > 0 or Bridge_SCount > 0 then
				
				Cmd_AttackMoveMarker( "sg_Streamer_Parent", "mkr_Bridge_counter")
				
			elseif Armor_ECount > 0 or Armor_SCount > 0 then
				
				Cmd_AttackMoveMarker( "sg_Streamer_Parent", "mkr_Armor_Base")
				
			else
				
				Cmd_AttackMoveMarker("sg_Streamer_Parent",  "mkr_Player_Base_Grabber")
				
			end
			
		end
		
	end
	
end

end

function Rule_Streamer_backup_checker()

for i = 1,2 do
	
	if Player_AreSquadsNearMarker(g_Player1, "mkr_BridgeHead_North"..i) then
		
		Rule_AddInterval(Rule_IG_Troops_Streamer, 30)
		
		Rule_Remove(Rule_Streamer_backup_checker)
		
	end
	
end

end

--create AI controllable engineers function Rule_Engineer_Spawner()

if g_gameover == false then
	
	SGroup_CreateIfNotFound("sg_HQ_Engineer")
	SGroup_CreateIfNotFound("sg_NorthBridge_HQ_Engineer")
	
	if EGroup_Exists("eg_IG_HQ") and EGroup_IsEmpty("eg_IG_HQ") == false then
		
		if SGroup_Exists("sg_HQ_Engineer") == false or SGroup_Exists("sg_HQ_Engineer") and SGroup_IsEmpty("sg_HQ_Engineer") then
			
			Util_CreateSquadsAtMarker(g_Player2, "sg_HQ_Engineer", "guard_squad_enginseer", "mkr_NPC_HQ_Spawn", 1)
			
		end
		
	end
	
	if EGroup_Exists("eg_NorthBridge_HQ") and EGroup_IsEmpty("eg_NorthBridge_HQ") == false then
		
		if SGroup_Exists("sg_NorthBridge_HQ_Engineer") == false or SGroup_Exists("sg_NorthBridge_HQ_Engineer") and SGroup_IsEmpty("sg_NorthBridge_HQ_Engineer") then
			
			Util_CreateSquadsAtMarker(g_Player2, "sg_NorthBridge_HQ_Engineer", "guard_squad_enginseer", "mkr_NorthBridge_HQ_spawn", 1)
			
		end
		
	end
	
end

end

function Rule_Invulnerability_Checker()

SGroup_CreateIfNotFound("sg_Invulnerability_Check")

--clear out the group as a precaution - no shenanigans!
SGroup_Clear("sg_Invulnerability_Check")

--add selected players units to the "sg_Invulnerability_Check" group to be checked
SGroup_AddGroup("sg_Invulnerability_Check", Player_GetSquads(g_Player2))

--initially check the entire group for any invulerable units,  if this high level check comes back false it spares a lot of possible cpu time checking each unit.
if SGroup_GetHealthInvulnerable("sg_Invulnerability_Check", false) == true then
	
	count = SGroup_CountSpawned("sg_Invulnerability_Check")
	
	for i = 1,count do
		
		if Squad_GetHealthInvulnerable(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Invulnerability_Check"), i)) == true then
			
			--set the invulnerable unit to vulnerable.
			Squad_SetHealthInvulnerable(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Invulnerability_Check"), i), false)
			
			print("Invulnerablility toggled off")
			
		end
		
	end
	
end

end


--[[Custom Utils]]

--[[Will generate a random melee stance for the specified squad based on the percentage value passed in. Example: a value of 2 results in a 50% chance, while an 8 would result in 12.5% chance]] function JMUtil_Random_Melee_Stance(percentage, squadgroup)

local randmelee = World_GetRand(1,percentage)

if randmelee == 1 then
	
	Cmd_SetMeleeStance(squadgroup, MSTANCE_Assault)
	
end

end

--randomly chooses to spawn a leader unit from table when called and attaches it to another squad. function JMUtil_Random_Leader_Spawn(playerid, squadgroupname, markername, sgattachee, AiLocked)

rand = World_GetRand(1,3)
randleader = {"guard_squad_commissar", "guard_squad_priest", "guard_squad_psyker"}

Util_CreateSquadsAtMarker(playerid,sgattachee, randleader[rand], markername,1) 
Cmd_AttachSquads(squadgroupname, sgattachee)

if AiLocked == true then
	Cpu_LockSGroupAcrossPlayers(sgattachee)
end

end

--spawn 1 upgraded guardsmen squad based on values fed into the function function JMUtil_Spawn_Upgraded_Guardmen(playerid, squadgroupname, markername, squadsize, plasmacount, grenadecount, AiLocked, stance, elite)

if elite == true then
	
	bp = "guard_squad_guardsmen_advance_sp"
	
elseif elite == false then
	
	bp = "guard_squad_guardsmen"
	
end

Util_CreateSquadsAtMarkerEx(playerid, squadgroupname, bp, markername, 1, squadsize)

if plasmacount > 0 then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName(squadgroupname), 1),"guard_plasma_gun_guardsmen",plasmacount)
end

if grenadecount > 0 then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName(squadgroupname), 1),"guard_grenade_launcher_guardsmen",grenadecount)
end

if AiLocked == true then
	Cpu_LockSGroupAcrossPlayers(squadgroupname)
end

Cmd_SetStance(squadgroupname, stance)

end

--spawn 1 upgraded kasrkin squad based on values fed into the function function JMUtil_Spawn_Upgraded_Kasrkin(playerid, squadgroupname, markername, squadsize, plasmacount, grenadecount, AiLocked, stance, elite)

if elite == true then
	
	bp = "guard_squad_kasrkin_advance_sp"
	
elseif elite == false then
	
	bp = "guard_squad_kasrkin"
	
end

Util_CreateSquadsAtMarkerEx(playerid, squadgroupname, "guard_squad_kasrkin", markername, 1, squadsize)

if plasmacount > 0 then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName(squadgroupname), 1),"guard_plasma_gun_kasrkin",plasmacount)
end

if grenadecount > 0 then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName(squadgroupname), 1),"guard_grenade_launcher_kasrkin",grenadecount)
end

if AiLocked == true then
	Cpu_LockSGroupAcrossPlayers(squadgroupname)
end

Cmd_SetStance(squadgroupname, stance)

end


--[[Spawning and Upgrading Things on the map]]

--[[Create all IG controlled buildings]] function Rule_Create_HQ_Buildings()

	--[[HQ]]
	
	EGroup_CreateIfNotFound("eg_IG_HQ_Destroy")
	EGroup_CreateIfNotFound("eg_IG_Outro_NIS_Destroy")
	
	--create HQ
	Entity_CreateBuildingMarker(g_Player2,"eg_IG_HQ", "guard_hq","mkr_NPC_HQ", 1)
	EGroup_ForceAddOn("eg_IG_HQ", "addon_guard_hq_2")
	EGroup_AddGroup("eg_IG_HQ_Destroy", "eg_IG_HQ")
	
	--create HQ Mars Pattern
	Entity_CreateBuildingMarker(g_Player2,"eg_IG_HQ_Mars","guard_mars_pattern","mkr_NPC_MarsPattern", 1)
	EGroup_AddGroup("eg_IG_HQ_Destroy", "eg_IG_HQ_Mars")
	
	--create HQ tactica
	Entity_CreateBuildingMarker(g_Player2,"eg_IG_HQ_Tactica","guard_tactica","mkr_NPC_Tactica", 1)
	EGroup_AddGroup("eg_IG_HQ_Destroy", "eg_IG_HQ_Tactica")
	
	--create ALL plasma gens - DEFUNCT - plasmas have been placed manually
	--[[for i = 1, 8 do
		
		Entity_CreateBuildingMarker(g_Player2,"eg_IG_Generator"..i, "guard_plasma_generator","mkr_NPC_PlasmaGen"..i, 1)
		
	end]]
	
	--create HQ turrets
	for i = 1,8 do
		
		Entity_CreateBuildingMarker(g_Player2,"eg_IG_HQ_BolterTurrets"..i,"guard_turret_heavy_bolter","mkr_NPC_BolterTurret"..i, 1)
		EGroup_AddGroup("eg_IG_HQ_Destroy", "eg_IG_HQ_BolterTurrets"..i)
		EGroup_AddGroup("eg_IG_Outro_NIS_Destroy", "eg_IG_HQ_BolterTurrets"..i)
		
	end
	
	--create HQ barracks
	for j = 1,2 do
		
		Entity_CreateBuildingMarker(g_Player2,"eg_IG_HQ_Barracks"..j,"guard_infantry","mkr_NPC_HQ_Barracks"..j, 1)
		EGroup_AddGroup("eg_IG_HQ_Destroy", "eg_IG_HQ_Barracks"..j)
		
	end
	
	--create HQ Mech shop
	for k = 1,2 do
		
		Entity_CreateBuildingMarker(g_Player2,"eg_IG_HQ_Mech"..k,"guard_mechanized","mkr_NPC_HQ_Mech"..k, 1)
		EGroup_AddGroup("eg_IG_HQ_Destroy", "eg_IG_HQ_Mech"..k)
		
	end
	
	

end

function Rule_Create_Bridge_Buildings()

EGroup_Create("eg_IG_Bridge_Turrets")

--create Bridge bolter turrets
for i = 1,4 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_IG_Bridge_BolterTurrets"..i,"guard_turret_heavy_bolter","mkr_NPC_Bridge_Bolter"..i, 1)
	EGroup_AddGroup("eg_IG_Bridge_Turrets","eg_IG_Bridge_BolterTurrets"..i)
	
end

--create Bridge rocket turrets
for i = 1,4 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_IG_Bridge_RocketTurrets"..i,"guard_turret_heavy_bolter","mkr_NPC_Bridge_Rocket"..i, 1)
	EGroup_AddGroup("eg_IG_Bridge_Turrets","eg_IG_Bridge_RocketTurrets"..i)
	
end

--create bridge minefields
for i = 1,12 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_IG_Bridge_Mines"..i,"guard_mines","mkr_NPC_Bridge_Mines"..i, 1)
	
end

end

function Rule_Create_Islandbase_Buildings()

--[[ISLAND BASE]]

--create island entrance minefields
for i = 1,6 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_IG_Island_Mines"..i,"guard_mines","mkr_NPC_Island_Mines"..i, 1)
	
end

--create Island bolter turrets
for i = 1,2 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_IG_Island_BolterTurrets"..i,"guard_turret_heavy_bolter","mkr_NPC_Island_Turret"..i, 1)
	
end

--create island mech shop
Entity_CreateBuildingMarker(g_Player2,"eg_IG_Island_MechShop","guard_mechanized","mkr_NPC_Machine_Shop_Island", 1)

end

function Rule_Create_ForwardBase_Buildings()

--[[FORWARD BASE]]

--create FB (Forward Base) barracks
for i = 1,2 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_IG_FB_Barracks"..i,"guard_infantry","mkr_NPC_FB_Barracks"..i, 1)
	
	EGroup_AddGroup(EGroup_CreateIfNotFound("eg_FB_Buildings"), "eg_IG_FB_Barracks"..i)
	
end

--create FB bolter turrets.  The turrets are not to be added to the buildings eg_FB_Buildings group.
for i = 1,6 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_IG_FB_BolterTurrets"..i,"guard_turret_heavy_bolter","mkr_NPC_FB_Turret"..i, 1)
	
end

end

function Rule_Create_Rebel_Buildings()

--[[REBEL BASE]]

--create Rebel barracks
Entity_CreateBuildingMarker(g_Player3,"eg_Rebel_Barracks","guard_infantry","mkr_Rebel_Barracks", 1)
EGroup_AddGroup(EGroup_CreateIfNotFound("eg_All_Rebel_Buildings"),"eg_Rebel_Barracks")

--create Rebel Plasmagens
for i = 1, 2 do
	
	Entity_CreateBuildingMarker(g_Player3,"eg_Rebel_Generator"..i, "guard_plasma_generator","mkr_Rebel_PlasmaGen"..i, 1)
	EGroup_AddGroup(EGroup_CreateIfNotFound("eg_All_Rebel_Buildings"),"eg_Rebel_Generator"..i)
	
end

--[[create Rebel bolter turrets
for j = 1,2 do
	
	Entity_CreateBuildingMarker(g_Player3,"eg_Rebel_BolterTurrets"..j,"guard_turret_heavy_bolter","mkr_Rebel_Turret"..j, 1)
	EGroup_AddGroup(EGroup_CreateIfNotFound("eg_All_Rebel_Buildings"),"eg_Rebel_BolterTurrets"..j)
	
end]]

--create mech plant
Entity_CreateBuildingMarker(g_Player3,"eg_Rebel_Mech1", "guard_mechanized","mkr_Rebel_Base_Mech1", 1)
EGroup_AddGroup(EGroup_CreateIfNotFound("eg_All_Rebel_Buildings"),"eg_Rebel_Mech1")

end

function Rule_Create_Slagbase_Buildings()

--[[SLAG BASE]]

--create SlagBase Barracks
for i = 1,5 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_SlagBase_Barracks"..i,"guard_infantry","mkr_Slag_Barracks"..i, 1)
	
end

--create SlagBase Turrets
for i = 1,9 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_Slagbase_BolterTurret"..i,"guard_turret_heavy_bolter","mkr_SlagBase_Turret"..i, 1)
	
end

Rule_AddOneShot(Rule_Upgrade_Slagbase_Turrets, 1)

--create SlagBase Mechshops
for i = 1,6 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_Slagbase_Mech"..i,"guard_mechanized","mkr_Slag_Mech"..i, 1)
	
end

end

function Rule_Create_Armor_Buildings()

EGroup_CreateIfNotFound("eg_AB_Buildings")

for i = 1,2 do
	
	Entity_CreateBuildingMarker(g_Player2,"eg_Bridgebase_Mech"..i,"guard_mechanized","mkr_BB_Mech"..i, 1)
	EGroup_AddGroup("eg_AB_Buildings","eg_Bridgebase_Mech"..i)
	
end

--create airstrike control building
Entity_CreateBuildingMarker(g_Player2,"eg_Airstrike_HQ","guard_hq","mkr_Airstrike_Control", 1)
EGroup_AddGroup("eg_AB_Buildings","eg_Airstrike_HQ")

--create barracks
Entity_CreateBuildingMarker(g_Player2, "eg_Mechbase_barracks", "guard_infantry", "mkr_Mechbase_barracks", 1)

end

function Rule_Create_NorthBridge_Buildings()

EGroup_Create("eg_Northbridge_Base")

for i = 1,2 do
	
	Entity_CreateBuildingMarker(g_Player2, "eg_NorthBridge_Mech"..i, "guard_mechanized", "mkr_NorthBridge_Mech"..i, 1)
	Entity_CreateBuildingMarker(g_Player2, "eg_NorthBridge_Barracks"..i, "guard_infantry", "mkr_NorthBridge_Barracks"..i, 1)
	
	EGroup_AddGroup("eg_Northbridge_Base", "eg_NorthBridge_Mech"..i)
	EGroup_AddGroup("eg_Northbridge_Base", "eg_NorthBridge_Barracks"..i)		
	
end

--do not add the HQ to the eg_Northbridge_Base group, or else it will completely break the strat point capture squad stuff
Entity_CreateBuildingMarker(g_Player2,"eg_NorthBridge_HQ","guard_hq","mkr_NorthBridge_HQ", 1)

end


--[[Player buildings and builder units ]]

function Rule_Create_Player_Buildings()

t_Player_Buildings ={

chaos_name = {"eg_Player_HQ"},
chaos_building_blueprint = {"chaos_hq"},
chaos_marker_spawn = {"mkr_Player_HQ"},

eldar_name = {"eg_Player_HQ"},
eldar_building_blueprint = {"eldar_hq"},
eldar_marker_spawn ={"mkr_Player_HQ"}, 

guard_name = {"eg_Player_HQ"},
guard_building_blueprint = {"guard_hq"}, 
guard_marker_spawn ={"mkr_Player_HQ"},

ork_name = {"eg_Player_HQ"},
ork_building_blueprint = {"ork_hq"},
ork_marker_spawn ={"mkr_Player_HQ"},

marines_name = {"eg_Player_HQ"},
marines_building_blueprint = {"space_marine_hq"},
marines_marker_spawn ={"mkr_Player_HQ"},

tau_name = {"eg_Player_HQ"},
tau_building_blueprint = {"tau_hq"},
tau_marker_spawn= {"mkr_Player_HQ"},

necron_name ={"eg_Player_HQ"},
necron_building_blueprint = {"monolith"},
necron_marker_spawn = {"mkr_Player_HQ"},

}

t_Player_Builder_Units = {

chaos_buildername = {"sg_Player_Builder"},
chaos_builder_blueprint = {"chaos_squad_slave"},
chaos_buildermarker_spawn = {"mkr_Player_Builder"},

eldar_buildername = {"sg_Player_Builder"},
eldar_builder_blueprint = {"eldar_squad_bonesinger"},
eldar_buildermarker_spawn ={"mkr_Player_Builder"}, 

guard_buildername = {"sg_Player_Builder"},
guard_builder_blueprint = {"guard_squad_enginseer"}, 
guard_buildermarker_spawn ={"mkr_Player_Builder"},

ork_buildername = {"sg_Player_Builder"},
ork_builder_blueprint = {"ork_squad_grot"},
ork_buildermarker_spawn ={"mkr_Player_Builder"},

marines_buildername = {"sg_Player_Builder"},
marines_builder_blueprint = {"space_marine_squad_servitor"},
marines_buildermarker_spawn ={"mkr_Player_Builder"},

tau_buildername = {"sg_Player_Builder"},
tau_builder_blueprint = {"tau_builder_squad"},
tau_buildermarker_spawn= {"mkr_Player_Builder"},

necron_buildername ={"sg_Player_Builder"},
necron_builder_blueprint = {"necron_builder_scarab_squad"},
necron_buildermarker_spawn = {"mkr_Player_Builder"},
}




if MetaMap_GetPlayerRaceName() == "chaos_marine_race" then

	for i = 1, table.getn(t_Player_Buildings.chaos_name) do
		
		Entity_CreateBuildingMarker(g_Player1, t_Player_Buildings.chaos_name[i], t_Player_Buildings.chaos_building_blueprint[i], t_Player_Buildings.chaos_marker_spawn[i], 1)
		Util_CreateSquadsAtMarkerEx(g_Player1, t_Player_Builder_Units.chaos_buildername[i], t_Player_Builder_Units.chaos_builder_blueprint[i], t_Player_Builder_Units.chaos_buildermarker_spawn[i], 1, 1)
		
		
	end

elseif MetaMap_GetPlayerRaceName() == "eldar_race" then

	for i = 1, table.getn(t_Player_Buildings.eldar_name) do
	
		Entity_CreateBuildingMarker(g_Player1, t_Player_Buildings.eldar_name[i], t_Player_Buildings.eldar_building_blueprint[i], t_Player_Buildings.eldar_marker_spawn[i], 1)
		Util_CreateSquadsAtMarkerEx(g_Player1, t_Player_Builder_Units.eldar_buildername[i], t_Player_Builder_Units.eldar_builder_blueprint[i], t_Player_Builder_Units.eldar_buildermarker_spawn[i], 1, 1)
	
	end

elseif MetaMap_GetPlayerRaceName() == "guard_race" then

	for i = 1, table.getn(t_Player_Buildings.guard_name) do
	
		Entity_CreateBuildingMarker(g_Player1, t_Player_Buildings.guard_name[i], t_Player_Buildings.guard_building_blueprint[i], t_Player_Buildings.guard_marker_spawn[i], 1)
		Util_CreateSquadsAtMarkerEx(g_Player1, t_Player_Builder_Units.guard_buildername[i], t_Player_Builder_Units.guard_builder_blueprint[i], t_Player_Builder_Units.guard_buildermarker_spawn[i], 1, 1)
		
	
	end

elseif MetaMap_GetPlayerRaceName() == "ork_race" then

	for i = 1, table.getn(t_Player_Buildings.ork_name) do
		
		Entity_CreateBuildingMarker(g_Player1, t_Player_Buildings.ork_name[i], t_Player_Buildings.ork_building_blueprint[i], t_Player_Buildings.ork_marker_spawn[i], 1)
		Util_CreateSquadsAtMarkerEx(g_Player1, t_Player_Builder_Units.ork_buildername[i], t_Player_Builder_Units.ork_builder_blueprint[i], t_Player_Builder_Units.ork_buildermarker_spawn[i], 1, 1)
		
		
	end

elseif MetaMap_GetPlayerRaceName() == "space_marine_race" then

	for i = 1, table.getn(t_Player_Buildings.marines_name) do
		
		Entity_CreateBuildingMarker(g_Player1, t_Player_Buildings.marines_name[i], t_Player_Buildings.marines_building_blueprint[i], t_Player_Buildings.marines_marker_spawn[i], 1)
		Util_CreateSquadsAtMarkerEx(g_Player1, t_Player_Builder_Units.marines_buildername[i], t_Player_Builder_Units.marines_builder_blueprint[i], t_Player_Builder_Units.marines_buildermarker_spawn[i], 1, 1)
		
		
	end
	
elseif MetaMap_GetPlayerRaceName() == "tau_race" then
	
	for i = 1, table.getn(t_Player_Buildings.tau_name) do
		
		Entity_CreateBuildingMarker(g_Player1, t_Player_Buildings.tau_name[i], t_Player_Buildings.tau_building_blueprint[i], t_Player_Buildings.tau_marker_spawn[i], 1)
		Util_CreateSquadsAtMarkerEx(g_Player1, t_Player_Builder_Units.tau_buildername[i], t_Player_Builder_Units.tau_builder_blueprint[i], t_Player_Builder_Units.tau_buildermarker_spawn[i], 1, 1)
		
	end
	
elseif MetaMap_GetPlayerRaceName() == "necron_race" then
	
	for i = 1, table.getn(t_Player_Buildings.necron_name) do
		
		Entity_CreateBuildingMarker(g_Player1, t_Player_Buildings.tau_name[i], t_Player_Buildings.necron_building_blueprint[i], t_Player_Buildings.necron_marker_spawn[i], 1)
		Util_CreateSquadsAtMarkerEx(g_Player1, t_Player_Builder_Units.necron_buildername[i], t_Player_Builder_Units.necron_builder_blueprint[i], t_Player_Builder_Units.necron_buildermarker_spawn[i], 1, 1)
		
	end
	
end



--[[Add bonus buildings]]
--establish variables to be used to incrementally create turrets and generators by concantenating the variables onto the markers as needed
-- generator markers start at 0
g_bonus_gen_counter = 0
-- turrer markers start at 6
g_bonus_turret_counter = 6

--determine race specific blueprints to be looked for when creating forward base
if MetaMap_GetPlayerRaceName() == "chaos_marine_race" then
	
	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"
	
elseif MetaMap_GetPlayerRaceName() == "eldar_race" then
	
	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"
	
elseif MetaMap_GetPlayerRaceName() == "guard_race" then
	
	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"
	
elseif MetaMap_GetPlayerRaceName() == "ork_race" then
	
	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"
	
elseif MetaMap_GetPlayerRaceName() == "space_marine_race" then
	
	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"
	
elseif MetaMap_GetPlayerRaceName() == "tau_race" then
	
	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 algorithym 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"
	
elseif MetaMap_GetPlayerRaceName() == "necron_race" then
	
	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"
	
end

--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
		
		Entity_CreateBuildingMarker(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
		
		Entity_CreateBuildingMarker(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
		
		--fixed marker spawn based on Phil's table.  Only one barracks is spawned, always at marker 10
		--Necron intentionally spawn a summoning core in place of a barracks due to the monolith doubling as their barracks.
		Entity_CreateBuildingMarker(g_Player1, "eg_Bonus"..j, t_blueprintEntitybonus[j], "MM_Reinforcement10", 1)
		
	elseif t_blueprintEntitybonus[j] == g_bonus_research then
		
		--fixed marker spawn based on Phil's table.  Only one research building is spawned, always at marker 11
		Entity_CreateBuildingMarker(g_Player1, "eg_Bonus"..j, t_blueprintEntitybonus[j], "MM_Reinforcement11", 1)
		
	elseif t_blueprintEntitybonus[j] == g_bonus_barracks2 then
		
		--This will only be used to spawn the kroot nest when the player is Tau, otherwise it will be passed over due to g_bonus_barracks2 being a dummy value.
		--fixed marker spawn based on Phil's table.  Only one kroot nest is spawned, always at marker 13
		Entity_CreateBuildingMarker(g_Player1, "eg_Bonus"..j, t_blueprintEntitybonus[j], "MM_Reinforcement13", 1)
		
	end
	
end


Rule_Remove(Rule_Create_Player_Buildings)

end

--Turret upgrades function Rule_Upgrade_IG_Turrets()

--doing manual upgrades instead of for loops because for loops not working properly.
EGroup_ForceAddOn("eg_IG_Bridge_RocketTurrets1", "addon_guard_turret")
EGroup_ForceAddOn("eg_IG_Bridge_RocketTurrets2", "addon_guard_turret")
EGroup_ForceAddOn("eg_IG_Bridge_RocketTurrets3", "addon_guard_turret")
EGroup_ForceAddOn("eg_IG_Bridge_RocketTurrets4", "addon_guard_turret")

EGroup_ForceAddOn("eg_IG_Island_BolterTurrets1", "addon_guard_turret")
EGroup_ForceAddOn("eg_IG_Island_BolterTurrets2", "addon_guard_turret")

EGroup_ForceAddOn("eg_IG_FB_BolterTurrets6", "addon_guard_turret")

end

function Rule_Upgrade_Slagbase_Turrets()

EGroup_ForceAddOn("eg_Slagbase_BolterTurret3", "addon_guard_turret")
EGroup_ForceAddOn("eg_Slagbase_BolterTurret9", "addon_guard_turret")

end

function Rule_Upgrade_HQ_Turrets()

EGroup_ForceAddOn("eg_IG_HQ_BolterTurrets1", "addon_guard_turret")
EGroup_ForceAddOn("eg_IG_HQ_BolterTurrets4", "addon_guard_turret")
EGroup_ForceAddOn("eg_IG_HQ_BolterTurrets5", "addon_guard_turret")
EGroup_ForceAddOn("eg_IG_HQ_BolterTurrets8", "addon_guard_turret")

end

--listening posts upgrades function Rule_Upgrade_IG_List_Posts()

for i = 1,9 do
	
	EGroup_ForceAddOn("eg_HQ_List_Post"..i, "addon_guard_list_post_2")
	
end

end


--[[Spawning Armies]]

--[[Create IG Units]] function Rule_Create_Heavy_Weapons_Squads()

for i = 1,19 do
	
	Util_CreateSquadsAtMarker(g_Player2, "sg_Heavy_WeaponsSG"..i, "guard_heavy_weapons_team_squad", "mkr_Heavy_Weapons"..i, 1)
	
	Cpu_LockSGroupAcrossPlayers("sg_Heavy_WeaponsSG"..i)
	
	Cmd_SetStance("sg_Heavy_WeaponsSG"..i, STANCE_StandGround)
	
end

--Set facings before entrenching (entrenched untis seem not to respond to facing commands)
SGroup_FaceMarker("sg_Heavy_WeaponsSG1", "mkr_List_Post9")
SGroup_FaceMarker("sg_Heavy_WeaponsSG3", "mkr_List_Post9")

SGroup_FaceMarker("sg_Heavy_WeaponsSG4", "mkr_Artillery_Trigger6")
SGroup_FaceMarker("sg_Heavy_WeaponsSG5", "mkr_Artillery_Trigger6")

SGroup_FaceMarker("sg_Heavy_WeaponsSG8", "mkr_BridgeHead_North3")

SGroup_FaceMarker("sg_Heavy_WeaponsSG9", "mkr_HQ_Door1")
SGroup_FaceMarker("sg_Heavy_WeaponsSG10", "mkr_HQ_Door1")

SGroup_FaceMarker("sg_Heavy_WeaponsSG13", "mkr_BridgeHead_North1")
SGroup_FaceMarker("sg_Heavy_WeaponsSG14", "mkr_BridgeHead_North1")


--[[When calling the entrench command, the Sgroups that the hvy wpns groups belonged to are lost.]]
--[[To properly upgrade them, 2 things must happen:]]
--[[1) Each unit must be regrouped to be referenced for upgrades]]
--[[2) A delay between the entrench command and the regrouping and upgrade commands are needed to account for the deployment animation time]]

--do entrench command
for k = 1,19 do
	
	Cmd_SquadEntrench("sg_Heavy_WeaponsSG"..k)
	
end

--delayed 2nd step
Rule_AddOneShot( Rule_Upgrade_Heavy_Weapons_Squad, 10)

end

function Rule_Upgrade_Heavy_Weapons_Squad()

--regroup all units
for k = 1,19 do
	
	Player_GetAllSquadsNearMarker(g_Player2, "sg_Hvy_Wpns_Entrenched"..k, "mkr_Heavy_Weapons"..k)
	
	Cpu_LockSGroupAcrossPlayers("sg_Hvy_Wpns_Entrenched"..k)
	
	Cmd_SetStance("sg_Hvy_Wpns_Entrenched"..k, STANCE_StandGround)
	
end

--do upgrades after entrenched
--slag base in the center area
if SGroup_Exists("sg_Hvy_Wpns_Entrenched2") and SGroup_IsEmpty("sg_Hvy_Wpns_Entrenched2") == false then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Hvy_Wpns_Entrenched2"), 1),"guard_autocannon_heavy_weapons_team",1)
end

--slagbase upper level squad (near "shipping" area)
if SGroup_Exists("sg_Hvy_Wpns_Entrenched8") and SGroup_IsEmpty("sg_Hvy_Wpns_Entrenched8") == false then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Hvy_Wpns_Entrenched8"), 1),"guard_autocannon_heavy_weapons_team",1)
end

--stronghold HQ squads
if SGroup_Exists("sg_Hvy_Wpns_Entrenched9") and SGroup_IsEmpty("sg_Hvy_Wpns_Entrenched9") == false then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Hvy_Wpns_Entrenched9"), 1),"guard_autocannon_heavy_weapons_team",1)
end
if SGroup_Exists("sg_Hvy_Wpns_Entrenched10") and SGroup_IsEmpty("sg_Hvy_Wpns_Entrenched10") == false then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Hvy_Wpns_Entrenched10"), 1),"guard_lasgun_heavy_weapons_team",1)
end

--bridge HQ squads
if SGroup_Exists("sg_Hvy_Wpns_Entrenched13") and SGroup_IsEmpty("sg_Hvy_Wpns_Entrenched13") == false then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Hvy_Wpns_Entrenched13"), 1),"guard_autocannon_heavy_weapons_team",1)
end
if SGroup_Exists("sg_Hvy_Wpns_Entrenched14") and SGroup_IsEmpty("sg_Hvy_Wpns_Entrenched14") == false then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Hvy_Wpns_Entrenched14"), 1),"guard_lasgun_heavy_weapons_team",1)
end

--Mars pattern near stronghold
if SGroup_Exists("sg_Hvy_Wpns_Entrenched15") and SGroup_IsEmpty("sg_Hvy_Wpns_Entrenched15") == false then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Hvy_Wpns_Entrenched15"), 1),"guard_lasgun_heavy_weapons_team",1)
end

--rear bridge squads
if SGroup_Exists("sg_Hvy_Wpns_Entrenched17") and SGroup_IsEmpty("sg_Hvy_Wpns_Entrenched17") == false then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Hvy_Wpns_Entrenched17"), 1),"guard_lasgun_heavy_weapons_team",1)
end
if SGroup_Exists("sg_Hvy_Wpns_Entrenched18") and SGroup_IsEmpty("sg_Hvy_Wpns_Entrenched18") == false then
	Squad_ForceUpgradeWeapons(SGroup_GetSpawnedSquadAt(SGroup_FromName("sg_Hvy_Wpns_Entrenched18"), 1),"guard_lasgun_heavy_weapons_team",1)
end

Rule_AddOneShot(Rule_Destroy_Heavy_Weapons_Squad, 3)

end

function Rule_Destroy_Heavy_Weapons_Squad()

--systematically remove heavy weapon squads based of the province military strength

if g_DIFF == 10 then
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched1")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched1")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched2")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched2")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched8")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched8")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched9")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched9")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched11")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched11")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched12")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched12")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched15")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched15")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched16")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched16")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched17")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched17")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched18")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched18")
	
elseif g_DIFF == 11 or g_DIFF == 12 then
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched1")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched1")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched2")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched2")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched9")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched9")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched11")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched11")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched15")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched15")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched18")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched18")
	
	
elseif g_DIFF == 13 or g_DIFF == 14 then
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched2")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched2")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched11")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched11")
	
	SGroup_DeSpawn("sg_Hvy_Wpns_Entrenched18")
	SGroup_Destroy("sg_Hvy_Wpns_Entrenched18")
	
end

end

function Rule_Create_Island_Units()

--create island artillery - unlimited range unit type
for i = 1,10 do
	
	Util_CreateSquadsAtMarker(g_Player2, "sg_NPC_Island_ArtillerySG"..i, "guard_squad_basilisk_stronghold_sp", "mkr_NPC_Artillery"..i,1)
	
	Cmd_SetStance("sg_NPC_Island_ArtillerySG"..i, STANCE_StandGround)
	
	Cpu_LockSGroupAcrossPlayers("sg_NPC_Island_ArtillerySG"..i)
	
	SGroup_AddGroup(SGroup_CreateIfNotFound("sg_NPC_Island_Artillery"),  SGroup_FromName("sg_NPC_Island_ArtillerySG"..i))
	
	SGroup_CreateIfNotFound("sg_Artillery_objective1")
	SGroup_CreateIfNotFound("sg_Artillery_objective2")
	
	if i <= 5 then
		
		SGroup_AddGroup("sg_Artillery_objective1", "sg_NPC_Island_ArtillerySG"..i)
		
	elseif i > 5 then
		
		SGroup_AddGroup("sg_Artillery_objective2", "sg_NPC_Island_ArtillerySG"..i)
		
	end
	
end

Cpu_LockSGroupAcrossPlayers("sg_NPC_Island_Artillery")

--face artillery marker
SGroup_FaceMarker("sg_NPC_Island_Artillery","mkr_Heavy_Weapons4")

if Rule_Exists(Rule_Bridge_Area_Check) == false then
	
	Rule_AddIntervalDelay(Rule_Bridge_Area_Check,1,10)
	
end

end

function Rule_Create_River_Guardsmen()

--each spawn has a different loadout
JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_River_Guardsmen1", "mkr_river_guardsmen1", 8, 0, 0, true, STANCE_Hold, false)

Cpu_LockSGroupAcrossPlayers("sg_River_Guardsmen1")


JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_River_Guardsmen2", "mkr_river_guardsmen2", 8, 4, 0, true, STANCE_Hold, false)

Cpu_LockSGroupAcrossPlayers("sg_River_Guardsmen2")


Util_CreateSquadsAtMarker(g_Player2, "sg_River_Guardsmen3", "guard_heavy_weapons_team_squad", "mkr_river_guardsmen3", 1)

Cpu_LockSGroupAcrossPlayers("sg_River_Guardsmen3")

Cmd_SetStance("sg_River_Guardsmen3", STANCE_StandGround)

Rule_AddOneShot(Rule_Entrench_River_HvyWpns, 3)

--face the entrance to the shallows.
for i = 1,3 do
	
	SGroup_FaceMarker("sg_River_Guardsmen"..i, "mkr_river_south")
	
end

end

function Rule_Entrench_River_HvyWpns()

Cmd_SquadEntrench("sg_River_Guardsmen3")

Rule_AddOneShot(Rule_Lock_River_HvyWpns, 3)

end

function Rule_Lock_River_HvyWpns()

Player_GetAllSquadsNearMarker(g_Player2, "sg_River_HvyWpns_Entrenched", "mkr_river_guardsmen3")

Cpu_LockSGroupAcrossPlayers("sg_River_HvyWpns_Entrenched")

Cmd_SetStance("sg_River_HvyWpns_Entrenched", STANCE_StandGround)

end

function Rule_Create_Mech_Base_Units()

Util_CreateSquadsAtMarker(g_Player2, "sg_Mech_Base_BaneBlade", "guard_squad_baneblade", "mkr_Armor_Base_Baneblade", 1)

Cpu_LockSGroupAcrossPlayers("sg_Mech_Base_BaneBlade")

for i = 1,3 do
	
	local randSS = World_GetRand(6,8)
	local randplasma = World_GetRand(2,4)
	local randgrenade = 0 --World_GetRand(1,2)
	
	JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Mechbase_infantry"..i, "mkr_Armor_Base", randSS, randplasma, randgrenade, true, STANCE_Attack, false)
	SGroup_AddGroup(SGroup_CreateIfNotFound("sg_Mechbase_defenders"), "sg_Mechbase_infantry"..i)
	SGroup_AddLeaders("sg_Mechbase_infantry"..i)
	
	JMUtil_Random_Leader_Spawn(g_Player2, "sg_Mechbase_infantry"..i, "mkr_Armor_Base", "sg_Mechbase_infantry_leader"..i, true)
	
end

--[[
--create garrisoning units
for i = 1,3 do
	
	local randSS = World_GetRand(2,6)
	
	Util_CreateSquadsAtMarkerEx(g_Player2, "sg_MechBase_Garrison"..i, "guard_squad_guardsmen", "mkr_Mech_Garrison_Spawn", randSS, 1)
	
	Cpu_LockSGroupAcrossPlayers("sg_MechBase_Garrison"..i)
	
	--adjust to account for the mech shops
	if i == 1 then
		
		eg = "eg_Airstrike_HQ"
		
	elseif i == 2 then
		
		eg = "eg_HQ_List_Post6"
		
	elseif i == 3 then
		
		eg = "eg_Mechbase_barracks"
		
	end
	
	--load created units into corresponding buildings.
	Cmd_EnterBuilding("sg_MechBase_Garrison"..i, eg)
	
end]]

end

function Rule_Create_Bridge_Units()

--create initial chimeras on the bridge
for i = 1,2 do
	
	Util_CreateSquadsAtMarker(g_Player2,"sg_Bridge_Chimera","guard_squad_chimera","mkr_Bridge_Chimera"..i,1)
	
end

Cpu_LockSGroupAcrossPlayers("sg_Bridge_Chimera")

SGroup_FaceMarker("sg_Bridge_Chimera","mkr_BridgeHead_South")


--create initial bridge infantry
Util_CreateSquadsAtMarkerEx(g_Player2,"sg_Bridge_Infantry1","guard_squad_ogryns","mkr_Bridge_Spawn1",1,6)
--JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Bridge_Infantry1", "mkr_Bridge_Spawn1", 8, 4, 1, true, STANCE_Attack, false)
SGroup_AddLeaders("sg_Bridge_Infantry1")
Cpu_LockSGroupAcrossPlayers("sg_Bridge_Infantry1")

--JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Bridge_Infantry2", "mkr_Bridge_Spawn2", 8, 4, 1, true, STANCE_Attack, false)
JMUtil_Spawn_Upgraded_Kasrkin(g_Player2, "sg_Bridge_Infantry2", "mkr_Bridge_Spawn2", 8, 4, 1, true, STANCE_Attack, false)
SGroup_AddLeaders("sg_Bridge_Infantry2")
Cpu_LockSGroupAcrossPlayers("sg_Bridge_Infantry2")

-- move squads up
for i = 1,2 do
	
	Cmd_AttackMoveMarker("sg_Bridge_Infantry"..i,"mkr_Bridge_DefensePoint"..i)
	
end

--create initial armor on the north end of the bridge
Util_CreateSquadsAtMarker(g_Player2,"sg_NorthBridge_defense","guard_squad_sentinel","mkr_Bridge_defender1",1)
Util_CreateSquadsAtMarker(g_Player2,"sg_NorthBridge_defense","guard_squad_sentinel","mkr_Bridge_defender4",1)
Util_CreateSquadsAtMarker(g_Player2,"sg_NorthBridge_defense","guard_squad_hellhound","mkr_Bridge_defender2",1)
Util_CreateSquadsAtMarker(g_Player2,"sg_NorthBridge_defense","guard_squad_lemanruss","mkr_Bridge_defender3",1)

Cmd_SetStance("sg_NorthBridge_defense", STANCE_Hold)

Cpu_LockSGroupAcrossPlayers("sg_NorthBridge_defense")

SGroup_FaceMarker("sg_Bridge_Chimera","mkr_BridgeHead_South")

end

function Rule_Create_Slagbase_Units()

--create initial guardsmen SlagBase
for i = 1,3 do
	
	local randSS = World_GetRand(6,8)
	local randplasma = World_GetRand(2,3)
	local randgrenade = World_GetRand(1,2)
	
	JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_SlagBase_Defenders"..i, "mkr_SlagBase_Roof_Defense"..i, randSS, randplasma, randgrenade, true, STANCE_Hold, false)
	
	if i == 2 then
		
		Cmd_SetMeleeStance("sg_SlagBase_Defenders"..i, MSTANCE_Assault)
		
	end
	
end

--add patrol for guardsmen
Rule_AddInterval(Rule_Slagbase_static_patrol, 15)


--create garrisoning units
for i = 1,11 do
	
	local randSS = World_GetRand(2,8)
	local randplasma = World_GetRand(0,4)
	local randgrenade = World_GetRand(0,2)
	local randspawn = World_GetRand(1,2)
	
	for k = 1,randspawn do
		
		JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_SlagBase_Garrison"..i, "mkr_Slag_Garrison_Spawn"..i, randSS, randplasma, randgrenade, true, STANCE_Hold, false)
		
	end
	
	--Util_CreateSquadsAtMarkerEx(g_Player2, "sg_SlagBase_Garrison"..i, "guard_squad_guardsmen", "mkr_Slag_Garrison_Spawn"..i, randspawn, randSS)
	
	Cpu_LockSGroupAcrossPlayers("sg_SlagBase_Garrison"..i)
	
	--adjust to account for the mech shops
	if i <= 5 then
		
		k = i
		
		eg = "eg_SlagBase_Barracks"..k
		
	else
		
		k = i - 5
		
		eg = "eg_Slagbase_Mech"..k
		
	end
	
	--make sure all the require parts are in play.
	if EGroup_Exists(eg) and EGroup_IsEmpty(eg) == false and SGroup_Exists("sg_SlagBase_Garrison"..i) and SGroup_IsEmpty("sg_SlagBase_Garrison"..i) == false then
		--load created units into corresponding buildings.
		Cmd_EnterBuilding("sg_SlagBase_Garrison"..i, eg)
	end
	
end	

end

function Rule_Create_Rebel_Units()

--create Commissar at rebel base
Util_CreateSquadsAtMarker(g_Player3,"sg_Rebel_Commissar","guard_squad_commissar_advance_sp","mkr_Commissar",1)
Cpu_LockSGroupAcrossPlayers("sg_Rebel_Commissar")

Util_CreateSquadsAtMarker(g_Player3,"sg_Rebel_Commissar_Ogryn","guard_squad_ogryns_advance_sp","mkr_Commissar",1)
Cpu_LockSGroupAcrossPlayers("sg_Rebel_Commissar_Ogryn")

Cmd_AttachSquads("sg_Rebel_Commissar_Ogryn", "sg_Rebel_Commissar")

--create rebel forces
local rand = World_GetRand(7,9)
JMUtil_Spawn_Upgraded_Guardmen(g_Player3, "sg_Rebels1", "mkr_Rebel_Spawn", rand, 5, 2, true, STANCE_Hold, false)
SGroup_AddGroup(SGroup_CreateIfNotFound("sg_All_Rebel_Units"),"sg_Rebels1")

JMUtil_Spawn_Upgraded_Guardmen(g_Player3, "sg_Rebels2", "mkr_Rebel_Door1", rand, 5, 2, true, STANCE_Hold, false)
SGroup_AddGroup(SGroup_CreateIfNotFound("sg_All_Rebel_Units"),"sg_Rebels2")

JMUtil_Spawn_Upgraded_Kasrkin(g_Player3, "sg_Rebels3", "mkr_Rebel_Lookout4", rand, 5, 2, true, STANCE_Hold, false)
SGroup_AddGroup(SGroup_CreateIfNotFound("sg_All_Rebel_Units"),"sg_Rebels3")

for k = 1,2 do
	
	Util_CreateSquadsAtMarker(g_Player3,"sg_Rebels4","guard_squad_sentinel","mkr_Rebel_Lookout"..k,1)
	
end

Util_CreateSquadsAtMarker(g_Player3, "sg_Rebels5", "guard_squad_hellhound", "mkr_Rebel_Lookout3", 1)
SGroup_AddGroup(SGroup_CreateIfNotFound("sg_All_Rebel_Units"),"sg_Rebels5")

Cmd_SetStance("sg_Rebels4", STANCE_StandGround)	
Cpu_LockSGroupAcrossPlayers("sg_Rebels4")
Cpu_LockSGroupAcrossPlayers("sg_All_Rebel_Units")

SGroup_AddGroup(SGroup_CreateIfNotFound("sg_All_Rebel_Units"),"sg_Rebels4")
SGroup_FaceMarker("sg_Rebels4", "mkr_Rebel_Base_Main_Entrance")

end

function Rule_Create_HQ_Units()

--create HQ Leman Russ'
for i = 1,4 do
	
	Util_CreateSquadsAtMarker(g_Player2,"sg_HQ_LemanRuss"..i,"guard_squad_lemanruss","mkr_HQ_LemanRuss"..i,1)
	
	--leman #3 and 4, the ones on the stronghold tiers will not move from their position.
	if i > 2 then
		
		Cmd_SetStance("sg_HQ_LemanRuss"..i, STANCE_StandGround)
		
	end
	
	SGroup_AddGroup(SGroup_CreateIfNotFound("sg_HQ_LemanRuss"), "sg_HQ_LemanRuss"..i)
	SGroup_AddGroup(SGroup_CreateIfNotFound("sg_HQ_Outro_NIS_Delete"), "sg_HQ_LemanRuss"..i)
	
	SGroup_Clear("sg_HQ_LemanRuss"..i)
	
end

Cpu_LockSGroupAcrossPlayers("sg_HQ_LemanRuss")

--face forward
SGroup_FaceMarker("sg_HQ_LemanRuss", "mkr_Stronghold_Detect2")

--create artillery
for i = 1,2 do
	
	Util_CreateSquadsAtMarker(g_Player2,"sg_HQ_Artillery","guard_squad_basilisk","mkr_HQ_Artillery"..i,1)
	SGroup_AddGroup(SGroup_CreateIfNotFound("sg_HQ_Outro_NIS_Delete"), "sg_HQ_Artillery")
	
end

--face forward
SGroup_FaceMarker("sg_HQ_Artillery", "mkr_Stronghold_Detect2")

Cpu_LockSGroupAcrossPlayers("sg_HQ_Artillery")

Cmd_SetStance("sg_HQ_Artillery", STANCE_StandGround)

--create HQ Hellhounds
for i = 1,2 do
	
	Util_CreateSquadsAtMarker(g_Player2,"sg_HQ_Hellhounds","guard_squad_hellhound","mkr_HQ_Hellhound"..i,1)
	SGroup_AddGroup(SGroup_CreateIfNotFound("sg_HQ_Outro_NIS_Delete"), "sg_HQ_Hellhounds")
	
end

Cpu_LockSGroupAcrossPlayers("sg_HQ_Hellhounds")

--face forward
SGroup_FaceMarker("sg_HQ_Hellhounds", "mkr_Stronghold_Detect2")


--create HQ Baneblade
--Util_CreateSquadsAtMarker(g_Player2,"sg_HQ_BaneBlade","guard_squad_baneblade","mkr_HQ_Mars_Spawn",1)
--Cpu_LockSGroupAcrossPlayers("sg_HQ_BaneBlade")
--Cmd_SetStance("sg_HQ_BaneBlade", STANCE_Attack)

--create HQ Elite Guard (replaced kasrkin - too many on the field)
for i = 1,2 do
	
	Util_CreateSquadsAtMarkerEx(g_Player2,"sg_HQ_Guardsmen_Elite","guard_squad_guardsmen_advance_sp","mkr_HQ_Kasrkin"..i,1,8)
	SGroup_AddGroup(SGroup_CreateIfNotFound("sg_HQ_Outro_NIS_Delete"), "sg_HQ_Guardsmen_Elite")
	
end	

Cpu_LockSGroupAcrossPlayers("sg_HQ_Guardsmen_Elite")

--create HQ guardsmen
for i = 1,3 do
	
	JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_HQ_Guardsmen", "mkr_HQ_guardsmen"..i, 8, 4, 2, true, STANCE_Attack, false)
	SGroup_AddGroup(SGroup_CreateIfNotFound("sg_HQ_Outro_NIS_Delete"), "sg_HQ_Guardsmen")
	
end	

Cpu_LockSGroupAcrossPlayers("sg_HQ_Guardsmen")

end

function Rule_Create_Gen_Defenders()

--create 'honor guard' guardsmen
JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Titan_Gen_Defenders", "mkr_Gen_Defender2", 8, 4, 2, true, STANCE_Hold, true)
JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Titan_Gen_Defenders", "mkr_Gen_Defender3", 8, 4, 2, true, STANCE_Hold, true)
JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Titan_Gen_Defenders", "mkr_Gen_Defender4", 8, 4, 2, true, STANCE_Hold, true)
JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_Titan_Gen_Defenders", "mkr_Gen_Defender5", 8, 4, 2, true, STANCE_Hold, true)

--create elite leman russ
Util_CreateSquadsAtMarker(g_Player2, "sg_Titan_Gen_Defenders", "guard_squad_lemanruss_advance_sp", "mkr_Gen_Defender1", 1)
Util_CreateSquadsAtMarker(g_Player2, "sg_Titan_Gen_Defenders", "guard_squad_lemanruss_advance_sp", "mkr_Gen_Defender6", 1)

Cmd_SetStance("sg_Titan_Gen_Defenders", STANCE_Hold)
Cpu_LockSGroupAcrossPlayers("sg_Titan_Gen_Defenders")

end

--optimizing check for Rule_FB_Spawn_Infantry1 & 2 function Rule_FB_Spawn_Infantry_Check()

if g_init_FB == false then
	
	SGroup_Create("sg_FB_Infantry1")
	SGroup_Create("sg_FB_Infantry2")
	g_init_FB = true
	
end

if SGroup_Exists("sg_FB_Infantry1") == false or SGroup_Exists("sg_FB_Infantry1") and SGroup_IsEmpty("sg_FB_Infantry1") then
	
	Rule_AddOneShot(Rule_FB_Spawn_Infantry1,1)
	
end

if SGroup_Exists("sg_FB_Infantry2") == false or SGroup_Exists("sg_FB_Infantry2") and SGroup_IsEmpty("sg_FB_Infantry2") then
	
	Rule_AddOneShot(Rule_FB_Spawn_Infantry2,10)
	
end

if EGroup_IsEmpty("eg_IG_FB_Barracks1") and EGroup_IsEmpty("eg_IG_FB_Barracks2") then
	
	Rule_Remove(Rule_FB_Spawn_Infantry_Check)
	
end

end

--Forward Base infantry spawning function Rule_FB_Spawn_Infantry1()

if EGroup_IsEmpty("eg_IG_FB_Barracks1") == false then
	
	for i = 1,2 do
		
		JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_FB_InfantrySG"..i, "mkr_NPC_FB_Spawn1", 8, 5, 2, true, STANCE_StandGround, false)
		SGroup_AddLeaders("sg_FB_InfantrySG"..i)
		SGroup_AddGroup(SGroup_CreateIfNotFound("sg_FB_Infantry1"),  SGroup_FromName("sg_FB_InfantrySG"..i))
		
	end
	
	Cpu_LockSGroupAcrossPlayers("sg_FB_Infantry1")
	Cmd_AttackMoveMarker("sg_FB_Infantry1","mkr_FB_DefensePoint1")
	
end

if Rule_Exists(Rule_FB_Infantry_Mover) == false then
	
	Rule_AddIntervalDelay(Rule_FB_Infantry_Mover, 10, 10)
	
end

end

function Rule_FB_Infantry_Mover()

for i = 1,2 do
	
	if SGroup_Exists("sg_FB_InfantrySG"..i) and SGroup_CountSpawned("sg_FB_InfantrySG"..i) > 0 then
		
		Util_AttackMoveMarkerRandomRadius("sg_FB_InfantrySG"..i, "mkr_FB_DefensePoint"..i)
		
	elseif EGroup_IsEmpty("eg_IG_FB_Barracks1") then
		
		Rule_Remove(Rule_FB_Infantry_Mover)
		
	end
	
end

end

function Rule_FB_Spawn_Infantry2()

if EGroup_IsEmpty("eg_IG_FB_Barracks2") == false then
	
	for i = 1,2 do
		
		JMUtil_Spawn_Upgraded_Guardmen(g_Player2, "sg_FB_InfantrySG"..i+2, "mkr_NPC_FB_Spawn2", 8, 6, 2, true, STANCE_StandGround, false)
		SGroup_AddGroup(SGroup_CreateIfNotFound("sg_FB_Infantry2"),  SGroup_FromName("sg_FB_InfantrySG"..i+2))
		
	end
	
	if SGroup_Exists("sg_FB_InfantrySG3_Leader") == false or SGroup_Exists("sg_FB_InfantrySG3_Leader") and SGroup_IsEmpty("sg_FB_InfantrySG3_Leader") then
		
		JMUtil_Random_Leader_Spawn(g_Player2, "sg_FB_InfantrySG3", "mkr_NPC_FB_Spawn2", "sg_FB_InfantrySG3_Leader", true)
		
	elseif SGroup_Exists("sg_FB_InfantrySG3_Leader") and SGroup_IsEmpty("sg_FB_InfantrySG3_Leader") == false then
		
		SGroup_AddGroup("sg_FB_InfantrySG3", "sg_FB_InfantrySG3_Leader")
		
	end
	
	Cpu_LockSGroupAcrossPlayers("sg_FB_Infantry2")
	Cmd_AttackMoveMarker("sg_FB_Infantry2","mkr_FB_DefensePoint3")
	
end

end

function Rule_Create_Player_Units()

--setting up the bonus units for the player
t_blueprintbonus = {}
MetaMap_GetRaceStartingSquadsList(MetaMap_GetPlayerRaceName(), t_blueprintbonus)

for j = 1,  table.getn(t_blueprintbonus) do
		
	k = math.mod(j - 1, 6) + 1
	
	Util_CreateSquadsAtMarker(g_Player1, "sg_Bonus"..j, t_blueprintbonus[j], "mkr_Bonus"..k, 1)
	
	
end

--setting up the upgrades for the commander
MetaMap_UpdatePlayerWargear(g_Player1)

end


--[[ OBJECTIVES ]]

--[[Primary Objective - destroy the IG Stronghold]] function Rule_Objective_Conquer_Stronghold()

Objective_Conquer_Stronghold = {title_id = 2620000, short_desc_id = 2620001, help_tip_id = 2620000}

if Event_IsAnyRunning() == false and Objective_Exists(Objective_Conquer_Stronghold.title_id) == false then
	
	Util_WXP_ObjectiveCreate(Objective_Conquer_Stronghold, true, g_Player1)
	
	Objective_ShowScreen()
	Flash_OtherButton("dlg_objectives", 0, false, true)
	
	--[[adding map and mini-map pings]]
	g_ping_hq = Objective_PingMarker(Objective_Conquer_Stronghold.title_id, "mkr_NPC_HQ", true, "default")
	g_ping_hq_mini = Ping_Marker("mkr_NPC_HQ", true, "default")
	
	Rule_AddOneShot(Rule_Stop_Conquer_Stronghold_Ping, 5)
	
elseif Event_IsAnyRunning() == false and g_Win == true then 

	--[[removing map and mini-map pings]]
	Objective_PingRemove(Objective_Conquer_Stronghold.title_id, g_ping_hq)
	
	Util_ObjectiveComplete(Objective_Conquer_Stronghold.title_id)
	Rule_Remove(Rule_Objective_Conquer_Stronghold)
	
end

end

function Rule_Stronghold_Conquered()

--[[game is won]]
Fade_Start(0, false)
World_SetTeamWin( g_Player1, "" )
Rule_AddOneShot( Rule_GameOver, 1)

end

function Rule_Stop_Conquer_Stronghold_Ping()

Ping_Stop(g_ping_hq_mini)

end

-- used to establish individual pings for each of the 10 thermo plasma generators. t_Artillery_Pings = {

	geo_pings = {	g_ping_Artillery1, g_ping_Artillery2},
	
	mini_map_pings = {g_ping_Artillery_mini1, g_ping_Artillery_mini2}
	
}

--[[Secondary Objective - destroy the artillery battery]] function Rule_Objective_Destroy_Artillery()

Objective_Destroy_Artillery = {title_id = 2620010, short_desc_id = 2620011, help_tip_id = 2620010}

if Event_IsAnyRunning() == false and Objective_Exists(Objective_Destroy_Artillery.title_id) == false then
	
	Util_WXP_ObjectiveCreate(Objective_Destroy_Artillery, false, g_Player1)
	
	Objective_ShowScreen()
	Flash_OtherButton("dlg_objectives", 0, false, true)
	
	--[[adding map and mini-map pings]]
	for i = 1,2 do
		
		t_Artillery_Pings.geo_pings[i] = Objective_PingMarker(Objective_Destroy_Artillery.title_id, "mkr_Artillery_Objective"..i, true, "default")
		t_Artillery_Pings.mini_map_pings[i] = Ping_Marker("mkr_Artillery_Objective"..i, true, "default")
		
	end
	
	Rule_AddOneShot(Rule_Stop_Destroy_Artillery_Ping, 5)
	
elseif Event_IsAnyRunning() == false and Objective_Exists(Objective_Destroy_Artillery.title_id) then 
	
	--[[removing map and mini-map pings]]
	if g_Artillery_pings_removed == false then
		
		for j = 1,2 do
			
			if SGroup_Exists("sg_Artillery_objective"..j) == false or SGroup_Exists("sg_Artillery_objective"..j) and SGroup_IsEmpty("sg_Artillery_objective"..j) then
				
				Objective_PingRemove(Objective_Destroy_Artillery.title_id, t_Artillery_Pings.geo_pings[j])
				
			end
			
			g_Artillery_pings_removed = true
			
		end
		
	end
	
	if g_Artillery_Destroyed == true then
		
		Util_ObjectiveComplete(Objective_Destroy_Artillery.title_id)
		Rule_Remove(Rule_Objective_Destroy_Artillery)
		
	end
	
end

end

function Rule_Stop_Destroy_Artillery_Ping()

for i = 1,2 do
	
	Ping_Stop(t_Artillery_Pings.mini_map_pings[i])
	
end

end

--[[Secondary Objective - Kill the rebel officer]] function Rule_Objective_Kill_Rebel_Officer()

Objective_Kill_Rebel_Officer = {title_id = 2620030, short_desc_id = 2620031, help_tip_id = 2620030}

if Event_IsAnyRunning() == false and Objective_Exists(Objective_Kill_Rebel_Officer.title_id) == false then
	
	Util_WXP_ObjectiveCreate(Objective_Kill_Rebel_Officer, false, g_Player1)
	
	Objective_ShowScreen()
	Flash_OtherButton("dlg_objectives", 0, false, true)
	
	FOW_RevealSGroup("sg_Rebel_Commissar", 6)
	
	--[[adding map and mini-map pings]]
	g_ping_rebels = Objective_PingPosition(Objective_Kill_Rebel_Officer.title_id, SGroup_GetPosition("sg_Rebel_Commissar"), true, "default")
	g_ping_rebels_mini = Ping_Marker("mkr_Commissar", true, "default")
	
	Rule_AddOneShot(Rule_Stop_Kill_Rebel_Officer_Ping, 5)
	
elseif Event_IsAnyRunning() == false and Objective_Exists(Objective_Kill_Rebel_Officer.title_id) and g_Commisar_Dead == true then 
	
	--[[removing map and mini-map pings]]
	Objective_PingRemove(Objective_Kill_Rebel_Officer.title_id, g_ping_rebels)
	
	Util_ObjectiveComplete(Objective_Kill_Rebel_Officer.title_id)
	Rule_Remove(Rule_Objective_Kill_Rebel_Officer)
	
end

end

function Rule_Stop_Kill_Rebel_Officer_Ping()

Ping_Stop(g_ping_rebels_mini)

end

--[[Secondary Objective - Destroy the forward base]] function Rule_Objective_Destroy_Forward_Base()

if EGroup_IsEmpty("eg_FB_Buildings") == true then
	
	g_FB_Destroyed = true
	
end

Objective_Destroy_Forward_Base = {title_id = 2620040, short_desc_id = 2620041, help_tip_id = 2620040}	

if Event_IsAnyRunning() == false and Objective_Exists(Objective_Destroy_Forward_Base.title_id) == false then
	
	Util_WXP_ObjectiveCreate(Objective_Destroy_Forward_Base, false, g_Player1)
	
	Objective_ShowScreen()
	Flash_OtherButton("dlg_objectives", 0, false, true)
	
	--[[adding map and mini-map pings]]
	g_ping_FB = Objective_PingMarker(Objective_Destroy_Forward_Base.title_id, "mkr_Forward_Base", true, "default")
	g_ping_FB_mini = Ping_Marker("mkr_Forward_Base", true, "default")
	
	Rule_AddOneShot(Rule_Stop_Destroy_Forward_Base, 5)
	
elseif Event_IsAnyRunning() == false and Objective_Exists(Objective_Destroy_Forward_Base.title_id) and g_FB_Destroyed == true then 
	
	--[[removing map and mini-map pings]]
	Objective_PingRemove(Objective_Destroy_Forward_Base.title_id, g_ping_FB)
	
	Util_ObjectiveComplete(Objective_Destroy_Forward_Base.title_id)
	Rule_Remove(Rule_Objective_Destroy_Forward_Base)
	
	--add step 2 research
	Rule_AddOneShot(Rule_Give_AI_Research_Step2, 60)
	
	--add infantry spawning from across the bridge.
	Rule_AddInterval(Rule_Bridge_Infantry_spawner, 180)
	
end

end

function Rule_Stop_Destroy_Forward_Base()

Ping_Stop(g_ping_FB_mini)

end

--[[Secondary Objective - Destroy the Armor Base]] function Rule_Objective_Destroy_Armor_Base()

if EGroup_IsEmpty("eg_AB_Buildings") == true then
	
	g_AB_Destroyed = true
	
end

Objective_Destroy_Armor_Base = {title_id = 2620050, short_desc_id = 2620051, help_tip_id = 2620050}	

if Event_IsAnyRunning() == false and Objective_Exists(Objective_Destroy_Armor_Base.title_id) == false then
	
	Util_WXP_ObjectiveCreate(Objective_Destroy_Armor_Base, false, g_Player1)
	
	Objective_ShowScreen()
	Flash_OtherButton("dlg_objectives", 0, false, true)
	
	--[[adding map and mini-map pings]]
	g_ping_AB = Objective_PingMarker(Objective_Destroy_Armor_Base.title_id, "mkr_Armor_Base", true, "default")
	g_ping_AB_mini = Ping_Marker("mkr_Armor_Base", true, "default")
	
	Rule_AddOneShot(Rule_Stop_Destroy_Armor_Base, 5)
	
elseif Event_IsAnyRunning() == false and Objective_Exists(Objective_Destroy_Armor_Base.title_id) and g_AB_Destroyed == true then 
	
	--[[removing map and mini-map pings]]
	Objective_PingRemove(Objective_Destroy_Armor_Base.title_id, g_ping_AB)
	
	Util_ObjectiveComplete(Objective_Destroy_Armor_Base.title_id)
	Rule_Remove(Rule_Objective_Destroy_Armor_Base)
	
end

end

function Rule_Stop_Destroy_Armor_Base()

Ping_Stop(g_ping_AB_mini)

end

--[[DEFUNCT --[[Secondary Objective - repair the abandoned artillery at the rebel base]] function Rule_Objective_Repair_Artillery()

Objective_Repair_Artillery = {title_id = 2620070, short_desc_id = 2620071, help_tip_id = 2620070}

if Event_IsAnyRunning() == false and Objective_Exists(Objective_Repair_Artillery.title_id) == false then
	
	Util_WXP_ObjectiveCreate(Objective_Repair_Artillery, false, g_Player1)
	
	--[[adding map and mini-map pings]]
	g_ping_repair_artillery = Objective_PingMarker(Objective_Repair_Artillery.title_id, "mkr_Freebie_Rebel_Unit2", true, "default")
	g_ping_repair_artillery_mini = Ping_Marker("mkr_Freebie_Rebel_Unit2", true, "default")
	
	Rule_AddOneShot(Rule_Stop_Repair_Artillery_Ping, 5)
	
elseif Event_IsAnyRunning() == false and Objective_Exists(Objective_Repair_Artillery.title_id) and g_Artillery_Repaired == true then 
	
	--[[removing map and mini-map pings]]
	Objective_PingRemove(Objective_Repair_Artillery.title_id, g_ping_repair_artillery)
	
	Util_ObjectiveComplete(Objective_Repair_Artillery.title_id)
	Rule_Remove(Rule_Objective_Repair_Artillery)
	
end

end

function Rule_Stop_Repair_Artillery_Ping()

Ping_Stop(g_ping_repair_artillery_mini)

end]]

-- used to establish individual pings for each of the 10 thermo plasma generators. --[[t_Titan_Pings = {

	geo_pings = {	g_ping_Thermo1,
							g_ping_Thermo2,
							g_ping_Thermo3,
							g_ping_Thermo4,
							g_ping_Thermo5,
							g_ping_Thermo6,
							g_ping_Thermo7,
							g_ping_Thermo8,
							g_ping_Thermo9,
							g_ping_Thermo10},
	
	mini_map_pings = {g_ping_Thermo_mini1,
									g_ping_Thermo_mini2,
									g_ping_Thermo_mini3,
									g_ping_Thermo_mini4,
									g_ping_Thermo_mini5,
									g_ping_Thermo_mini6,
									g_ping_Thermo_mini7,
									g_ping_Thermo_mini8,
									g_ping_Thermo_mini9,
									g_ping_Thermo_mini10}
	
}]]

--[[Secondary Objective - Shut down the Titan Cannon]] function Rule_Objective_Disable_Titan_Cannon()

if EGroup_IsEmpty("eg_Titan_Thermos") == true then
	
	g_Titan_Thermos_Destroyed = true
	
end

Objective_Disable_Titan_Cannon = {title_id = 2620060, short_desc_id = 2620061, help_tip_id = 2620060}	

if Event_IsAnyRunning() == false and Objective_Exists(Objective_Disable_Titan_Cannon.title_id) == false then
	
	Util_WXP_ObjectiveCreate(Objective_Disable_Titan_Cannon, false, g_Player1)
	
	Objective_ShowScreen()
	Flash_OtherButton("dlg_objectives", 0, false, true)
	
	--[[adding map and mini-map pings]]
		
	g_Disable_Titan_Cannon_ping1 = Objective_PingMarker(Objective_Disable_Titan_Cannon.title_id, "mkr_Thermo1", true, "default")
	g_Disable_Titan_Cannon_ping2 = Objective_PingMarker(Objective_Disable_Titan_Cannon.title_id, "mkr_Thermo2", true, "default")
	g_Disable_Titan_Cannon_ping3 = Objective_PingMarker(Objective_Disable_Titan_Cannon.title_id, "mkr_Thermo3", true, "default")
	g_Disable_Titan_Cannon_ping4 = Objective_PingMarker(Objective_Disable_Titan_Cannon.title_id, "mkr_Thermo4", true, "default")
	g_Disable_Titan_Cannon_ping5 = Objective_PingMarker(Objective_Disable_Titan_Cannon.title_id, "mkr_Thermo5", true, "default")
	g_Disable_Titan_Cannon_ping6 = Objective_PingMarker(Objective_Disable_Titan_Cannon.title_id, "mkr_Thermo6", true, "default")
	g_Disable_Titan_Cannon_ping7 = Objective_PingMarker(Objective_Disable_Titan_Cannon.title_id, "mkr_Thermo7", true, "default")
	g_Disable_Titan_Cannon_ping8 = Objective_PingMarker(Objective_Disable_Titan_Cannon.title_id, "mkr_Thermo8", true, "default")
	g_Disable_Titan_Cannon_ping9 = Objective_PingMarker(Objective_Disable_Titan_Cannon.title_id, "mkr_Thermo9", true, "default")
	g_Disable_Titan_Cannon_ping10 = Objective_PingMarker(Objective_Disable_Titan_Cannon.title_id, "mkr_Thermo10", true, "default")
	g_Disable_Titan_Cannon_mini_map_ping1 = Ping_Marker("mkr_Thermo1", true, "default")
	g_Disable_Titan_Cannon_mini_map_ping2 = Ping_Marker("mkr_Thermo2", true, "default")
	g_Disable_Titan_Cannon_mini_map_ping3 = Ping_Marker("mkr_Thermo3", true, "default")
	g_Disable_Titan_Cannon_mini_map_ping4 = Ping_Marker("mkr_Thermo4", true, "default")
	g_Disable_Titan_Cannon_mini_map_ping5 = Ping_Marker("mkr_Thermo5", true, "default")
	g_Disable_Titan_Cannon_mini_map_ping6 = Ping_Marker("mkr_Thermo6", true, "default")
	g_Disable_Titan_Cannon_mini_map_ping7 = Ping_Marker("mkr_Thermo7", true, "default")
	g_Disable_Titan_Cannon_mini_map_ping8 = Ping_Marker("mkr_Thermo8", true, "default")
	g_Disable_Titan_Cannon_mini_map_ping9 = Ping_Marker("mkr_Thermo9", true, "default")
	g_Disable_Titan_Cannon_mini_map_ping10 = Ping_Marker("mkr_Thermo10", true, "default")
	
	Rule_AddOneShot(Rule_Stop_Disable_Titan_Cannon, 5)
	
elseif Event_IsAnyRunning() == false and Objective_Exists(Objective_Disable_Titan_Cannon.title_id) then 
	
	--[[removing map and mini-map pings]]
	if g_Thermo_ping_removed == false then
		
		for j = 1,10 do
			
			if EGroup_Exists("eg_Thermo_Plasma"..j) == false or EGroup_Exists("eg_Thermo_Plasma"..j) and EGroup_IsEmpty("eg_Thermo_Plasma"..j) then
				
				if j == 1 then
					Objective_PingRemove(Objective_Disable_Titan_Cannon.title_id, g_Disable_Titan_Cannon_ping1)
				elseif j == 2 then
					Objective_PingRemove(Objective_Disable_Titan_Cannon.title_id, g_Disable_Titan_Cannon_ping2)
				elseif j == 3 then
					Objective_PingRemove(Objective_Disable_Titan_Cannon.title_id, g_Disable_Titan_Cannon_ping3)
				elseif j == 4 then
					Objective_PingRemove(Objective_Disable_Titan_Cannon.title_id, g_Disable_Titan_Cannon_ping4)
				elseif j == 5 then
					Objective_PingRemove(Objective_Disable_Titan_Cannon.title_id, g_Disable_Titan_Cannon_ping5)
				elseif j == 6 then
					Objective_PingRemove(Objective_Disable_Titan_Cannon.title_id, g_Disable_Titan_Cannon_ping6)
				elseif j == 7 then
					Objective_PingRemove(Objective_Disable_Titan_Cannon.title_id, g_Disable_Titan_Cannon_ping7)
				elseif j == 8 then
					Objective_PingRemove(Objective_Disable_Titan_Cannon.title_id, g_Disable_Titan_Cannon_ping8)
				elseif j == 9 then
					Objective_PingRemove(Objective_Disable_Titan_Cannon.title_id, g_Disable_Titan_Cannon_ping9)
				elseif j == 10 then
					Objective_PingRemove(Objective_Disable_Titan_Cannon.title_id, g_Disable_Titan_Cannon_ping10)
				end
				
			end
			
			g_Thermo_ping_removed = true
			
		end
		
	end
	
	if g_Titan_Thermos_Destroyed == true then
		
		Util_ObjectiveComplete(Objective_Disable_Titan_Cannon.title_id)
		Rule_Remove(Rule_Objective_Disable_Titan_Cannon)
		
		Rule_AddInterval(Rule_Objective_Capture_Titan_Cannon, 5)
		
	end
	
end

end

function Rule_Stop_Disable_Titan_Cannon()

Ping_Stop(g_Disable_Titan_Cannon_mini_map_ping1)
Ping_Stop(g_Disable_Titan_Cannon_mini_map_ping2)
Ping_Stop(g_Disable_Titan_Cannon_mini_map_ping3)
Ping_Stop(g_Disable_Titan_Cannon_mini_map_ping4)
Ping_Stop(g_Disable_Titan_Cannon_mini_map_ping5)
Ping_Stop(g_Disable_Titan_Cannon_mini_map_ping6)
Ping_Stop(g_Disable_Titan_Cannon_mini_map_ping7)
Ping_Stop(g_Disable_Titan_Cannon_mini_map_ping8)
Ping_Stop(g_Disable_Titan_Cannon_mini_map_ping9)
Ping_Stop(g_Disable_Titan_Cannon_mini_map_ping10)

end

--[[Secondary Objective - Take control of the Titan Cannon]] function Rule_Objective_Capture_Titan_Cannon()

Objective_Capture_Titan_Cannon = {title_id = 2620070, short_desc_id = 2620071, help_tip_id = 2620070}	

if Event_IsAnyRunning() == false and Objective_Exists(Objective_Capture_Titan_Cannon.title_id) == false then
	
	Util_WXP_ObjectiveCreate(Objective_Capture_Titan_Cannon, false, g_Player1)
	
	Objective_ShowScreen()
	Flash_OtherButton("dlg_objectives", 0, false, true)
	
	--[[adding map and mini-map pings]]
	g_Capture_Titan_Cannon_ping1 = Objective_PingMarker(Objective_Capture_Titan_Cannon.title_id, "mkr_Thermo1", true, "default")
	g_Capture_Titan_Cannon_ping2 = Objective_PingMarker(Objective_Capture_Titan_Cannon.title_id, "mkr_Thermo2", true, "default")
	g_Capture_Titan_Cannon_ping3 = Objective_PingMarker(Objective_Capture_Titan_Cannon.title_id, "mkr_Thermo3", true, "default")
	g_Capture_Titan_Cannon_ping4 = Objective_PingMarker(Objective_Capture_Titan_Cannon.title_id, "mkr_Thermo4", true, "default")
	g_Capture_Titan_Cannon_ping5 = Objective_PingMarker(Objective_Capture_Titan_Cannon.title_id, "mkr_Thermo5", true, "default")
	g_Capture_Titan_Cannon_ping6 = Objective_PingMarker(Objective_Capture_Titan_Cannon.title_id, "mkr_Thermo6", true, "default")
	g_Capture_Titan_Cannon_ping7 = Objective_PingMarker(Objective_Capture_Titan_Cannon.title_id, "mkr_Thermo7", true, "default")
	g_Capture_Titan_Cannon_ping8 = Objective_PingMarker(Objective_Capture_Titan_Cannon.title_id, "mkr_Thermo8", true, "default")
	g_Capture_Titan_Cannon_ping9 = Objective_PingMarker(Objective_Capture_Titan_Cannon.title_id, "mkr_Thermo9", true, "default")
	g_Capture_Titan_Cannon_ping10 = Objective_PingMarker(Objective_Capture_Titan_Cannon.title_id, "mkr_Thermo10", true, "default")
	g_Capture_Titan_Cannon_mini_map_ping1 = Ping_Marker("mkr_Thermo1", true, "default")
	g_Capture_Titan_Cannon_mini_map_ping2 = Ping_Marker("mkr_Thermo2", true, "default")
	g_Capture_Titan_Cannon_mini_map_ping3 = Ping_Marker("mkr_Thermo3", true, "default")
	g_Capture_Titan_Cannon_mini_map_ping4 = Ping_Marker("mkr_Thermo4", true, "default")
	g_Capture_Titan_Cannon_mini_map_ping5 = Ping_Marker("mkr_Thermo5", true, "default")
	g_Capture_Titan_Cannon_mini_map_ping6 = Ping_Marker("mkr_Thermo6", true, "default")
	g_Capture_Titan_Cannon_mini_map_ping7 = Ping_Marker("mkr_Thermo7", true, "default")
	g_Capture_Titan_Cannon_mini_map_ping8 = Ping_Marker("mkr_Thermo8", true, "default")
	g_Capture_Titan_Cannon_mini_map_ping9 = Ping_Marker("mkr_Thermo9", true, "default")
	g_Capture_Titan_Cannon_mini_map_ping10 = Ping_Marker("mkr_Thermo10", true, "default")
	
	Rule_AddOneShot(Rule_Stop_Capture_Titan_Cannon, 5)
	
elseif Event_IsAnyRunning() == false and Objective_Exists(Objective_Capture_Titan_Cannon.title_id) and g_Titan_Captured == true then 
	
	--[[removing map and mini-map pings]]
	if g_Thermo_ping_removed2 == false then
		
		Objective_PingRemove(Objective_Capture_Titan_Cannon.title_id, g_Capture_Titan_Cannon_ping1)
		Objective_PingRemove(Objective_Capture_Titan_Cannon.title_id, g_Capture_Titan_Cannon_ping2)
		Objective_PingRemove(Objective_Capture_Titan_Cannon.title_id, g_Capture_Titan_Cannon_ping3)
		Objective_PingRemove(Objective_Capture_Titan_Cannon.title_id, g_Capture_Titan_Cannon_ping4)
		Objective_PingRemove(Objective_Capture_Titan_Cannon.title_id, g_Capture_Titan_Cannon_ping5)
		Objective_PingRemove(Objective_Capture_Titan_Cannon.title_id, g_Capture_Titan_Cannon_ping6)
		Objective_PingRemove(Objective_Capture_Titan_Cannon.title_id, g_Capture_Titan_Cannon_ping7)
		Objective_PingRemove(Objective_Capture_Titan_Cannon.title_id, g_Capture_Titan_Cannon_ping8)
		Objective_PingRemove(Objective_Capture_Titan_Cannon.title_id, g_Capture_Titan_Cannon_ping9)
		Objective_PingRemove(Objective_Capture_Titan_Cannon.title_id, g_Capture_Titan_Cannon_ping10)
		
		g_Thermo_ping_removed2 = true
		
	end
	
	Util_ObjectiveComplete(Objective_Capture_Titan_Cannon.title_id)
	Rule_Remove(Rule_Objective_Capture_Titan_Cannon)
	
end

end

function Rule_Stop_Capture_Titan_Cannon()

for i = 1,10 do
	
	Ping_Stop(g_Capture_Titan_Cannon_mini_map_ping1)
	Ping_Stop(g_Capture_Titan_Cannon_mini_map_ping2)
	Ping_Stop(g_Capture_Titan_Cannon_mini_map_ping3)
	Ping_Stop(g_Capture_Titan_Cannon_mini_map_ping4)
	Ping_Stop(g_Capture_Titan_Cannon_mini_map_ping5)
	Ping_Stop(g_Capture_Titan_Cannon_mini_map_ping6)
	Ping_Stop(g_Capture_Titan_Cannon_mini_map_ping7)
	Ping_Stop(g_Capture_Titan_Cannon_mini_map_ping8)
	Ping_Stop(g_Capture_Titan_Cannon_mini_map_ping9)
	Ping_Stop(g_Capture_Titan_Cannon_mini_map_ping10)
	
end

end


--[[ INTEL EVENTS ]]

function Rule_Opening_Discussion()

local humanplayer = MetaMap_GetPlayerRaceName()

if humanplayer == "chaos_marine_race" then
	
	Util_StartIntel(EVENTS.IE_Chaos_Start)
	
elseif humanplayer == "eldar_race" then
	
	Util_StartIntel(EVENTS.IE_Eldar_Start)
	
elseif humanplayer == "guard_race" then
	
	--[[no text since this is the IG stronghold]]
	
elseif humanplayer == "ork_race" then
	
	Util_StartIntel(EVENTS.IE_Ork_Start)	
	
elseif humanplayer =="space_marine_race" then
	
	Util_StartIntel(EVENTS.IE_SM_Start)	
	
elseif humanplayer == "tau_race" then
	
	Util_StartIntel(EVENTS.IE_Tau_Start)
	
elseif humanplayer == "necron_race" then
	
	Util_StartIntel(EVENTS.IE_Necron_Start)
	
end

end

function Rule_FB_IE_Taunts()

t_IE_FB_Taunts = {	EVENTS.IE_Taunt1,
								EVENTS.IE_Taunt2,
								EVENTS.IE_Taunt3,
								EVENTS.IE_Taunt4,
								EVENTS.IE_Taunt5}

local rand_chance = World_GetRand(1,2)
local rand_taunt = World_GetRand(1,5) 

if rand_chance == 1 then
	
	--rand must not equal the last rand varible stored in g_FB_IE_Last_Taunt, this will stop repeat IE events back to back.
	if not (rand_taunt == g_FB_IE_Last_Taunt) then
		Util_StartIntel(t_IE_FB_Taunts[rand_taunt])
		
		g_FB_IE_Last_Taunt = rand_taunt
		
	end
	
end

end

function Rule_First_Artillery_Strike_IE()

Util_StartIntel(EVENTS.IE_First_Artillery_Strike)

end

function Rule_Second_Half_IE()

Util_StartIntel(EVENTS.IE_Second_Half)

end

function Rule_Strat_Recapture_IE()

t_IE_Recap_Taunts = {	EVENTS.IE_Recapture1,
										EVENTS.IE_Recapture2,
										EVENTS.IE_Recapture3,
										EVENTS.IE_Recapture4}

local rand_chance = World_GetRand(1,2)
local rand_taunt = World_GetRand(1,4) 

if rand_chance == 1 then
	
	--rand must not equal the last rand varible stored in g_Recap_IE_Last_Taunt, this will stop repeat IE events back to back.
	if not (rand_taunt == g_Recap_IE_Last_Taunt) then
		
		Util_StartIntel(t_IE_Recap_Taunts[rand_taunt])
		
		g_Recap_IE_Last_Taunt = rand_taunt
		
	end
	
end

end

function Rule_Commissar_Death_IE()

if MetaMap_GetPlayerRaceName() == "chaos_marine_race" then
	
	Util_StartIntel(EVENTS.IE_Chaos_Commissar)
	
elseif MetaMap_GetPlayerRaceName() == "eldar_race" then
	
	Util_StartIntel(EVENTS.IE_Eldar_Commissar)
	
elseif MetaMap_GetPlayerRaceName() == "guard_race" then
	
	--[[N/A]]
	
elseif MetaMap_GetPlayerRaceName() == "ork_race" then
	
	Util_StartIntel(EVENTS.IE_Ork_Commissar)
	
elseif MetaMap_GetPlayerRaceName() == "space_marine_race" then
	
	Util_StartIntel(EVENTS.IE_SM_Commissar)
	
elseif MetaMap_GetPlayerRaceName() == "tau_race" then
	
	Util_StartIntel(EVENTS.IE_Tau_Commissar)
	
elseif MetaMap_GetPlayerRaceName() == "necron_race" then
	
	Util_StartIntel(EVENTS.IE_Necron_Commissar)
	
end

end

function Rule_Stronghold_Breach_IE()

if MetaMap_GetPlayerRaceName() == "chaos_marine_race" then
	
	Util_StartIntel(EVENTS.IE_Chaos_Breach)
	
elseif MetaMap_GetPlayerRaceName() == "eldar_race" then
	
	Util_StartIntel(EVENTS.IE_Eldar_Breach)
	
elseif MetaMap_GetPlayerRaceName() == "guard_race" then
	
	--[[N/A]]
	
elseif MetaMap_GetPlayerRaceName() == "ork_race" then
	
	Util_StartIntel(EVENTS.IE_Ork_Breach)
	
elseif MetaMap_GetPlayerRaceName() == "space_marine_race" then
	
	Util_StartIntel(EVENTS.IE_SM_Breach)
	
elseif MetaMap_GetPlayerRaceName() == "tau_race" then
	
	Util_StartIntel(EVENTS.IE_Tau_Breach)
	
elseif MetaMap_GetPlayerRaceName() == "necron_race" then
	
	Util_StartIntel(EVENTS.IE_Necron_Breach)
	
end

end

function Rule_FB_Detect_IE()

if MetaMap_GetPlayerRaceName() == "chaos_marine_race" then
	
	Util_StartIntel(EVENTS.IE_Chaos_FB)
	
elseif MetaMap_GetPlayerRaceName() == "eldar_race" then
	
	Util_StartIntel(EVENTS.IE_Eldar_FB)
	
elseif MetaMap_GetPlayerRaceName() == "guard_race" then
	
	--[[N/A]]
	
elseif MetaMap_GetPlayerRaceName() == "ork_race" then
	
	Util_StartIntel(EVENTS.IE_Ork_FB)
	
elseif MetaMap_GetPlayerRaceName() == "space_marine_race" then
	
	Util_StartIntel(EVENTS.IE_SM_FB)
	
elseif MetaMap_GetPlayerRaceName() == "tau_race" then
	
	Util_StartIntel(EVENTS.IE_Tau_FB)
	
elseif MetaMap_GetPlayerRaceName() == "necron_race" then
	
	Util_StartIntel(EVENTS.IE_Necron_FB)
	
end

end

function Rule_South_Bridge_IE()

Util_StartIntel(EVENTS.IE_South_Bridge)

end

function Rule_Armor_Base_Detect_IE()

Util_StartIntel(EVENTS.IE_Armor_Base)

end


--[[ NIS ]]

function Rule_Opening_NIS()

Util_StartNIS(EVENTS.NIS_Intro)

end

function Rule_Remove_NIS_Bridge_Troops()

for i = 1,2 do
	
	Player_GetAllSquadsNearMarker(g_Player2, "sg_Bridge_destroy"..i, "mkr_Intro_NIS_Bridge_Target"..i)
	
	if SGroup_Exists("sg_Bridge_destroy"..i) and SGroup_IsEmpty("sg_Bridge_destroy"..i) == false then
		
		SGroup_DeSpawn("sg_Bridge_destroy"..i)
		
	end
	
end

end

function Rule_Closing_NIS()

g_gameover = true

Util_StartNIS(EVENTS.NIS_Outro)

end


--[[ win loss ]]

function Rule_EndGame_Win()

if EGroup_Exists("eg_IG_HQ") == false or (EGroup_Exists("eg_IG_HQ") and EGroup_IsEmpty("eg_IG_HQ")) then

	g_Win = true
	Rule_Remove(Rule_EndGame_Win)
	Rule_Remove(Rule_EndGame_Lose)

end

end

function Rule_EndGame_Lose()

g_building_exceptions = 
{
	--guard buildings
	"guard_thermo_plasma",
	"guard_plasma_generator",
	"guard_turret_heavy_bolter",
	"guard_mines",
	
	--chaos buildings
	"chaos_thermo_plasma_generator",
	"chaos_plasma_generator",
	"chaos_turret_bolter",
	"chaos_mine_field",
	
	--eldar buildings
	"eldar_advanced_warp_generator",
	"eldar_warp_generator",
	"eldar_support_platform_scatterlaser",
	"eldar_mine_field",
	
	--necron buildings
	"necron_thermoplasma_generator",
	"necron_plasma_generator",
	"necron_turret",
	
	--ork buildings
	"ork_bigger_generator",
	"ork_generator",
	"ork_waagh_banner",
	"ork_mine_field",
	
	--space marines
	"space_marine_thermo_generator",
	"space_marine_generator",
	"space_marine_turret_bolter",
	"space_marine_mine_field",
	
	--tau buildings
	"tau_thermoplasma_generator",
	"tau_plasma_generator"
}

g_unit_exceptions = 
{

}

--[[ Lose because of Annihilation ]]	
if( Player_HasBuildingsExcept(g_Player1, g_building_exceptions) == false ) then
	
	Rule_RemoveAll()
	Fade_Start(4, false)
	World_SetTeamWin( g_enemy, "" )
	Rule_AddIntervalEx( Rule_GameOver,5,1 )
	
end

end

--[[ call this with an interval to ensure the mission ends ]] function Rule_GameOver() World_SetGameOver() end


--[[ test ]]

function test()

Util_CreateSquadsAtMarker(g_Player2, "sg_test"..g_test, "chaos_marine_squad", "mkr_Artillery_Trigger1", 1)

SGroup_SetHealthInvulnerable("sg_test"..g_test, true)

Cpu_LockSGroupAcrossPlayers("sg_test"..g_test)

g_test = g_test + 1

end