code:
//This file was auto-corrected by findeclaration.exe on 25.5.2012 20:42:31

/*
 * GAMEMODES (by Rastaf0)
 *
 * In the new mode system all special roles are fully supported.
 * You can have proper wizards/traitors/changelings/cultists during any mode.
 * Only two things really depends on gamemode:
 * 1. Starting roles, equipment and preparations
 * 2. Conditions of finishing the round.
 *
 */

/datum/game_mode
	var/name = "invalid"
	var/config_tag = null
	var/votable = 1
	var/probability = 0
	var/station_was_nuked = 0 //see nuclearbomb.dm and malfunction.dm
	var/explosion_in_progress = 0 //sit back and relax
	var/round_ends_with_antag_death = 0 //flags the "one verse the station" antags as such
	var/list/datum/mind/modePlayer = new
	var/list/datum/mind/antag_candidates = list()	// List of possible starting antags goes here
	var/list/restricted_jobs = list()	// Jobs it doesn't make sense to be.  I.E chaplain or AI cultist
	var/list/protected_jobs = list()	// Jobs that can't be traitors because
	var/required_players = 0
	var/required_enemies = 0
	var/recommended_enemies = 0
	var/antag_flag = null //preferences flag such as BE_WIZARD that need to be turned on for players to be antag
	var/mob/living/living_antag_player = null
	var/list/datum/game_mode/replacementmode = null
	var/round_converted = 0 //0: round not converted, 1: round going to convert, 2: round converted
	var/reroll_friendly 	//During mode conversion only these are in the running
	var/continuous_sanity_checked	//Catches some cases where config options could be used to suggest that modes without antagonists should end when all antagonists die
	var/enemy_minimum_age = 7 //How many days must players have been playing before they can play this antagonist

	var/const/waittime_l = 600
	var/const/waittime_h = 1800 // started at 1800

/datum/game_mode/proc/announce() //to be calles when round starts
	world << "Notice: [src] did not define announce()"

///can_start()
///Checks to see if the game can be setup and ran with the current number of players or whatnot.
/datum/game_mode/proc/can_start()
	var/playerC = 0
	for(var/mob/new_player/player in player_list)
		if((player.client)&&(player.ready))
			playerC++
	if(!Debug2)
		if(playerC < required_players)
			return 0
	antag_candidates = get_players_for_role(antag_flag)
	if(!Debug2)
		if(antag_candidates.len < required_enemies)
			return 0
		return 1
	else
		world << "DEBUG: GAME STARTING WITHOUT PLAYER NUMBER CHECKS, THIS WILL PROBABLY BREAK SHIT."
		return 1

///pre_setup()
///Attempts to select players for special roles the mode might have.
/datum/game_mode/proc/pre_setup()
	return 1

///post_setup()
///Everyone should now be on the station and have their normal gear.  This is the place to give the special roles extra things
/datum/game_mode/proc/post_setup(report=0) //Gamemodes can override the intercept report. Passing a 1 as the argument will force a report.
	if(!report)
		report = config.intercept
	spawn (ROUNDSTART_LOGOUT_REPORT_TIME)
		display_roundstart_logout_report()

	feedback_set_details("round_start","[time2text(world.realtime)]")
	if(ticker && ticker.mode)
		feedback_set_details("game_mode","[ticker.mode]")
	if(revdata.commit)
		feedback_set_details("revision","[revdata.commit]")
	feedback_set_details("server_ip","[world.internet_address]:[world.port]")
	if(report)
		spawn (rand(waittime_l, waittime_h))
			send_intercept(0)
	start_state = new /datum/station_state()
	start_state.count(1)
	return 1

///make_antag_chance()
///Handles late-join antag assignments
/datum/game_mode/proc/make_antag_chance(mob/living/carbon/human/character)
	if(replacementmode && round_converted == 2)
		replacementmode.make_antag_chance(character)
	return

///convert_roundtype()
///Allows rounds to basically be "rerolled" should the initial premise fall through
/datum/game_mode/proc/convert_roundtype()
	var/list/living_crew = list()

	for(var/mob/Player in mob_list)
		if(Player.mind && Player.stat != DEAD && !isnewplayer(Player) &&!isbrain(Player))
			living_crew += Player
	if(living_crew.len / joined_player_list.len <= config.midround_antag_life_check) //If a lot of the player base died, we start fresh
		message_admins("Convert_roundtype failed due to too many dead people. Limit is [config.midround_antag_life_check * 100]% living crew")
		return null

	var/list/datum/game_mode/runnable_modes = config.get_runnable_midround_modes(living_crew.len)
	var/list/datum/game_mode/usable_modes = list()
	for(var/datum/game_mode/G in runnable_modes)
		if(G.reroll_friendly)
			usable_modes += G
		else
			qdel(G)

	if(!usable_modes)
		message_admins("Convert_roundtype failed due to no valid modes to convert to. Please report this error to the Coders.")
		return null

	replacementmode = pickweight(usable_modes)

	switch(SSshuttle.emergency.mode) //Rounds on the verge of ending don't get new antags, they just run out
		if(SHUTTLE_STRANDED, SHUTTLE_ESCAPE)
			return 1
		if(SHUTTLE_CALL)
			if(SSshuttle.emergency.timeLeft(1) < initial(SSshuttle.emergencyCallTime)*0.5)
				return 1

	if(world.time >= (config.midround_antag_time_check * 600))
		message_admins("Convert_roundtype failed due to round length. Limit is [config.midround_antag_time_check] minutes.")
		return null

	var/list/antag_canadates = list()

	for(var/mob/living/carbon/human/H in living_crew)
		if(H.client && H.client.prefs.allow_midround_antag)
			antag_canadates += H

	if(!antag_canadates)
		message_admins("Convert_roundtype failed due to no antag canadates.")
		return null

	antag_canadates = shuffle(antag_canadates)

	if(config.protect_roles_from_antagonist)
		replacementmode.restricted_jobs += replacementmode.protected_jobs
	if(config.protect_assistant_from_antagonist)
		replacementmode.restricted_jobs += "Assistant"

	message_admins("The roundtype will be converted. If you have other plans for the station or think the round should end stop the creation of antags or end the round now.")

	spawn(rand(1200,3000)) //somewhere between 2 and 5 minutes from now
		if(!config.midround_antag[ticker.mode.config_tag])
			round_converted = 0
			return 1
		for(var/mob/living/carbon/human/H in antag_canadates)
			replacementmode.make_antag_chance(H)
		round_converted = 2
		message_admins("The roundtype has been converted, antagonists may have been created")
	return 1

///process()
///Called by the gameticker
/datum/game_mode/process()
	return 0

/datum/game_mode/proc/check_finished() //to be called by ticker
	if(replacementmode && round_converted == 2)
		return replacementmode.check_finished()
	if(SSshuttle.emergency.mode >= SHUTTLE_ENDGAME || station_was_nuked)
		return 1
	if(!round_converted && (!config.continuous[config_tag] || (config.continuous[config_tag] && config.midround_antag[config_tag]))) //Non-continuous or continous with replacement antags
		if(!continuous_sanity_checked) //make sure we have antags to be checking in the first place
			for(var/mob/Player in mob_list)
				if(Player.mind)
					if(Player.mind.special_role)
						continuous_sanity_checked = 1
						return 0
			if(!continuous_sanity_checked)
				message_admins("The roundtype ([config_tag]) has no antagonists, continuous round has been defaulted to on and midround_antag has been defaulted to off.")
				config.continuous[config_tag] = 1
				config.midround_antag[config_tag] = 0
				SSshuttle.emergencyNoEscape = 0
				return 0

		if(living_antag_player && living_antag_player.mind && isliving(living_antag_player) && living_antag_player.stat != DEAD && !isnewplayer(living_antag_player) &&!isbrain(living_antag_player))
			return 0 //A resource saver: once we find someone who has to die for all antags to be dead, we can just keep checking them, cycling over everyone only when we lose our mark.

		for(var/mob/Player in living_mob_list)
			if(Player.mind && Player.stat != DEAD && !isnewplayer(Player) &&!isbrain(Player))
				if(Player.mind.special_role) //Someone's still antaging!
					living_antag_player = Player
					return 0

		if(!config.continuous[config_tag])
			return 1

		else
			round_converted = convert_roundtype()
			if(!round_converted)
				if(round_ends_with_antag_death)
					return 1
				else
					config.midround_antag[config_tag] = 0
					return 0

	return 0

/datum/game_mode/proc/declare_completion()
	var/clients = 0
	var/surviving_humans = 0
	var/surviving_total = 0
	var/ghosts = 0
	var/escaped_humans = 0
	var/escaped_total = 0

	for(var/mob/M in player_list)
		if(M.client)
			clients++
			if(ishuman(M))
				if(!M.stat)
					surviving_humans++
					if(M.z == 2)
						escaped_humans++
			if(!M.stat)
				surviving_total++
				if(M.z == 2)
					escaped_total++

			if(isobserver(M))
				ghosts++

	if(clients > 0)
		feedback_set("round_end_clients",clients)
	if(ghosts > 0)
		feedback_set("round_end_ghosts",ghosts)
	if(surviving_humans > 0)
		feedback_set("survived_human",surviving_humans)
	if(surviving_total > 0)
		feedback_set("survived_total",surviving_total)
	if(escaped_humans > 0)
		feedback_set("escaped_human",escaped_humans)
	if(escaped_total > 0)
		feedback_set("escaped_total",escaped_total)
	send2irc("Server", "Round just ended.")
	return 0

/datum/game_mode/proc/check_win() //universal trigger to be called at mob death, nuke explosion, etc. To be called from everywhere.
	return 0

/datum/game_mode/proc/send_intercept()
	var/intercepttext = "Centcom Update Requested status information:
"
	intercepttext += " Centcom has recently been contacted by the following syndicate affiliated organisations in your area, please investigate any information you may have:"

	var/list/possible_modes = list()
	possible_modes.Add("revolution", "wizard", "nuke", "traitor", "malf", "changeling", "cult", "gang")
	possible_modes -= "[ticker.mode]" //remove current gamemode to prevent it from being randomly deleted, it will be readded later

	var/number = pick(1, 2)
	var/i = 0
	for(i = 0, i < number, i++) //remove 1 or 2 possibles modes from the list
		possible_modes.Remove(pick(possible_modes))

	possible_modes[rand(1, possible_modes.len)] = "[ticker.mode]" //replace a random game mode with the current one

	possible_modes = shuffle(possible_modes) //shuffle the list to prevent meta

	var/datum/intercept_text/i_text = new /datum/intercept_text
	for(var/A in possible_modes)
		if(modePlayer.len == 0)
			intercepttext += i_text.build(A)
		else
			intercepttext += i_text.build(A, pick(modePlayer))

	print_command_report(intercepttext,"Centcom Status Summary")
	priority_announce("Summary downloaded and printed out at all communications consoles.", "Enemy communication intercept. Security Level Elevated.", 'sound/AI/intercept.ogg')
	if(security_level < SEC_LEVEL_BLUE)
		set_security_level(SEC_LEVEL_BLUE)

/datum/game_mode/proc/get_players_for_role(role)
	var/list/players = list()
	var/list/candidates = list()
	var/list/drafted = list()
	var/datum/mind/applicant = null

	// Ultimate randomizing code right here
	for(var/mob/new_player/player in player_list)
		if(player.client && player.ready)
			players += player

	// Shuffling, the players list is now ping-independent!!!
	// Goodbye antag dante
	players = shuffle(players)

	for(var/mob/new_player/player in players)
		if(player.client && player.ready)
			if(role in player.client.prefs.be_special)
				if(!jobban_isbanned(player, "Syndicate") && !jobban_isbanned(player, role)) //Nodrak/Carn: Antag Job-bans
					if(age_check(player.client)) //Must be older than the minimum age
						candidates += player.mind				// Get a list of all the people who want to be the antagonist for this round

	if(restricted_jobs)
		for(var/datum/mind/player in candidates)
			for(var/job in restricted_jobs)					// Remove people who want to be antagonist but have a job already that precludes it
				if(player.assigned_role == job)
					candidates -= player

	if(candidates.len < recommended_enemies)
		for(var/mob/new_player/player in players)
			if(player.client && player.ready)
				if(!(role in player.client.prefs.be_special)) // We don't have enough people who want to be antagonist, make a seperate list of people who don't want to be one
					if(!jobban_isbanned(player, "Syndicate") && !jobban_isbanned(player, role)) //Nodrak/Carn: Antag Job-bans
						drafted += player.mind

	if(restricted_jobs)
		for(var/datum/mind/player in drafted)				// Remove people who can't be an antagonist
			for(var/job in restricted_jobs)
				if(player.assigned_role == job)
					drafted -= player

	drafted = shuffle(drafted) // Will hopefully increase randomness, Donkie

	while(candidates.len < recommended_enemies)				// Pick randomlly just the number of people we need and add them to our list of candidates
		if(drafted.len > 0)
			applicant = pick(drafted)
			if(applicant)
				candidates += applicant
				drafted.Remove(applicant)

		else												// Not enough scrubs, ABORT ABORT ABORT
			break
/*
	if(candidates.len < recommended_enemies && override_jobbans) //If we still don't have enough people, we're going to start drafting banned people.
		for(var/mob/new_player/player in players)
			if (player.client && player.ready)
				if(jobban_isbanned(player, "Syndicate") || jobban_isbanned(player, roletext)) //Nodrak/Carn: Antag Job-bans
					drafted += player.mind
*/
	if(restricted_jobs)
		for(var/datum/mind/player in drafted)				// Remove people who can't be an antagonist
			for(var/job in restricted_jobs)
				if(player.assigned_role == job)
					drafted -= player

	drafted = shuffle(drafted) // Will hopefully increase randomness, Donkie

	while(candidates.len < recommended_enemies)				// Pick randomlly just the number of people we need and add them to our list of candidates
		if(drafted.len > 0)
			applicant = pick(drafted)
			if(applicant)
				candidates += applicant
				drafted.Remove(applicant)

		else												// Not enough scrubs, ABORT ABORT ABORT
			break

	return candidates		// Returns: The number of people who had the antagonist role set to yes, regardless of recomended_enemies, if that number is greater than recommended_enemies
							//			recommended_enemies if the number of people with that role set to yes is less than recomended_enemies,
							//			Less if there are not enough valid players in the game entirely to make recommended_enemies.

/*
/datum/game_mode/proc/check_player_role_pref(var/role, var/mob/new_player/player)
	if(player.preferences.be_special & role)
		return 1
	return 0
*/

/datum/game_mode/proc/num_players()
	. = 0
	for(var/mob/new_player/P in player_list)
		if(P.client && P.ready)
			. ++

///////////////////////////////////
//Keeps track of all living heads//
///////////////////////////////////
/datum/game_mode/proc/get_living_heads()
	. = list()
	for(var/mob/living/carbon/human/player in mob_list)
		if(player.stat != DEAD && player.mind && (player.mind.assigned_role in command_positions))
			. |= player.mind

////////////////////////////
//Keeps track of all heads//
////////////////////////////
/datum/game_mode/proc/get_all_heads()
	. = list()
	for(var/mob/player in mob_list)
		if(player.mind && (player.mind.assigned_role in command_positions))
			. |= player.mind

//////////////////////////////////////////////
//Keeps track of all living security members//
//////////////////////////////////////////////
/datum/game_mode/proc/get_living_sec()
	. = list()
	for(var/mob/living/carbon/human/player in mob_list)
		if(player.stat != DEAD && player.mind && (player.mind.assigned_role in security_positions))
			. |= player.mind

////////////////////////////////////////
//Keeps track of all  security members//
////////////////////////////////////////
/datum/game_mode/proc/get_all_sec()
	. = list()
	for(var/mob/living/carbon/human/player in mob_list)
		if(player.mind && (player.mind.assigned_role in security_positions))
			. |= player.mind

//////////////////////////
//Reports player logouts//
//////////////////////////
/proc/display_roundstart_logout_report()
	var/msg = "Roundstart logout report\n\n"
	for(var/mob/living/L in mob_list)

		if(L.ckey)
			var/found = 0
			for(var/client/C in clients)
				if(C.ckey == L.ckey)
					found = 1
					break
			if(!found)
				msg += "[L.name] ([L.ckey]), the [L.job] (Disconnected)\n"

		if(L.ckey && L.client)
			if(L.client.inactivity >= (ROUNDSTART_LOGOUT_REPORT_TIME / 2))	//Connected, but inactive (alt+tabbed or something)
				msg += "[L.name] ([L.ckey]), the [L.job] (Connected, Inactive)\n"
				continue //AFK client
			if(L.stat)
				if(L.suiciding)	//Suicider
					msg += "[L.name] ([L.ckey]), the [L.job] (Suicide)\n"
					continue //Disconnected client
				if(L.stat == UNCONSCIOUS)
					msg += "[L.name] ([L.ckey]), the [L.job] (Dying)\n"
					continue //Unconscious
				if(L.stat == DEAD)
					msg += "[L.name] ([L.ckey]), the [L.job] (Dead)\n"
					continue //Dead

			continue //Happy connected client
		for(var/mob/dead/observer/D in mob_list)
			if(D.mind && D.mind.current == L)
				if(L.stat == DEAD)
					if(L.suiciding)	//Suicider
						msg += "[L.name] ([ckey(D.mind.key)]), the [L.job] (Suicide)\n"
						continue //Disconnected client
					else
						msg += "[L.name] ([ckey(D.mind.key)]), the [L.job] (Dead)\n"
						continue //Dead mob, ghost abandoned
				else
					if(D.can_reenter_corpse)
						continue //Adminghost, or cult/wizard ghost
					else
						msg += "[L.name] ([ckey(D.mind.key)]), the [L.job] (Ghosted)\n"
						continue //Ghosted while alive

	for(var/mob/M in mob_list)
		if(M.client && M.client.holder)
			M << msg

/datum/game_mode/proc/printplayer(datum/mind/ply, fleecheck)
	var/text = "
[ply.key] was [ply.name] the [ply.assigned_role] and"
	if(ply.current)
		if(ply.current.stat == DEAD)
			text += " died"
		else
			text += " survived"
		if(fleecheck && ply.current.z > ZLEVEL_STATION)
			text += " while fleeing the station"
		if(ply.current.real_name != ply.name)
			text += " as [ply.current.real_name]"
	else
		text += " had their body destroyed"
	return text

/datum/game_mode/proc/printobjectives(datum/mind/ply)
	var/text = ""
	var/count = 1
	for(var/datum/objective/objective in ply.objectives)
		if(objective.check_completion())
			text += "
Objective #[count]: [objective.explanation_text] Success!"
		else
			text += "
Objective #[count]: [objective.explanation_text] Fail."
		count++
	return text

//If the configuration option is set to require players to be logged as old enough to play certain jobs, then this proc checks that they are, otherwise it just returns 1
/datum/game_mode/proc/age_check(client/C)
	if(get_remaining_days(C) == 0)
		return 1	//Available in 0 days = available right now = player is old enough to play.
	return 0

/datum/game_mode/proc/get_remaining_days(client/C)
	if(!C)
		return 0
	if(!config.use_age_restriction_for_jobs)
		return 0
	if(!isnum(C.player_age))
		return 0 //This is only a number if the db connection is established, otherwise it is text: "Requires database", meaning these restrictions cannot be enforced
	if(!isnum(enemy_minimum_age))
		return 0

	return max(0, enemy_minimum_age - C.player_age)

/datum/game_mode/proc/replace_jobbaned_player(mob/living/M, role_type, pref)
	var/list/mob/dead/observer/candidates = pollCandidates("Do you want to play as a [role_type]?", "[role_type]", null, pref, 100)
	var/mob/dead/observer/theghost = null
	if(candidates.len)
		theghost = pick(candidates)
		M << "Your mob has been taken over by a ghost! Appeal your job ban if you want to avoid this in the future!"
		message_admins("[key_name_admin(theghost)] has taken control of ([key_name_admin(M)]) to replace a jobbaned player.")
		M.ghostize(0)
		M.key = theghost.key

/datum/game_mode/proc/remove_antag_for_borging(datum/mind/newborgie)
	ticker.mode.remove_cultist(newborgie, 0)
	ticker.mode.remove_revolutionary(newborgie, 0)
	ticker.mode.remove_gangster(newborgie, 0, remove_bosses=1)
	ticker.mode.remove_hog_follower(newborgie, 0)


code:
/obj/machinery/dominator
	name = "dominator"
	desc = "A visibly sinister device. Looks like you can break it if you hit it enough."
	icon = 'icons/obj/machines/dominator.dmi'
	icon_state = "dominator"
	density = 1
	anchored = 1
	layer = 3.6
	var/maxhealth = 200
	var/health = 200
	var/datum/gang/gang
	var/operating = 0	//-1=broken, 0=standby, 1=takeover
	var/warned = 0	//if this device has set off the warning at <3 minutes yet

/obj/machinery/dominator/tesla_act()
	qdel(src)

/obj/machinery/dominator/New()
	..()
	SetLuminosity(2)
	poi_list |= src

/obj/machinery/dominator/examine(mob/user)
	..()
	if(operating == -1)
		user << "It looks completely busted."
		return

	var/time
	if(gang && isnum(gang.dom_timer))
		time = max(gang.dom_timer, 0)
		if(time > 0)
			user << "Hostile Takeover in progress. Estimated [time] seconds remain."
		else
			user << "Hostile Takeover of [station_name()] successful. Have a great day."
	else
		user << "System on standby."
	user << "System Integrity: [round((health/maxhealth)*100,1)]%"

/obj/machinery/dominator/process()
	..()
	if(gang && isnum(gang.dom_timer))
		if(gang.dom_timer > 0)
			playsound(loc, 'sound/items/timer.ogg', 10, 0)
			if(!warned && (gang.dom_timer < 180))
				warned = 1
				var/area/domloc = get_area(loc)
				gang.message_gangtools("Less than 3 minutes remain in hostile takeover. Defend your dominator at [domloc.map_name]!")
				for(var/datum/gang/G in ticker.mode.gangs)
					if(G != gang)
						G.message_gangtools("WARNING: [gang.name] Gang takeover imminent. Their dominator at [domloc.map_name] must be destroyed!",1,1)
		else
			SSmachine.processing -= src

/obj/machinery/dominator/proc/healthcheck(damage)
	var/iconname = "dominator"
	if(gang)
		iconname += "-[gang.color]"
		SetLuminosity(3)

	var/datum/effect_system/spark_spread/sparks = new /datum/effect_system/spark_spread

	health -= damage

	if(health > (maxhealth/2))
		if(prob(damage*2))
			sparks.set_up(5, 1, src)
			sparks.start()
	else if(operating >= 0)
		sparks.set_up(5, 1, src)
		sparks.start()
		overlays += "damage"

	if(operating != -1)
		if(health <= 0)
			set_broken()
		else
			icon_state = iconname

	if(health <= -100)
		new /obj/item/stack/sheet/plasteel(src.loc)
		qdel(src)

/obj/machinery/dominator/proc/set_broken()
	if(gang)
		gang.dom_timer = "OFFLINE"

		var/takeover_in_progress = 0
		for(var/datum/gang/G in ticker.mode.gangs)
			if(isnum(G.dom_timer))
				takeover_in_progress = 1
				break
		if(!takeover_in_progress)
			SSshuttle.emergencyNoEscape = 0
			if(SSshuttle.emergency.mode == SHUTTLE_STRANDED)
				SSshuttle.emergency.mode = SHUTTLE_DOCKED
				SSshuttle.emergency.timer = world.time
				priority_announce("Hostile enviroment resolved. You have 3 minutes to board the Emergency Shuttle.", null, 'sound/AI/shuttledock.ogg', "Priority")
			else
				priority_announce("All hostile activity within station systems have ceased.","Network Alert")

			if(get_security_level() == "delta")
				set_security_level("red")

		gang.message_gangtools("Hostile takeover cancelled: Dominator is no longer operational.[gang.dom_attempts ? " You have [gang.dom_attempts] attempt remaining." : " The station network will have likely blocked any more attempts by us."]",1,1)

	SetLuminosity(0)
	icon_state = "dominator-broken"
	overlays.Cut()
	operating = -1
	SSmachine.processing -= src

/obj/machinery/dominator/Destroy()
	if(operating != -1)
		set_broken()
	poi_list.Remove(src)
	return ..()

/obj/machinery/dominator/emp_act(severity)
	healthcheck(100)
	..()

/obj/machinery/dominator/ex_act(severity, target)
	if(target == src)
		qdel(src)
		return
	switch(severity)
		if(1)
			qdel(src)
		if(2)
			healthcheck(120)
		if(3)
			healthcheck(30)
	return

/obj/machinery/dominator/bullet_act(obj/item/projectile/Proj)
	if(Proj.damage)
		if((Proj.damage_type == BRUTE || Proj.damage_type == BURN))
			var/damage = Proj.damage
			if(Proj.forcedodge)
				damage *= 0.5
			playsound(src, 'sound/effects/bang.ogg', 50, 1)
			visible_message("[src] was hit by [Proj].")
			healthcheck(damage)
	..()

/obj/machinery/dominator/blob_act()
	healthcheck(110)

/obj/machinery/dominator/attackby(obj/I, mob/user, params)

	return

/obj/machinery/dominator/attack_hand(mob/user)
	if(operating)
		examine(user)
		return

	var/datum/gang/tempgang

	if(user.mind in ticker.mode.get_all_gangsters())
		tempgang = user.mind.gang_datum
	else
		examine(user)
		return

	if(isnum(tempgang.dom_timer))
		user << "Error: Hostile Takeover is already in progress."
		return

	if(!tempgang.dom_attempts)
		user << "Error: Unable to breach station network. Firewall has logged our signature and is blocking all further attempts."
		return

	var/time = round(get_domination_time(tempgang)/60,0.1)
	if(alert(user,"With [round((tempgang.territory.len/start_state.num_territories)*100, 1)]% station control, a takeover will require [time] minutes.\nYour gang will be unable to gain influence while it is active.\nThe entire station will likely be alerted to it once it starts.\nYou have [tempgang.dom_attempts] attempt(s) remaining. Are you ready?","Confirm","Ready","Later") == "Ready")
		if (isnum(tempgang.dom_timer) || !tempgang.dom_attempts || !in_range(src, user) || !istype(src.loc, /turf))
			return 0

		var/area/A = get_area(loc)
		var/locname = initial(A.name)

		gang = tempgang
		gang.dom_attempts --
		priority_announce("Network breach detected in [locname]. The [gang.name] Gang is attempting to seize control of the station!","Network Alert")
		gang.domination()
		src.name = "[gang.name] Gang [src.name]"
		healthcheck(0)
		operating = 1
		SSmachine.processing += src

		gang.message_gangtools("Hostile takeover in progress: Estimated [time] minutes until victory.[gang.dom_attempts ? "" : " This is your final attempt."]")
		for(var/datum/gang/G in ticker.mode.gangs)
			if(G != gang)
				G.message_gangtools("Enemy takeover attempt detected in [locname]: Estimated [time] minutes until our defeat.",1,1)

/obj/machinery/dominator/attack_alien(mob/living/user)
	user.do_attack_animation(src)
	playsound(src, 'sound/effects/bang.ogg', 50, 1)
	user.visible_message("[user] smashes against [src] with its claws.",\
	"You smash against [src] with your claws.",\
	"You hear metal scraping.")
	healthcheck(15)

/obj/machinery/dominator/attack_animal(mob/living/user)
	if(!isanimal(user))
		return
	var/mob/living/simple_animal/M = user
	M.do_attack_animation(src)
	if(M.melee_damage_upper <= 0)
		return
	healthcheck(M.melee_damage_upper)

/obj/machinery/dominator/mech_melee_attack(obj/mecha/M)
	if(M.damtype == "brute")
		playsound(src, 'sound/effects/bang.ogg', 50, 1)
		visible_message("[M.name] has hit [src].")
		healthcheck(M.force)
	return

/obj/machinery/dominator/attack_hulk(mob/user)
	playsound(src, 'sound/effects/bang.ogg', 50, 1)
	user.visible_message("[user] smashes [src].",\
	"You punch [src].",\
	"You hear metal being slammed.")
	healthcheck(5)

/obj/machinery/dominator/attackby(obj/item/weapon/I, mob/living/user, params)
	if(istype(I, /obj/item/weapon))
		add_fingerprint(user)
		user.changeNext_move(CLICK_CD_MELEE)
		user.do_attack_animation(src)
		if( (I.flags&NOBLUDGEON) || !I.force )
			return
		playsound(src, 'sound/weapons/smash.ogg', 50, 1)
		visible_message("[user] has hit \the [src] with [I].")
		if(I.damtype == BURN || I.damtype == BRUTE)
			healthcheck(I.force)
		return

license: mit


code:
//gang.dm
//Gang War Game Mode

var/list/gang_name_pool = list("Clandestine", "Prima", "Zero-G", "Max", "Blasto", "Waffle", "North", "Omni", "Newton", "Cyber", "Donk", "Gene", "Gib", "Tunnel", "Diablo", "Psyke", "Osiron", "Sirius", "Sleeping Carp")
var/list/gang_colors_pool = list("red","orange","yellow","green","blue","purple")

/datum/game_mode
	var/list/datum/gang/gangs = list()
	var/datum/gang_points/gang_points

/proc/is_gangster(var/mob/living/M)
	return istype(M) && M.mind && M.mind.gang_datum

/proc/is_in_gang(var/mob/living/M, var/gang_type)
	if(!is_gangster(M) || !gang_type)
		return 0
	var/datum/gang/G = M.mind.gang_datum
	if(G.name == gang_type)
		return 1
	return 0

/datum/game_mode/gang
	name = "gang war"
	config_tag = "gang"
	antag_flag = ROLE_GANG
	restricted_jobs = list("Security Officer", "Warden", "Detective", "AI", "Cyborg","Captain", "Head of Personnel", "Head of Security", "Chief Engineer", "Research Director", "Chief Medical Officer")
	required_players = 20
	required_enemies = 2
	recommended_enemies = 2
	enemy_minimum_age = 14

///////////////////////////
//Announces the game type//
///////////////////////////
/datum/game_mode/gang/announce()
	world << "The current game mode is - Gang War!"
	world << "A violent turf war has erupted on the station!
Gangsters -  Take over the station by activating and defending a Dominator!
Crew - The gangs will try to keep you on the station. Successfully evacuate the station to win!"

///////////////////////////////////////////////////////////////////////////////
//Gets the round setup, cancelling if there's not enough players at the start//
///////////////////////////////////////////////////////////////////////////////
/datum/game_mode/gang/pre_setup()
	if(config.protect_roles_from_antagonist)
		restricted_jobs += protected_jobs

	if(config.protect_assistant_from_antagonist)
		restricted_jobs += "Assistant"

	//Spawn more bosses depending on server population
	var/gangs_to_create = 2
	if(prob(num_players() * 2))
		gangs_to_create ++

	for(var/i=1 to gangs_to_create)
		if(!antag_candidates.len)
			break

		//Create the gang
		var/datum/gang/G = new()
		gangs += G

		//Now assign a boss for the gang
		var/datum/mind/boss = pick(antag_candidates)
		antag_candidates -= boss
		G.bosses += boss
		boss.gang_datum = G
		boss.special_role = "[G.name] Gang Boss"
		boss.restricted_roles = restricted_jobs
		log_game("[boss.key] has been selected as the Boss for the [G.name] Gang")

	if(gangs.len < 2) //Need at least two gangs
		return 0

	return 1

/datum/game_mode/gang/post_setup()
	spawn(rand(10,100))
		for(var/datum/gang/G in gangs)
			for(var/datum/mind/boss_mind in G.bosses)
				G.add_gang_hud(boss_mind)
				forge_gang_objectives(boss_mind)
				greet_gang(boss_mind)
				equip_gang(boss_mind.current,G)
				modePlayer += boss_mind
	..()

/datum/game_mode/proc/forge_gang_objectives(datum/mind/boss_mind)
	var/datum/objective/rival_obj = new
	rival_obj.owner = boss_mind
	rival_obj.explanation_text = "Be the first gang to successfully takeover the station with a Dominator."
	boss_mind.objectives += rival_obj

/datum/game_mode/proc/greet_gang(datum/mind/boss_mind, you_are=1)
	var/obj_count = 1
	if (you_are)
		boss_mind.current << "You are the Boss of the [boss_mind.gang_datum.name] Gang!"
	for(var/datum/objective/objective in boss_mind.objectives)
		boss_mind.current << "Objective #[obj_count]: [objective.explanation_text]"
		obj_count++

///////////////////////////////////////////////////////////////////////////
//This equips the bosses with their gear, and makes the clown not clumsy//
///////////////////////////////////////////////////////////////////////////
/datum/game_mode/proc/equip_gang(mob/living/carbon/human/mob, gang)
	if(!istype(mob))
		return

	if (mob.mind)
		if (mob.mind.assigned_role == "Clown")
			mob << "Your training has allowed you to overcome your clownish nature, allowing you to wield weapons without harming yourself."
			mob.dna.remove_mutation(CLOWNMUT)

	var/obj/item/device/gangtool/gangtool = new(mob)
	var/obj/item/weapon/pen/gang/T = new(mob)
	var/obj/item/toy/crayon/spraycan/gang/SC = new(mob,gang)
	var/obj/item/clothing/glasses/hud/security/chameleon/C = new(mob,gang)

	var/list/slots = list (
		"backpack" = slot_in_backpack,
		"left pocket" = slot_l_store,
		"right pocket" = slot_r_store,
		"left hand" = slot_l_hand,
		"right hand" = slot_r_hand,
	)

	. = 0

	var/where = mob.equip_in_one_of_slots(gangtool, slots)
	if (!where)
		mob << "Your Syndicate benefactors were unfortunately unable to get you a Gangtool."
		. += 1
	else
		gangtool.register_device(mob)
		mob << "The Gangtool in your [where] will allow you to purchase weapons and equipment, send messages to your gang, and recall the emergency shuttle from anywhere on the station."
		mob << "As the gang boss, you can also promote your gang members to lieutenant. Unlike regular gangsters, Lieutenants cannot be deconverted and are able to use recruitment pens and gangtools."

	var/where2 = mob.equip_in_one_of_slots(T, slots)
	if (!where2)
		mob << "Your Syndicate benefactors were unfortunately unable to get you a recruitment pen to start."
		. += 1
	else
		mob << "The recruitment pen in your [where2] will help you get your gang started. Stab unsuspecting crew members with it to recruit them."

	var/where3 = mob.equip_in_one_of_slots(SC, slots)
	if (!where3)
		mob << "Your Syndicate benefactors were unfortunately unable to get you a territory spraycan to start."
		. += 1
	else
		mob << "The territory spraycan in your [where3] can be used to claim areas of the station for your gang. The more territory your gang controls, the more influence you get. All gangsters can use these, so distribute them to grow your influence faster."

	var/where4 = mob.equip_in_one_of_slots(C, slots)
	if (!where4)
		mob << "Your Syndicate benefactors were unfortunately unable to get you a chameleon security HUD."
		. += 1
	else
		mob << "The chameleon security HUD in your [where4] will help you keep track of who is loyalty-implanted, and unable to be recruited."
	mob.update_icons()
	return .

///////////////////////////////////////////
//Deals with converting players to a gang//
///////////////////////////////////////////
/datum/game_mode/proc/add_gangster(datum/mind/gangster_mind, datum/gang/G, check = 1)
	if(!G || (gangster_mind in get_all_gangsters()))
		return 0
	if(check && isloyal(gangster_mind.current)) //Check to see if the potential gangster is implanted
		return 1
	G.gangsters += gangster_mind
	gangster_mind.gang_datum = G
	if(check)
		if(iscarbon(gangster_mind.current))
			var/mob/living/carbon/carbon_mob = gangster_mind.current
			carbon_mob.silent = max(carbon_mob.silent, 5)
			carbon_mob.flash_eyes(1, 1)
		gangster_mind.current.Stun(5)
	gangster_mind.current << "You are now a member of the [G.name] Gang!"
	gangster_mind.current << "Help your bosses take over the station by claiming territory with special spraycans only they can provide. Simply spray on any unclaimed area of the station."
	gangster_mind.current << "Their ultimate objective is to take over the station with a Dominator machine."
	gangster_mind.current << "You can identify your bosses by their red \[G\] icon."
	gangster_mind.current.attack_log += "\[[time_stamp()]\] Has been converted to the [G.name] Gang!"
	gangster_mind.special_role = "[G.name] Gangster"
	G.add_gang_hud(gangster_mind)
	if(jobban_isbanned(gangster_mind.current, ROLE_GANG))
		replace_jobbaned_player(gangster_mind.current, ROLE_GANG, ROLE_GANG)
	return 2
////////////////////////////////////////////////////////////////////
//Deals with players reverting to neutral (Not a gangster anymore)//
////////////////////////////////////////////////////////////////////
/datum/game_mode/proc/remove_gangster(datum/mind/gangster_mind, beingborged, silent, remove_bosses=0)
	var/datum/gang/gang = gangster_mind.gang_datum
	if(!gang)
		return 0

	var/removed

	for(var/datum/gang/G in gangs)
		if(gangster_mind in G.gangsters)
			G.gangsters -= gangster_mind
			removed = 1
		if(remove_bosses && (gangster_mind in G.bosses))
			G.bosses -= gangster_mind
			removed = 1

	if(!removed)
		return 0

	gangster_mind.special_role = null
	gangster_mind.gang_datum = null

	if(silent < 2)
		gangster_mind.current.attack_log += "\[[time_stamp()]\] Has reformed and defected from the [gang.name] Gang!"

		if(beingborged)
			if(!silent)
				gangster_mind.current.visible_message("The frame beeps contentedly from the MMI before initalizing it.")
			gangster_mind.current << "The frame's firmware detects and deletes your criminal behavior! You are no longer a gangster!"
			message_admins("[key_name_admin(gangster_mind.current)] ? (FLW) has been borged while being a member of the [gang.name] Gang. They are no longer a gangster.")
		else
			if(!silent)
				gangster_mind.current.Paralyse(5)
				gangster_mind.current.visible_message("[gangster_mind.current] looks like they've given up the life of crime!")
			gangster_mind.current << "You have been reformed! You are no longer a gangster!
You try as hard as you can, but you can't seem to recall any of the identities of your former gangsters..."

	gang.remove_gang_hud(gangster_mind)
	return 1

////////////////
//Helper Procs//
////////////////

/datum/game_mode/proc/get_all_gangsters()
	var/list/all_gangsters = list()
	all_gangsters += get_gangsters()
	all_gangsters += get_gang_bosses()
	return all_gangsters

/datum/game_mode/proc/get_gangsters()
	var/list/gangsters = list()
	for(var/datum/gang/G in gangs)
		gangsters += G.gangsters
	return gangsters

/datum/game_mode/proc/get_gang_bosses()
	var/list/gang_bosses = list()
	for(var/datum/gang/G in gangs)
		gang_bosses += G.bosses
	return gang_bosses

/proc/get_domination_time(var/datum/gang/G)
	return max(180,900 - (round((G.territory.len/start_state.num_territories)*100, 1) * 12))

//////////////////////////////////////////////////////////////////////
//Announces the end of the game with all relavent information stated//
//////////////////////////////////////////////////////////////////////

/datum/game_mode/proc/auto_declare_completion_gang(datum/gang/winner)
	if(gangs.len)
		if(!winner)
			world << "The station was [station_was_nuked ? "destroyed!" : "evacuated before a gang could claim it! The station wins!"]
"
		else
			world << "The [winner.name] Gang successfully performed a hostile takeover of the station!
"

	for(var/datum/gang/G in gangs)
		var/text = "The [G.name] Gang was [winner==G ? "victorious" : "defeated"] with [round((G.territory.len/start_state.num_territories)*100, 1)]% control of the station!"
		text += "
The [G.name] Gang Bosses were:"
		for(var/datum/mind/boss in G.bosses)
			text += printplayer(boss, 1)
		text += "
The [G.name] Gangsters were:"
		for(var/datum/mind/gangster in G.gangsters)
			text += printplayer(gangster, 1)
		text += "
"
		world << text

//////////////////////////////////////////////////////////
//Handles influence, territories, and the victory checks//
//////////////////////////////////////////////////////////

/datum/gang_points
	var/next_point_interval = 1800
	var/next_point_time

/datum/gang_points/New()
	next_point_time = world.time + next_point_interval
	SSobj.processing += src

/datum/gang_points/process(seconds)
	var/list/winners = list() //stores the winners if there are any

	for(var/datum/gang/G in ticker.mode.gangs)
		if(world.time > next_point_time)
			G.income()

		if(isnum(G.dom_timer))
			G.dom_timer -= seconds/10
			if(G.dom_timer < 0)
				winners += G

	if(world.time > next_point_time)
		next_point_time = world.time + next_point_interval

	if(winners.len)
		if(winners.len > 1) //Edge Case: If more than one dominator complete at the same time
			for(var/datum/gang/G in winners)
				G.domination(0.5)
			priority_announce("Multiple station takeover attempts have made simultaneously. Conflicting takeover attempts appears to have restarted.","Network Alert")
		else
			ticker.mode.explosion_in_progress = 1
			ticker.station_explosion_cinematic(1)
			ticker.mode.explosion_in_progress = 0
			ticker.force_ending = pick(winners)


code:
//gang_datum.dm
//Datum-based gangs

/datum/gang
	var/name = "ERROR"
	var/color = "white"
	var/color_hex = "#FFFFFF"
	var/list/datum/mind/gangsters = list() //gang B Members
	var/list/datum/mind/bosses = list() //gang A Bosses
	var/list/obj/item/device/gangtool/gangtools = list()
	var/style
	var/fighting_style = "normal"
	var/list/territory = list()
	var/list/territory_new = list()
	var/list/territory_lost = list()
	var/dom_timer = "OFFLINE"
	var/dom_attempts = 2
	var/points = 15
	var/datum/atom_hud/antag/ganghud

/datum/gang/New(loc,gangname)
	if(!gang_colors_pool.len)
		message_admins("WARNING: Maximum number of gangs have been exceeded!")
		throw EXCEPTION("Maximum number of gangs has been exceeded")
		return
	else
		color = pick(gang_colors_pool)
		gang_colors_pool -= color
		switch(color)
			if("red")
				color_hex = "#DA0000"
			if("orange")
				color_hex = "#FF9300"
			if("yellow")
				color_hex = "#FFF200"
			if("green")
				color_hex = "#A8E61D"
			if("blue")
				color_hex = "#00B7EF"
			if("purple")
				color_hex = "#DA00FF"

	name = (gangname ? gangname : pick(gang_name_pool))
	gang_name_pool -= name

	ganghud = new()
	log_game("The [name] Gang has been created. Their gang color is [color].")

/datum/gang/proc/add_gang_hud(datum/mind/recruit_mind)
	ganghud.join_hud(recruit_mind.current)
	ticker.mode.set_antag_hud(recruit_mind.current, ((recruit_mind in bosses) ? "gang_boss" : "gangster"))

/datum/gang/proc/remove_gang_hud(datum/mind/defector_mind)
	ganghud.leave_hud(defector_mind.current)
	ticker.mode.set_antag_hud(defector_mind.current, null)

/datum/gang/proc/domination(modifier=1)
	dom_timer = get_domination_time(src) * modifier
	set_security_level("delta")
	SSshuttle.emergencyNoEscape = 1

//////////////////////////////////////////// OUTFITS

//Used by recallers when purchasing a gang outfit. First time a gang outfit is purchased the buyer decides a gang style which is stored so gang outfits are uniform
/datum/gang/proc/gang_outfit(mob/living/carbon/user,obj/item/device/gangtool/gangtool)
	if(!user || !gangtool)
		return 0
	if(!gangtool.can_use(user))
		return 0

	var/gang_style_list = list("Gang Colors","Black Suits","White Suits","Leather Jackets","Leather Overcoats","Puffer Jackets","Military Jackets","Tactical Turtlenecks","Soviet Uniforms")
	if(!style && (user.mind in ticker.mode.get_gang_bosses()))	//Only the boss gets to pick a style
		style = input("Pick an outfit style.", "Pick Style") as null|anything in gang_style_list

	if(gangtool.can_use(user) && (gangtool.outfits >= 1))
		var/outfit_path
		switch(style)
			if(null || "Gang Colors")
				outfit_path = text2path("/obj/item/clothing/under/color/[color]")
			if("Black Suits")
				outfit_path = /obj/item/clothing/under/suit_jacket/charcoal
			if("White Suits")
				outfit_path = /obj/item/clothing/under/suit_jacket/white
			if("Puffer Jackets")
				outfit_path = /obj/item/clothing/suit/jacket/puffer
			if("Leather Jackets")
				outfit_path = /obj/item/clothing/suit/jacket/leather
			if("Leather Overcoats")
				outfit_path = /obj/item/clothing/suit/jacket/leather/overcoat
			if("Military Jackets")
				outfit_path = /obj/item/clothing/suit/jacket/miljacket
			if("Soviet Uniforms")
				outfit_path = /obj/item/clothing/under/soviet
			if("Tactical Turtlenecks")
				outfit_path = /obj/item/clothing/under/syndicate

		if(outfit_path)
			var/obj/item/clothing/outfit = new outfit_path(user.loc)
			outfit.armor = list(melee = 20, bullet = 30, laser = 10, energy = 10, bomb = 20, bio = 0, rad = 0)
			outfit.desc += " Tailored for the [name] Gang to offer the wearer moderate protection against ballistics and physical trauma."
			outfit.gang = src
			user.put_in_hands(outfit)
			return 1

	return 0

//////////////////////////////////////////// MESSAGING

/datum/gang/proc/message_gangtools(message,beep=1,warning)
	if(!gangtools.len || !message)
		return
	for(var/obj/item/device/gangtool/tool in gangtools)
		var/mob/living/mob = get(tool.loc,/mob/living)
		if(mob && mob.mind && mob.stat == CONSCIOUS)
			if(mob.mind.gang_datum == src)
				mob << "\icon[tool] [message]"
				if(beep)
					playsound(mob.loc, 'sound/machines/twobeep.ogg', 50, 1)

//////////////////////////////////////////// INCOME

/datum/gang/proc/income()
	if(!bosses.len)
		return

	var/added_names = ""
	var/lost_names = ""

	//Re-add territories that were reclaimed, so if they got tagged over, they can still earn income if they tag it back before the next status report
	var/list/reclaimed_territories = territory_new & territory_lost
	territory |= reclaimed_territories
	territory_new -= reclaimed_territories
	territory_lost -= reclaimed_territories

	//Process lost territories
	for(var/area in territory_lost)
		if(lost_names != "")
			lost_names += ", "
		lost_names += "[territory_lost[area]]"
		territory -= area

	//Count uniformed gangsters
	var/uniformed = 0
	for(var/datum/mind/gangmind in (gangsters|bosses))
		if(ishuman(gangmind.current))
			var/mob/living/carbon/human/gangster = gangmind.current
			//Gangster must be alive and on station
			if((gangster.stat == DEAD) || (gangster.z > ZLEVEL_STATION))
				continue

			var/obj/item/clothing/outfit
			var/obj/item/clothing/gang_outfit
			if(gangster.w_uniform)
				outfit = gangster.w_uniform
				if(outfit.gang == src)
					gang_outfit = outfit
			if(gangster.wear_suit)
				outfit = gangster.wear_suit
				if(outfit.gang == src)
					gang_outfit = outfit

			if(gang_outfit)
				gangster << "The [src] Gang's influence grows as you wear [gang_outfit]."
				uniformed ++

	//Calculate and report influence growth
	var/message = "[src] Gang Status Report:
*---------*
"
	if(isnum(dom_timer))
		var/new_time = max(180,dom_timer - (uniformed * 4) - (territory.len * 2))
		if(new_time < dom_timer)
			message += "Takeover shortened by [dom_timer - new_time] seconds for defending [territory.len] territories and [uniformed] uniformed gangsters.
"
			dom_timer = new_time
		message += "[dom_timer] seconds remain in hostile takeover.
"
	else
		var/points_new = min(999,points + 15 + (uniformed * 2) + territory.len)
		if(points_new != points)
			message += "Gang influence has increased by [points_new - points] for defending [territory.len] territories and [uniformed] uniformed gangsters.
"
		points = points_new
		message += "Your gang now has [points] influence.
"

	//Process new territories
	for(var/area in territory_new)
		if(added_names != "")
			added_names += ", "
		added_names += "[territory_new[area]]"
		territory += area

	//Report territory changes
	message += "[territory_new.len] new territories:
[added_names]
"
	message += "[territory_lost.len] territories lost:
[lost_names]
"

	//Clear the lists
	territory_new = list()
	territory_lost = list()

	var/control = round((territory.len/start_state.num_territories)*100, 1)
	message += "Your gang now has [control]% control of the station.
*---------*"
	message_gangtools(message)

	//Increase outfit stock
	for(var/obj/item/device/gangtool/tool in gangtools)
		tool.outfits = min(tool.outfits+1,5)


code:
/*
 * Gang Boss Pens
 */
/obj/item/weapon/pen/gang
	origin_tech = "materials=2;syndicate=5"
	var/cooldown
	var/last_used = 0
	var/charges = 1

/obj/item/weapon/pen/gang/New()
	..()
	last_used = world.time

/obj/item/weapon/pen/gang/attack(mob/living/M, mob/user)
	if(!istype(M))
		return
	if(ishuman(M) && ishuman(user) && M.stat != DEAD)
		if(user.mind && (user.mind in ticker.mode.get_gang_bosses()))
			if(..(M,user,1))
				if(cooldown)
					user << "[src] needs more time to recharge before it can be used."
					return
				if(M.client)
					M.mind_initialize()		//give them a mind datum if they don't have one.
					var/datum/gang/G = user.mind.gang_datum
					var/recruitable = ticker.mode.add_gangster(M.mind,G)
					switch(recruitable)
						if(2)
							M.Paralyse(5)
							cooldown(G)
						if(1)
							user << "This mind is resistant to recruitment!"
						else
							user << "This mind has already been recruited into a gang!"
			return
	..()

/obj/item/weapon/pen/gang/proc/cooldown(datum/gang/gang)
	var/cooldown_time = 600+(600*gang.bosses.len) // 1recruiter=2mins, 2recruiters=3mins, 3recruiters=4mins

	cooldown = 1
	icon_state = "pen_blink"

	var/time_passed = world.time - last_used
	var/time
	for(time=time_passed, time>=cooldown_time, time-=cooldown_time) //get 1 charge every cooldown interval
		charges++

	charges = max(0,charges-1)

	last_used = world.time - time

	if(charges)
		cooldown_time = 50
	spawn(cooldown_time)
		cooldown = 0
		icon_state = "pen"
		var/mob/M = get(src, /mob)
		M << "\icon[src] [src][(src.loc == M)?(""):(" in your [src.loc]")] vibrates softly. It is ready to be used again."

//////////////
// IMPLANTS //
//////////////

/obj/item/weapon/implant/gang
	name = "gang implant"
	desc = "Makes you a gangster or such."
	activated = 0
	origin_tech = "materials=2;biotech=4;programming=4;syndicate=4"
	var/datum/gang/gang

/obj/item/weapon/implant/gang/New(loc,var/setgang)
	..()
	gang = setgang

/obj/item/weapon/implant/gang/get_data()
	var/dat = {"Implant Specifications:

				Name: Criminal Loyalty Implant

				Life: A few seconds after injection.

				Important Notes: Illegal

				Implant Details:

				Function: Contains a small pod of nanobots that change the host's brain to be loyal to a certain organization.

				Special Features: This device will also emit a small EMP pulse, destroying any other implants within the host's brain.

				Integrity: Implant's EMP function will destroy itself in the process."}
	return dat

/obj/item/weapon/implant/gang/implant(mob/target)
	if(..())
		for(var/obj/item/weapon/implant/I in target)
			if(I != src)
				qdel(I)

		if(!target.mind || target.stat == DEAD)
			return 0

		var/success
		if(target.mind in ticker.mode.get_gangsters())
			if(ticker.mode.remove_gangster(target.mind,0,1))
				success = 1	//Was not a gang boss, convert as usual
		else
			success = 1

		if(ishuman(target))
			if(!success)
				target.visible_message("[target] seems to resist the implant!", "You feel the influence of your enemies try to invade your mind!")

		qdel(src)
		return -1

/obj/item/weapon/implanter/gang
	name = "implanter (gang)"

/obj/item/weapon/implanter/gang/New(loc, var/gang)
	if(!gang)
		qdel(src)
		return
	imp = new /obj/item/weapon/implant/gang(src,gang)
	..()


code:
//gangtool device
/obj/item/device/gangtool
	name = "suspicious device"
	desc = "A strange device of sorts. Hard to really make out what it actually does if you don't know how to operate it."
	icon_state = "gangtool-white"
	item_state = "walkietalkie"
	throwforce = 0
	w_class = 1
	throw_speed = 3
	throw_range = 7
	flags = CONDUCT
	origin_tech = "programming=3;bluespace=2;syndicate=5"
	var/datum/gang/gang //Which gang uses this?
	var/recalling = 0
	var/outfits = 3
	var/free_pen = 0
	var/promotable = 0

/obj/item/device/gangtool/New() //Initialize supply point income if it hasn't already been started
	if(!ticker.mode.gang_points)
		ticker.mode.gang_points = new /datum/gang_points(ticker.mode)

/obj/item/device/gangtool/attack_self(mob/user)
	if (!can_use(user))
		return

	var/dat
	if(!gang)
		dat += "This device is not registered.

"
		if(user.mind in ticker.mode.get_gang_bosses())
			if(promotable && user.mind.gang_datum.bosses.len < 3)
				dat += "Give this device to another member of your organization to use to promote them to Lieutenant.

"
				dat += "If this is meant as a spare device for yourself:
"
			dat += "Register Device as Spare
"
		else if (promotable)
			if(user.mind.gang_datum.bosses.len < 3)
				dat += "You have been selected for a promotion!
"
				dat += "Accept Promotion
"
			else
				dat += "No promotions available: All positions filled.
"
		else
			dat += "This device is not authorized to promote.
"
	else
		if(isnum(gang.dom_timer))
			dat += "Takeover In Progress:
[gang.dom_timer] seconds remain"

		var/isboss = (user.mind == gang.bosses[1])
		var/points = gang.points
		dat += "Registration: [gang.name] Gang [isboss ? "Boss" : "Lieutenant"]
"
		dat += "Organization Size: [gang.gangsters.len + gang.bosses.len] | Station Control: [round((gang.territory.len/start_state.num_territories)*100, 1)]%
"
		dat += "Gang Influence: [points]
"
		dat += "Time until Influence grows: [(points >= 999) ? ("--:--") : (time2text(ticker.mode.gang_points.next_point_time - world.time, "mm:ss"))]
"
		dat += "
"
		dat += "Gangtool Functions:
"

		dat += "Send Message to Gang
"
		if(outfits > 0)
			dat += "Create Armored Gang Outfit
"
		else
			dat += "Create Gang Outfit (Restocking)
"
		if(isboss)
			dat += "Recall Emergency Shuttle
"

		dat += "
"
		dat += "Purchase Weapons:
"

		/////////////////
		// NORMAL GANG //
		/////////////////

		if(gang.fighting_style == "normal")
			dat += "(10 Influence) "
			if(points >= 10)
				dat += "Switchblade
"
			else
				dat += "Switchblade
"

			dat += "(25 Influence) "
			if(points >= 25)
				dat += "10mm Pistol
"
			else
				dat += "10mm Pistol
"

			dat += " ↳(10 Influence) "
			if(points >= 10)
				dat += "10mm Ammo
"
			else
				dat += "10mm Ammo
"

			dat += "(60 Influence) "
			if(points >= 60)
				dat += "Uzi SMG
"
			else
				dat += "Uzi SMG
"

			dat += " ↳(40 Influence) "
			if(points >= 40)
				dat += "Uzi Ammo
"
			else
				dat += "Uzi Ammo
"

			dat += "(1 Influence) "
			if(points >=1)
				dat += "Dope Necklace
"
			else
				dat += "Dope Necklace
"

			dat += "
"

		////////////////////////
		// STANDARD EQUIPMENT //
		////////////////////////

		dat += "Purchase Equipment:
"

		dat += "(5 Influence) "
		if(points >= 5)
			dat += "Territory Spraycan
"
		else
			dat += "Territory Spraycan
"

		dat += "(10 Influence) "
		if(points >= 10)
			dat += "C4 Explosive
"
		else
			dat += "C4 Explosive
"

		dat += "(15 Influence) "
		if(points >= 15)
			dat += "Implant Breaker
"
		else
			dat += "Implant Breaker
"

		if(free_pen)
			dat += "(GET ONE FREE) "
		else
			dat += "(50 Influence) "
		if((points >= 50)||free_pen)
			dat += "Recruitment Pen
"
		else
			dat += "Recruitment Pen
"

		var/gangtooltext = "Spare Gangtool"
		if(isboss && gang.bosses.len < 3)
			gangtooltext = "Promote a Gangster"
		dat += "(10 Influence) "
		if(points >= 10)
			dat += "[gangtooltext]
"
		else
			dat += "[gangtooltext]
"

		if(!gang.dom_attempts)
			dat += "(Out of stock) Station Dominator
"
		else
			dat += "(30 Influence) "
			if(points >= 30)
				dat += "Station Dominator
"
			else
				dat += "Station Dominator
"
			dat += "(Estimated Takeover Time: [round(get_domination_time(gang)/60,0.1)] minutes)
"

	dat += "
"
	dat += "Refresh
"

	var/datum/browser/popup = new(user, "gangtool", "Welcome to GangTool v3.2", 340, 625)
	popup.set_content(dat)
	popup.open()

/obj/item/device/gangtool/Topic(href, href_list)
	if(!can_use(usr))
		return

	add_fingerprint(usr)

	if(href_list["register"])
		register_device(usr)

	else if(!gang) //Gangtool must be registered before you can use the functions below
		return

	if(href_list["purchase"])
		var/pointcost
		var/item_type
		switch(href_list["purchase"])
			if("spraycan")
				if(gang.points >= 5)
					item_type = /obj/item/toy/crayon/spraycan/gang
					pointcost = 5
			if("switchblade")
				if(gang.points >= 10)
					item_type = /obj/item/weapon/switchblade
					pointcost = 10
			if("necklace")
				if(gang.points >=1)
					item_type = /obj/item/clothing/tie/dope_necklace
					pointcost = 1
			if("pistol")
				if(gang.points >= 25)
					item_type = /obj/item/weapon/gun/projectile/automatic/pistol
					pointcost = 25
			if("10mmammo")
				if(gang.points >= 10)
					item_type = /obj/item/ammo_box/magazine/m10mm
					pointcost = 10
			if("uzi")
				if(gang.points >= 60)
					item_type = /obj/item/weapon/gun/projectile/automatic/mini_uzi
					pointcost = 60
			if("9mmammo")
				if(gang.points >= 40)
					item_type = /obj/item/ammo_box/magazine/uzim9mm
					pointcost = 40
			if("scroll")
				if(gang.points >= 30)
					item_type = /obj/item/weapon/sleeping_carp_scroll
					usr << "Anyone who reads the sleeping carp scroll will learn secrets of the sleeping carp martial arts style."
					pointcost = 30
			if("wrestlingbelt")
				if(gang.points >= 20)
					item_type = /obj/item/weapon/storage/belt/champion/wrestling
					usr << "Anyone wearing the wresting belt will know how to be effective with wrestling."
					pointcost = 20
			if("bostaff")
				if(gang.points >= 10)
					item_type = /obj/item/weapon/twohanded/bostaff
					pointcost = 10
			if("C4")
				if(gang.points >= 10)
					item_type = /obj/item/weapon/c4
					pointcost = 10
			if("pen")
				if((gang.points >= 50) || free_pen)
					item_type = /obj/item/weapon/pen/gang
					usr << "More recruitment pens will allow you to recruit gangsters faster. Only gang leaders can recruit with pens."
					if(free_pen)
						free_pen = 0
					else
						pointcost = 50
			if("implant")
				if(gang.points >= 15)
					item_type = /obj/item/weapon/implanter/gang
					usr << "The implant breaker is a single-use device that destroys all implants within the target before trying to recruit them to your gang. Also works on enemy gangsters."
					pointcost = 15
			if("gangtool")
				if(gang.points >= 10)
					if(usr.mind == gang.bosses[1])
						item_type = /obj/item/device/gangtool/spare/lt
						if(gang.bosses.len < 3)
							usr << "Gangtools allow you to promote a gangster to be your Lieutenant, enabling them to recruit and purchase items like you. Simply have them register the gangtool. You may promote up to [3-gang.bosses.len] more Lieutenants"
					else
						item_type = /obj/item/device/gangtool/spare/
					pointcost = 10
			if("dominator")
				if(!gang.dom_attempts)
					return

				var/area/usrarea = get_area(usr.loc)
				var/usrturf = get_turf(usr.loc)
				if(initial(usrarea.name) == "Space" || istype(usrturf,/turf/open/space) || usr.z != 1)
					usr << "You can only use this on the station!"
					return

				for(var/obj/obj in usrturf)
					if(obj.density)
						usr << "There's not enough room here!"
						return

				if(usrarea.type in gang.territory|gang.territory_new)
					if(gang.points >= 30)
						item_type = /obj/machinery/dominator
						usr << "The dominator will secure your gang's dominance over the station. Turn it on when you are ready to defend it."
						pointcost = 30
				else
					usr << "The dominator can be spawned only on territory controlled by your gang!"
					return

		if(item_type)
			gang.points -= pointcost
			if(ispath(item_type))
				var/obj/purchased = new item_type(get_turf(usr),gang)
				var/mob/living/carbon/human/H = usr
				H.put_in_hands(purchased)
				if(pointcost)
					gang.message_gangtools("A [href_list["purchase"]] was purchased by [usr.real_name] for [pointcost] Influence.")
			log_game("A [href_list["purchase"]] was purchased by [key_name(usr)] ([gang.name] Gang) for [pointcost] Influence.")

		else
			usr << "Not enough influence."

	else if(href_list["choice"])
		switch(href_list["choice"])
			if("recall")
				if(usr.mind == gang.bosses[1])
					recall(usr)
			if("outfit")
				if(outfits > 0)
					if(gang.gang_outfit(usr,src))
						usr << "Gang Outfits can act as armor with moderate protection against ballistic and melee attacks. Every gangster wearing one will also help grow your gang's influence."
						outfits -= 1
			if("ping")
				ping_gang(usr)
	attack_self(usr)

/obj/item/device/gangtool/proc/ping_gang(mob/user)
	if(!user)
		return
	var/message = stripped_input(user,"Discreetly send a gang-wide message.","Send Message") as null|text
	if(!message || !can_use(user))
		return
	if(user.z > 2)
		user << "\icon[src]Error: Station out of range."
		return
	var/list/members = list()
	members += gang.gangsters
	members += gang.bosses
	if(members.len)
		var/gang_rank = gang.bosses.Find(user.mind)
		switch(gang_rank)
			if(1)
				gang_rank = "Gang Boss"
			if(2)
				gang_rank = "1st Lieutenant"
			if(3)
				gang_rank = "2nd Lieutenant"
			if(4)
				gang_rank = "3rd Lieutenant"
			else
				gang_rank = "[gang_rank - 1]th Lieutenant"
		var/ping = "[gang.name] [gang_rank]: [message]"
		for(var/datum/mind/ganger in members)
			if(ganger.current && (ganger.current.z <= 2) && (ganger.current.stat == CONSCIOUS))
				ganger.current << ping
		for(var/mob/M in dead_mob_list)
			M << "(F) [ping]"
		log_game("[key_name(user)] Messaged [gang.name] Gang: [message].")

/obj/item/device/gangtool/proc/register_device(mob/user)
	if(gang)	//It's already been registered!
		return
	if((promotable && (user.mind in ticker.mode.get_gangsters())) || (user.mind in ticker.mode.get_gang_bosses()))
		gang = user.mind.gang_datum
		gang.gangtools += src
		icon_state = "gangtool-[gang.color]"
		if(!(user.mind in gang.bosses))
			ticker.mode.remove_gangster(user.mind, 0, 2)
			gang.bosses += user.mind
			user.mind.gang_datum = gang
			user.mind.special_role = "[gang.name] Gang Lieutenant"
			gang.add_gang_hud(user.mind)
			log_game("[key_name(user)] has been promoted to Lieutenant in the [gang.name] Gang")
			free_pen = 1
			gang.message_gangtools("[user] has been promoted to Lieutenant.")
			user << "You have been promoted to Lieutenant!"
			ticker.mode.forge_gang_objectives(user.mind)
			ticker.mode.greet_gang(user.mind,0)
			user << "The Gangtool you registered will allow you to purchase weapons and equipment, and send messages to your gang."
			user << "Unlike regular gangsters, you may use recruitment pens to add recruits to your gang. Use them on unsuspecting crew members to recruit them. Don't forget to get your one free pen from the gangtool."
	else
		usr << "ACCESS DENIED: Unauthorized user."

/obj/item/device/gangtool/proc/recall(mob/user)
	if(!can_use(user))
		return 0

	if(recalling)
		usr << "Error: Recall already in progress."
		return 0

	gang.message_gangtools("[usr] is attempting to recall the emergency shuttle.")
	recalling = 1
	loc << "\icon[src]Generating shuttle recall order with codes retrieved from last call signal..."

	sleep(rand(100,300))

	if(SSshuttle.emergency.mode != SHUTTLE_CALL) //Shuttle can only be recalled when it's moving to the station
		user << "\icon[src]Emergency shuttle cannot be recalled at this time."
		recalling = 0
		return 0
	loc << "\icon[src]Shuttle recall order generated. Accessing station long-range communication arrays..."

	sleep(rand(100,300))

	if(!gang.dom_attempts)
		user << "\icon[src]Error: Unable to access communication arrays. Firewall has logged our signature and is blocking all further attempts."
		recalling = 0
		return 0

	var/turf/userturf = get_turf(user)
	if(userturf.z != 1) //Shuttle can only be recalled while on station
		user << "\icon[src]Error: Device out of range of station communication arrays."
		recalling = 0
		return 0
	var/datum/station_state/end_state = new /datum/station_state()
	end_state.count()
	if((100 *  start_state.score(end_state)) < 80) //Shuttle cannot be recalled if the station is too damaged
		user << "\icon[src]Error: Station communication systems compromised. Unable to establish connection."
		recalling = 0
		return 0
	loc << "\icon[src]Comm arrays accessed. Broadcasting recall signal..."

	sleep(rand(100,300))

	recalling = 0
	log_game("[key_name(user)] has tried to recall the shuttle with a gangtool.")
	message_admins("[key_name_admin(user)] has tried to recall the shuttle with a gangtool.", 1)
	userturf = get_turf(user)
	if(userturf.z == 1) //Check one more time that they are on station.
		if(SSshuttle.cancelEvac(user))
			return 1

	loc << "\icon[src]No response recieved. Emergency shuttle cannot be recalled at this time."
	return 0

/obj/item/device/gangtool/proc/can_use(mob/living/carbon/human/user)
	if(!istype(user))
		return 0
	if(user.restrained() || user.lying || user.stat || user.stunned || user.weakened)
		return 0
	if(!(src in user.contents))
		return 0
	if(!user.mind)
		return 0

	if(gang)	//If it's already registered, only let the gang's bosses use this
		if(user.mind in gang.bosses)
			return 1
	else	//If it's not registered, any gangster can use this to register
		if(user.mind in ticker.mode.get_all_gangsters())
			return 1

	return 0

/obj/item/device/gangtool/spare
	outfits = 1

/obj/item/device/gangtool/spare/lt
	promotable = 1


code:
var/global/list/global_handofgod_traptypes = list()
var/global/list/global_handofgod_structuretypes = list()

#define CONDUIT_RANGE	15

/datum/game_mode
	var/list/datum/mind/red_deities = list()
	var/list/datum/mind/red_deity_prophets = list()
	var/list/datum/mind/red_deity_followers = list()

	var/list/datum/mind/blue_deities = list()
	var/list/datum/mind/blue_deity_prophets = list()
	var/list/datum/mind/blue_deity_followers = list()

	var/list/datum/mind/unassigned_followers = list() //for roundstart team assigning
	var/list/datum/mind/assigned_to_red = list()
	var/list/datum/mind/assigned_to_blue = list()

/datum/game_mode/hand_of_god
	name = "hand of god"
	config_tag = "handofgod"
	antag_flag = ROLE_HOG_CULTIST		//Followers use ROLE_HOG_CULTIST, Gods are picked later on with ROLE_HOG_GOD

	required_players = 25
	required_enemies = 8
	recommended_enemies = 8
	restricted_jobs = list("Chaplain","AI", "Cyborg", "Security Officer", "Warden", "Detective", "Head of Security", "Captain", "Head of Personnel")

/datum/game_mode/hand_of_god/announce()
	world << "The current game mode is - Hand of God!"
	world << "Two cults are onboard the station, seeking to overthrow the other, and anyone who stands in their way."
	world << "Followers - Complete your deity's objectives. Convert crewmembers to your cause by using your deity's nexus. Remember - there is no you, there is only the cult."
	world << "Prophets - Command your cult by the will of your deity.  You are a high-value target, so be careful!"
	world << "Personnel - Do not let any cult succeed in its mission. Loyalty implants and holy water will revert them to neutral, hopefully nonviolent crew."

/////////////
//Pre setup//
/////////////

/datum/game_mode/hand_of_god/pre_setup()
	if(config.protect_roles_from_antagonist)
		restricted_jobs += protected_jobs

	if(config.protect_assistant_from_antagonist)
		restricted_jobs += "Assistant"

	for(var/F in 1 to recommended_enemies)
		if(!antag_candidates.len)
			break
		var/datum/mind/follower = pick_n_take(antag_candidates)
		unassigned_followers += follower
		follower.restricted_roles = restricted_jobs
		log_game("[follower.key] (ckey) has been selected as a follower, however teams have not been decided yet.")

	while(unassigned_followers.len > (required_enemies / 2))
		var/datum/mind/chosen = pick_n_take(unassigned_followers)
		add_hog_follower(chosen,"red")

	while(unassigned_followers.len)
		var/datum/mind/chosen = pick_n_take(unassigned_followers)
		add_hog_follower(chosen,"blue")

	return 1

//////////////
//Post Setup//
//////////////

//Pick a follower to uplift into a god
/datum/game_mode/hand_of_god/post_setup()

	//Find viable red god
	var/list/red_god_possibilities = get_players_for_role(ROLE_HOG_GOD)
	red_god_possibilities &= red_deity_followers //followers only
	if(!red_god_possibilities.len) //No candidates? just pick any follower regardless of prefs
		red_god_possibilities = red_deity_followers

	//Make red god
	var/datum/mind/red_god = pick_n_take(red_god_possibilities)
	if(red_god)
		red_god.current.become_god("red")
		remove_hog_follower(red_god,0)
		add_god(red_god,"red")

	//Find viable blue god
	var/list/blue_god_possibilities = get_players_for_role(ROLE_HOG_GOD)
	blue_god_possibilities &= blue_deity_followers //followers only
	if(!blue_god_possibilities.len) //No candidates? just pick any follower regardless of prefs
		blue_god_possibilities = blue_deity_followers

	//Make blue god
	var/datum/mind/blue_god = pick_n_take(blue_god_possibilities)
	if(blue_god)
		blue_god.current.become_god("blue")
		remove_hog_follower(blue_god,0)
		add_god(blue_god,"blue")

	//Forge objectives
	//This is done here so that both gods exist
	if(red_god)
		ticker.mode.forge_deity_objectives(red_god)
	if(blue_god)
		ticker.mode.forge_deity_objectives(blue_god)

	..()

///////////////////
//Objective Procs//
///////////////////

/datum/game_mode/proc/forge_deity_objectives(datum/mind/deity)
	switch(rand(1,100))
		if(1 to 30)
			var/datum/objective/deicide/deicide = new
			deicide.owner = deity
			if(deicide.find_target())//Hard to kill the other god if there is none
				deity.objectives += deicide

			if(!(locate(/datum/objective/escape_followers) in deity.objectives))
				var/datum/objective/escape_followers/recruit = new
				recruit.owner = deity
				deity.objectives += recruit
				recruit.gen_amount_goal(8, 12)

		if(31 to 60)
			var/datum/objective/sacrifice_prophet/sacrifice = new
			sacrifice.owner = deity
			deity.objectives += sacrifice

			if(!(locate(/datum/objective/escape_followers) in deity.objectives))
				var/datum/objective/escape_followers/recruit = new
				recruit.owner = deity
				deity.objectives += recruit
				recruit.gen_amount_goal(8, 12)

		if(61 to 85)
			var/datum/objective/build/build = new
			build.owner = deity
			deity.objectives += build
			build.gen_amount_goal(8, 16)

			var/datum/objective/sacrifice_prophet/sacrifice = new
			sacrifice.owner = deity
			deity.objectives += sacrifice

			if(!(locate(/datum/objective/escape_followers) in deity.objectives))
				var/datum/objective/escape_followers/recruit = new
				recruit.owner = deity
				deity.objectives += recruit
				recruit.gen_amount_goal(8, 12)

		else
			if (!locate(/datum/objective/follower_block) in deity.objectives)
				var/datum/objective/follower_block/block = new
				block.owner = deity
				deity.objectives += block

///////////////
//Greet procs//
///////////////

/datum/game_mode/proc/greet_hog_follower(datum/mind/follower_mind,colour)
	if(follower_mind in blue_deity_prophets || follower_mind in red_deity_prophets)
		follower_mind.current << "You have been appointed as the prophet of the [colour] deity! You are the only one who can communicate with your deity at will. Guide your followers, but be wary, for many will want you dead."
	else if(colour)
		follower_mind.current << "You are a follower of the [colour] cult's deity!"
	else
		follower_mind.current << "You are a follower of a cult's deity!"

/////////////////
//Convert procs//
/////////////////

/datum/game_mode/proc/add_hog_follower(datum/mind/follower_mind, colour = "No Colour")
	var/mob/living/carbon/human/H = follower_mind.current
	if(isloyal(H))
		H << "Your loyalty implant blocked the influence of the [colour] deity. "
		return 0
	if((follower_mind in red_deity_followers) || (follower_mind in red_deity_prophets) || (follower_mind in blue_deity_followers) || (follower_mind in blue_deity_prophets))
		H << "You already belong to a deity. Your strong faith has blocked out the conversion attempt by the followers of the [colour] deity."
		return 0
	var/obj/item/weapon/nullrod/N = H.null_rod_check()
	if(N)
		H << "Your holy weapon prevented the [colour] deity from brainwashing you."
		return 0

	if(colour == "red")
		red_deity_followers += follower_mind
	if(colour == "blue")
		blue_deity_followers += follower_mind

	H.faction |= "[colour] god"
	follower_mind.current << "You are now a follower of the [colour] deity! Follow your deity's prophet in order to complete your deity's objectives. Convert crewmembers to your cause by using your deity's nexus. And remember - there is no you, there is only the cult."
	update_hog_icons_added(follower_mind, colour)
	follower_mind.special_role = "Hand of God: [capitalize(colour)] Follower"
	follower_mind.current.attack_log += "\[[time_stamp()]\] Has been converted to the [colour] follower cult!"
	return 1

/datum/game_mode/proc/add_god(datum/mind/god_mind, colour = "No Colour")
	remove_hog_follower(god_mind, announce = 0)
	if(colour == "red")
		red_deities += god_mind
	if(colour == "blue")
		blue_deities += god_mind
	god_mind.current.attack_log += "\[[time_stamp()]\] Has been made into a [colour] deity!"
	god_mind.special_role = "Hand of God: [colour] God"
	update_hog_icons_added(god_mind, colour)

//////////////////
//Deconvert proc//
//////////////////

/datum/game_mode/proc/remove_hog_follower(datum/mind/follower_mind, announce = 1)//deconverts both
	follower_mind.remove_hog_follower_prophet()
	update_hog_icons_removed(follower_mind,"red")
	update_hog_icons_removed(follower_mind,"blue")

	if(follower_mind.current)
		var/mob/living/carbon/human/H = follower_mind.current
		H.faction -= "red god"
		H.faction -= "blue god"

	if(announce)
		follower_mind.current.attack_log += "\[[time_stamp()]\] Has been deconverted from a deity's cult!"
		follower_mind.current << "Your mind has been cleared from the brainwashing the followers have done to you.  Now you serve yourself and the crew."
		for(var/mob/living/M in view(follower_mind.current))
			M << "[follower_mind.current] looks like their faith is shattered. They're no longer a cultist!"

//////////////////////
// Mob helper procs //
//////////////////////

/proc/is_handofgod_god(A)
	if(istype(A, /mob/camera/god))
		return 1
	return 0

/proc/is_handofgod_bluecultist(A)
	if(ishuman(A))
		var/mob/living/carbon/human/H = A
		if(H.mind)
			if(H.mind in ticker.mode.blue_deity_followers|ticker.mode.blue_deity_prophets)
				return 1
	return 0

/proc/is_handofgod_redcultist(A)
	if(ishuman(A))
		var/mob/living/carbon/human/H = A
		if(H.mind)
			if(H.mind in ticker.mode.red_deity_followers|ticker.mode.red_deity_prophets)
				return 1
	return 0

/proc/is_handofgod_blueprophet(A)
	if(ishuman(A))
		var/mob/living/carbon/human/H = A
		if(H.mind)
			if(H.mind in ticker.mode.blue_deity_prophets)
				return 1
	return 0

/proc/is_handofgod_redprophet(A)
	if(ishuman(A))
		var/mob/living/carbon/human/H = A
		if(H.mind)
			if(H.mind in ticker.mode.red_deity_prophets)
				return 1
	return 0

/proc/is_handofgod_cultist(A) //any of them what so ever, blue, red, hot pink, whatever.
	if(is_handofgod_redcultist(A))
		return 1
	if(is_handofgod_bluecultist(A))
		return 1
	return 0

/proc/is_handofgod_prophet(A) //any of them what so ever, blue, red, hot pink, whatever
	if(ishuman(A))
		var/mob/living/carbon/human/H = A
		if(H.mind)
			if(H.mind in ticker.mode.blue_deity_prophets|ticker.mode.red_deity_prophets)
				return 1
	return 0

/mob/camera/god/proc/is_handofgod_myprophet(A)
	if(!ishuman(A))
		return 0
	var/mob/living/carbon/human/H = A
	if(!H.mind)
		return 0
	if(side == "red")
		if(H.mind in ticker.mode.red_deity_prophets)
			return 1
	else if(side == "blue")
		if(H.mind in ticker.mode.blue_deity_prophets)
			return 1

/mob/camera/god/proc/is_handofgod_myfollowers(mob/A)
	if(!ishuman(A))
		return 0
	var/mob/living/carbon/human/H = A
	if(!H.mind)
		return 0
	if(side == "red")
		if(H.mind in ticker.mode.red_deity_prophets|ticker.mode.red_deity_followers)
			return 1
	else if(side == "blue")
		if(H.mind in ticker.mode.blue_deity_prophets|ticker.mode.blue_deity_followers)
			return 1

//////////////////////
//Roundend Reporting//
//////////////////////

/datum/game_mode/hand_of_god/declare_completion()
	if(red_deities.len)
		var/text = "
The red cult:"
		for(var/datum/mind/red_god in red_deities)
			var/godwin = 1

			text += "
[red_god.key] was the red deity, [red_god.name] ("
			if(red_god.current)
				if(red_god.current.stat == DEAD)
					text += "died"
				else
					text += "survived"
			else
				text += "ceased existing"
			text += ")"
			if(red_deity_prophets.len)
				for(var/datum/mind/red_prophet in red_deity_prophets)
					text += "
The red prophet was [red_prophet.name] ([red_prophet.key])"
			else
				text += "
the red prophet was killed for their beliefs."

			text += "
Red follower count:  [red_deity_followers.len]"
			text += "
Red followers: "
			for(var/datum/mind/player in red_deity_followers)
				text += "[player.name] ([player.key])"

			var/objectives = ""
			if(red_god.objectives.len)
				var/count = 1
				for(var/datum/objective/O in red_god.objectives)
					if(O.check_completion())
						objectives += "
Objective #[count]: [O.explanation_text] Success!"
						feedback_add_details("god_objective","[O.type]|SUCCESS")
					else
						objectives += "
Objective #[count]: [O.explanation_text] Fail."
						feedback_add_details("god_objective","[O.type]|FAIL")
						godwin = 0
					count++

			text += objectives

			if(godwin)
				text += "
The red cult and deity were successful!"
				feedback_add_details("god_success","SUCCESS")
			else
				text += "
The red cult and deity have failed!"
				feedback_add_details("god_success","FAIL")

			text += "
"

		world << text

	if(blue_deities.len)
		var/text = "
The blue cult:"
		for(var/datum/mind/blue_god in blue_deities)
			var/godwin = 1

			text += "
[blue_god.key] was the blue deity, [blue_god.name] ("
			if(blue_god.current)
				if(blue_god.current.stat == DEAD)
					text += "died"
				else
					text += "survived"
			else
				text += "ceased existing"
			text += ")"
			if(blue_deity_prophets.len)
				for(var/datum/mind/blue_prophet in blue_deity_prophets)
					text += "
The blue prophet was [blue_prophet.name] ([blue_prophet.key])"
			else
				text += "
the blue prophet was killed for their beliefs."

			text += "
Blue follower count:  [blue_deity_followers.len]"
			text += "
Blue followers: "
			for(var/datum/mind/player in blue_deity_followers)
				text += "[player.name] ([player.key])"

			var/objectives = ""
			if(blue_god.objectives.len)
				var/count = 1
				for(var/datum/objective/O in blue_god.objectives)
					if(O.check_completion())
						objectives += "
Objective #[count]: [O.explanation_text] Success!"
						feedback_add_details("god_objective","[O.type]|SUCCESS")
					else
						objectives += "
Objective #[count]: [O.explanation_text] Fail."
						feedback_add_details("god_objective","[O.type]|FAIL")
						godwin = 0
					count++

			text += objectives

			if(godwin)
				text += "
The blue cult and deity were successful!"
				feedback_add_details("god_success","SUCCESS")
			else
				text += "
The blue cult and deity have failed!"
				feedback_add_details("god_success","FAIL")

			text += "
"

		world << text

	..()
	return 1

/datum/game_mode/proc/update_hog_icons_added(datum/mind/hog_mind,side)
	var/hud_key
	var/rank = 0
	if(side == "red")
		hud_key = ANTAG_HUD_HOG_RED
		if(is_handofgod_redprophet(hog_mind.current))
			rank = 1

	else if(side == "blue")
		hud_key = ANTAG_HUD_HOG_BLUE
		if(is_handofgod_blueprophet(hog_mind.current))
			rank = 1

	if(is_handofgod_god(hog_mind.current))
		rank = 2

	if(hud_key)
		var/datum/atom_hud/antag/hog_hud = huds[hud_key]
		hog_hud.join_hud(hog_mind.current)
		set_antag_hud(hog_mind.current, "hog-[side]-[rank]")

/datum/game_mode/proc/update_hog_icons_removed(datum/mind/hog_mind,side)
	var/hud_key
	if(side == "red")
		hud_key = ANTAG_HUD_HOG_RED
	else if(side == "blue")
		hud_key = ANTAG_HUD_HOG_BLUE

	if(hud_key)
		var/datum/atom_hud/antag/hog_hud = huds[hud_key]
		hog_hud.leave_hud(hog_mind.current)
		set_antag_hud(hog_mind.current,null)


code:
/datum/action/innate/godspeak
	name = "Godspeak"
	button_icon_state = "godspeak"
	check_flags = AB_CHECK_CONSCIOUS
	var/mob/camera/god/god = null

/datum/action/innate/godspeak/IsAvailable()
	if(..())
		if(god)
			return 1
		return 0

/datum/action/innate/godspeak/Activate()
	var/msg = input(owner,"Speak to your god","Godspeak","") as null|text
	if(!msg)
		return
	god << "[owner]: [msg]"
	owner << "You say: [msg]"

/datum/action/innate/godspeak/Destroy()
	god = null
	return ..()


code:
/mob/camera/god
	name = "deity" //Auto changes to the player's deity name/random name
	real_name = "deity"
	icon = 'icons/mob/mob.dmi'
	icon_state = "marker"
	invisibility = 60
	see_in_dark = 0
	see_invisible = 55
	sight = SEE_TURFS | SEE_MOBS | SEE_OBJS | SEE_SELF
	languages = HUMAN | MONKEY | ALIEN | ROBOT | SLIME | DRONE | SWARMER
	hud_possible = list(ANTAG_HUD)
	mouse_opacity = 0 //can't be clicked

	var/faith = 100 //For initial prophet appointing/stupid purchase
	var/max_faith = 100
	var/side = "neutral" //Red or Blue for the gamemode
	var/obj/structure/divine/nexus/god_nexus = null //The source of the god's power in this realm, kill it and the god is kill
	var/nexus_required = FALSE //If the god dies from losing it's nexus, defaults to off so that gods don't instantly die at roundstart
	var/followers_required = 0 //Same as above
	var/alive_followers = 0
	var/list/structures = list()
	var/list/conduits = list()
	var/prophets_sacrificed_in_name = 0
	var/image/ghostimage = null //For observer with darkness off visiblity
	var/list/prophets = list()
	var/datum/action/innate/godspeak/speak2god

/mob/camera/god/New()
	..()
	update_icons()
	build_hog_construction_lists()

	//Force nexuses after 2 minutes in hand of god mode
	if(ticker && ticker.mode && ticker.mode.name == "hand of god")
		addtimer(src, "forceplacenexus", 1200, FALSE)

//Rebuilds the list based on the gamemode's lists
//As they are the most accurate each tick
/mob/camera/god/proc/get_my_followers()
	switch(side)
		if("red")
			. = ticker.mode.red_deity_followers|ticker.mode.red_deity_prophets
		if("blue")
			. = ticker.mode.blue_deity_followers|ticker.mode.blue_deity_prophets
		else
			. = list()

/mob/camera/god/Destroy()
	var/list/followers = get_my_followers()
	for(var/datum/mind/F in followers)
		if(F.current)
			F.current << "Your god is DEAD!"
	for(var/X in prophets)
		speak2god.Remove(X)
	ghost_darkness_images -= ghostimage
	updateallghostimages()
	return ..()

/mob/camera/god/proc/forceplacenexus()
	if(god_nexus)
		return

	if(ability_cost(0,1,0))
		place_nexus()

	else
		if(blobstart.len) //we're on invalid turf, try to pick from blobstart
			loc = pick(blobstart)
		place_nexus() //if blobstart fails, places on dense turf, but better than nothing
	src << "You failed to place your nexus, and it has been placed for you!"

/mob/camera/god/update_icons()
	icon_state = "[initial(icon_state)]-[side]"

	if(ghostimage)
		ghost_darkness_images -= ghostimage

	ghostimage = image(src.icon,src,src.icon_state)
	ghost_darkness_images |= ghostimage
	updateallghostimages()

/mob/camera/god/Stat()
	..()
	if(statpanel("Status"))
		if(god_nexus)
			stat("Nexus health: ", god_nexus.health)
		stat("Followers: ", alive_followers)
		stat("Faith: ", "[faith]/[max_faith]")

/mob/camera/god/Login()
	..()
	sync_mind()
	src << "You are a deity!"
	src << "You are a deity and are worshipped by a cult!  You are rather weak right now, but that will change as you gain more followers."
	src << "You will need to place an anchor to this world, a Nexus, in two minutes.  If you don't, one will be placed immediately below you."
	src << "Your Follower count determines how many people believe in you and are a part of your cult."
	src << "Your Nexus Integrity tells you the condition of your nexus.  If your nexus is destroyed, you will die. Place your Nexus on a safe, isolated place, that is still accessible to your followers."
	src << "Your Faith is used to interact with the world.  This will regenerate on its own, and it goes faster when you have more followers and power pylons."
	src << "The first thing you should do after placing your nexus is to appoint a prophet.  Only prophets can hear you talk, unless you use an expensive power."
	update_health_hud()

/mob/camera/god/update_health_hud()
	if(god_nexus && hud_used && hud_used.healths)
		hud_used.healths.maptext = "
 [god_nexus.health]
"

/mob/camera/god/proc/add_faith(faith_amt)
	if(faith_amt)
		faith = round(Clamp(faith+faith_amt, 0, max_faith))
		if(hud_used && hud_used.deity_power_display)
			hud_used.deity_power_display.maptext = "
 [faith]
"

/mob/camera/god/proc/place_nexus()
	if(god_nexus || (z != 1))
		return 0

	var/obj/structure/divine/nexus/N = new(get_turf(src))
	N.assign_deity(src)
	god_nexus = N
	nexus_required = TRUE
	verbs -= /mob/camera/god/verb/constructnexus
	//verbs += /mob/camera/god/verb/movenexus //Translocators have no sprite
	update_health_hud()

	var/area/A = get_area(src)
	if(A)
		var/areaname = A.name
		var/list/followers = get_my_followers()
		for(var/datum/mind/F in followers)
			if(F.current)
				F.current << "Your god's nexus is in \the [areaname]"

/mob/camera/god/verb/freeturret()
	set category = "Deity"
	set name = "Free Turret (0)"
	set desc = "Place a single turret, for 0 faith."

	if(!ability_cost(0,1,1))
		return
	var/obj/structure/divine/defensepylon/DP = new(get_turf(src))
	DP.assign_deity(src)
	verbs -= /mob/camera/god/verb/freeturret

/mob/camera/god/proc/update_followers()
	alive_followers = 0
	var/list/all_followers = get_my_followers()
	for(var/datum/mind/F in all_followers)
		if(F.current && F.current.stat != DEAD)
			alive_followers++

	if(hud_used && hud_used.deity_follower_display)
		hud_used.deity_follower_display.maptext = "
 [alive_followers]
"

/mob/camera/god/proc/check_death()
	if(!alive_followers)
		src << "You no longer have any followers. You shudder as you feel your existence cease..."
		if(god_nexus && !qdeleted(god_nexus))
			god_nexus.visible_message("\The [src] suddenly disappears!")
			qdel(god_nexus)
		qdel(src)

/mob/camera/god/say(msg)
	if(!msg)
		return
	if(client)
		if(client.prefs.muted & MUTE_IC)
			src << "You cannot send IC messages (muted)."
			return
		if(src.client.handle_spam_prevention(msg,MUTE_IC))
			return
	if(stat)
		return

	god_speak(msg)

/mob/camera/god/proc/god_speak(msg)
	log_say("Hand of God: [capitalize(side)] God/[key_name(src)] : [msg]")
	msg = trim(copytext(sanitize(msg), 1, MAX_MESSAGE_LEN))
	if(!msg)
		return

	msg = say_quote(msg, get_spans())
	var/rendered = "Divine Telepathy, [name] [msg]"

	for(var/mob/M in mob_list)
		if(is_handofgod_myfollowers(M) || isobserver(M))
			M.show_message(rendered, 2)
	src << rendered

/mob/camera/god/emote(act,m_type = 1 ,msg = null)
	return

/mob/camera/god/Move(NewLoc, Dir = 0)
	loc = NewLoc

/mob/camera/god/Topic(href, href_list)
	if(href_list["create_structure"])
		if(!ability_cost(75,1,1))
			return

		var/obj/structure/divine/construct_type = text2path(href_list["create_structure"]) //it's a path but we need to initial() some vars
		if(!construct_type)
			return

		add_faith(-75)
		var/obj/structure/divine/construction_holder/CH = new(get_turf(src))
		CH.assign_deity(src)
		CH.setup_construction(construct_type)
		CH.visible_message("[src] has created a transparent, unfinished [initial(construct_type.name)]. It can be finished by adding materials.")
		src << "You may click a construction site to cancel it, but only faith is refunded."
		structure_construction_ui(src)
		return

	if(href_list["place_trap"])
		if(!ability_cost(20,1,1))
			return

		var/atom/trap_type = text2path(href_list["place_trap"])
		if(!trap_type)
			return

		src << "You lay \a [initial(trap_type.name)]"
		add_faith(-20)
		new trap_type(get_turf(src))
		return

	..()

/mob/camera/god/proc/structure_construction_ui(mob/camera/god/user)
	var/dat = ""
	for(var/t in global_handofgod_structuretypes)
		if(global_handofgod_structuretypes[t])
			var/obj/structure/divine/apath = global_handofgod_structuretypes[t]
			dat += "[capitalize(t)]
"
			var/imgstate = initial(apath.autocolours) ? "[initial(apath.icon_state)]-[side]" : "[initial(apath.icon_state)]"
			var/icon/I = icon('icons/obj/hand_of_god_structures.dmi',imgstate)
			var/img_component = lowertext(t)
			//I hate byond, but atleast it autocaches these so it's only 1*number_of_structures worth of actual calls
			user << browse_rsc(I,"hog_structure-[img_component].png")
			dat += ""
			dat += "Description: [initial(apath.desc)]
"
			dat += "Construct [capitalize(t)]

"

	var/datum/browser/popup = new(src, "structures","Construct Structure",350,500)
	popup.set_content(dat)
	popup.open()

/mob/camera/god/proc/trap_construction_ui(mob/camera/god/user)
	var/dat = ""
	for(var/t in global_handofgod_traptypes)
		if(global_handofgod_traptypes[t])
			var/obj/structure/divine/trap/T = global_handofgod_traptypes[t]
			dat += "[capitalize(t)]
"
			var/icon/I = icon('icons/obj/hand_of_god_structures.dmi',"[initial(T.icon_state)]")
			var/img_component = lowertext(t)
			user << browse_rsc(I,"hog_trap-[img_component].png")
			dat += ""
			dat += "Description: [initial(T.desc)]
"
			dat += "Place [capitalize(t)]

"

	var/datum/browser/popup = new(src, "traps", "Place Trap",350,500)
	popup.set_content(dat)
	popup.open()


code:
/obj/item/weapon/banner
	name = "banner"
	icon = 'icons/obj/items.dmi'
	icon_state = "banner"
	item_state = "banner"
	desc = "A banner with Nanotrasen's logo on it."
	var/moralecooldown = 0
	var/moralewait = 600

/obj/item/weapon/banner/attack_self(mob/living/carbon/human/user)
	if(moralecooldown + moralewait > world.time)
		return
	var/side = ""
	if(is_handofgod_redcultist(user))
		side = "red"
	else if (is_handofgod_bluecultist(user))
		side = "blue"

	if(!side)
		return
	user << "You increase the morale of your fellows!"
	moralecooldown = world.time

	for(var/mob/living/carbon/human/H in range(4,get_turf(src)))
		if((side == "red") && is_handofgod_redcultist(H) || (side == "blue") && is_handofgod_bluecultist(H))
			H << "Your morale is increased by [user]'s banner!"
			H.adjustBruteLoss(-15)
			H.adjustFireLoss(-15)
			H.AdjustStunned(-2)
			H.AdjustWeakened(-2)
			H.AdjustParalysis(-2)

/obj/item/weapon/banner/red
	name = "red banner"
	icon_state = "banner-red"
	item_state = "banner-red"
	desc = "A banner with the logo of the red deity."

/obj/item/weapon/banner/red/examine(mob/user)
	..()
	if(is_handofgod_redcultist(user))
		user << "A banner representing our might against the heretics. We may use it to increase the morale of our fellow members!"
	else if(is_handofgod_bluecultist(user))
		user << "A heretical banner that should be destroyed posthaste."

/obj/item/weapon/banner/blue
	name = "blue banner"
	icon_state = "banner-blue"
	item_state = "banner-blue"
	desc = "A banner with the logo of the blue deity"

/obj/item/weapon/banner/blue/examine(mob/user)
	..()

	if(is_handofgod_redcultist(user))
		user << "A heretical banner that should be destroyed posthaste."
	else if(is_handofgod_bluecultist(user))
		user << "A banner representing our might against the heretics. We may use it to increase the morale of our fellow members!"

/obj/item/weapon/storage/backpack/bannerpack
	name = "nanotrasen banner backpack"
	desc = "It's a backpack with lots of extra room.  A banner with Nanotrasen's logo is attached, that can't be removed."
	max_combined_w_class = 27 //6 more then normal, for the tradeoff of declaring yourself an antag at all times.
	icon_state = "bannerpack"

/obj/item/weapon/storage/backpack/bannerpack/red
	name = "red banner backpack"
	desc = "It's a backpack with lots of extra room.  A red banner is attached, that can't be removed."
	icon_state = "bannerpack-red"

/obj/item/weapon/storage/backpack/bannerpack/blue
	name = "blue banner backpack"
	desc = "It's a backpack with lots of extra room.  A blue banner is attached, that can't be removed."
	icon_state = "bannerpack-blue"

//this is all part of one item set
/obj/item/clothing/suit/armor/plate/crusader
	name = "Crusader's Armour"
	icon_state = "crusader"
	w_class = 4 //bulky
	slowdown = 2.0 //gotta pretend we're balanced.
	body_parts_covered = CHEST|GROIN|LEGS|FEET|ARMS|HANDS
	armor = list(melee = 50, bullet = 50, laser = 50, energy = 40, bomb = 60, bio = 0, rad = 0)

/obj/item/clothing/suit/armor/plate/crusader/red
	icon_state = "crusader-red"

/obj/item/clothing/suit/armor/plate/crusader/blue
	icon_state = "crusader-blue"

/obj/item/clothing/suit/armor/plate/crusader/examine(mob/user)
	..()
	if(!is_handofgod_cultist(user))
		user << "Armour that's comprised of metal and cloth."
	else
		user << "Armour that was used to protect from backstabs, gunshots, explosives, and lasers.  The original wearers of this type of armour were trying to avoid being murdered.  Since they're not around anymore, you're not sure if they were successful or not."

/obj/item/clothing/head/helmet/plate/crusader
	name = "Crusader's Hood"
	icon_state = "crusader"
	w_class = 3 //normal
	flags_inv = HIDEHAIR|HIDEEARS|HIDEFACE
	armor = list(melee = 50, bullet = 50, laser = 50, energy = 40, bomb = 60, bio = 0, rad = 0)

/obj/item/clothing/head/helmet/plate/crusader/blue
	icon_state = "crusader-blue"

/obj/item/clothing/head/helmet/plate/crusader/red
	icon_state = "crusader-red"

/obj/item/clothing/head/helmet/plate/crusader/examine(mob/user)
	..()
	if(!is_handofgod_cultist(user))
		user << "A brownish hood."
	else
		user << "A hood that's very protective, despite being made of cloth.  Due to the tendency of the wearer to be targeted for assassinations, being protected from being shot in the face was very important.."

//Prophet helmet
/obj/item/clothing/head/helmet/plate/crusader/prophet
	name = "Prophet's Hat"
	alternate_worn_icon = 'icons/mob/large-worn-icons/64x64/head.dmi'
	flags = 0
	armor = list(melee = 60, bullet = 60, laser = 60, energy = 50, bomb = 70, bio = 50, rad = 50) //religion protects you from disease and radiation, honk.
	worn_x_dimension = 64
	worn_y_dimension = 64
	var/side = "neither"

/obj/item/clothing/head/helmet/plate/crusader/prophet/equipped(mob/living/carbon/user, slot)
	var/faithful = 0
	if(slot == slot_head)
		switch(side)
			if("blue")
				faithful = is_handofgod_bluecultist(user)
			if("red")
				faithful = is_handofgod_redcultist(user)
			else
				faithful = 1
		if(!faithful)
			user << "Your mind is assaulted by a vast power, furious at your desecration!"
			user.emote("scream")
			user.adjustFireLoss(10)
			user.unEquip(src)
			user.head = null
			user.update_inv_head()
			src.screen_loc = null
			user.Weaken(1)

/obj/item/clothing/head/helmet/plate/crusader/prophet/red
	icon_state = "prophet-red"
	side = "red"

/obj/item/clothing/head/helmet/plate/crusader/prophet/blue
	icon_state = "prophet-blue"
	side = "blue"

/obj/item/clothing/head/helmet/plate/crusader/prophet/examine(mob/user)
	..()
	if(!is_handofgod_cultist(user))
		user << "A brownish, religious-looking hat."
	else
		user << "A hat bestowed upon a prophet of gods and demigods."
		user << "This hat belongs to the [side] god."

//Structure conversion staff
/obj/item/weapon/godstaff
	name = "godstaff"
	icon_state = "godstaff-red"
	var/mob/camera/god/god = null
	var/staffcooldown = 0
	var/staffwait = 30

/obj/item/weapon/godstaff/examine(mob/user)
	..()
	if(!is_handofgod_cultist(user))
		user << "It's a stick..?"
	else
		user << "A powerful staff capable of changing the allegiance of god/demigod structures."

/obj/item/weapon/godstaff/attack_self(mob/living/carbon/user)
	if((god && !god.is_handofgod_myprophet(user)) || !god)
		user << "YOU ARE NOT THE CHOSEN ONE!"
		return
	if(!(istype(user.head, /obj/item/clothing/head/helmet/plate/crusader/prophet)))
		user << "Your connection to your diety isn't strong enough! You must wear your big hat!"
		return
	if(staffcooldown + staffwait > world.time)
		return
	user.visible_message("[user] chants deeply and waves their staff")
	if(do_after(user, 20,1,src))
		for(var/obj/structure/divine/R in orange(3,user))
			user.say("Grant us true sight my god!")
			if(istype(R, /obj/structure/divine/nexus)|| istype(R, /obj/structure/divine/trap))
				continue
			R.visible_message("[R] suddenly appears!")
			R.invisibility = 0
			R.alpha = initial(R.alpha)
			R.density = initial(R.density)
			R.activate()
	staffcooldown = world.time

/obj/item/weapon/godstaff/red
	icon_state = "godstaff-red"

/obj/item/weapon/godstaff/blue
	icon_state = "godstaff-blue"

/obj/item/clothing/gloves/plate
	name = "Plate Gauntlets"
	icon_state = "crusader"
	siemens_coefficient = 0
	cold_protection = HANDS
	min_cold_protection_temperature = GLOVES_MIN_TEMP_PROTECT
	heat_protection = HANDS
	max_heat_protection_temperature = GLOVES_MAX_TEMP_PROTECT

/obj/item/clothing/gloves/plate/red
	icon_state = "crusader-red"

/obj/item/clothing/gloves/plate/blue
	icon_state = "crusader-blue"

/obj/item/clothing/gloves/plate/examine(mob/user)
	..()
	if(!is_handofgod_cultist(user))
		usr << "They're like gloves, but made of metal."
	else
		usr << "Protective gloves that are also blessed to protect from heat and shock."

/obj/item/clothing/shoes/plate
	name = "Plate Boots"
	icon_state = "crusader"
	w_class = 3 //normal
	armor = list(melee = 50, bullet = 50, laser = 50, energy = 40, bomb = 60, bio = 0, rad = 0) //does this even do anything on boots?
	flags = NOSLIP
	cold_protection = FEET
	min_cold_protection_temperature = SHOES_MIN_TEMP_PROTECT
	heat_protection = FEET
	max_heat_protection_temperature = SHOES_MAX_TEMP_PROTECT

/obj/item/clothing/shoes/plate/red
	icon_state = "crusader-red"

/obj/item/clothing/shoes/plate/blue
	icon_state = "crusader-blue"

/obj/item/clothing/shoes/plate/examine(mob/user)
	..()
	if(!is_handofgod_cultist(user))
		usr << "Metal boots, they look heavy."
	else
		usr << "Heavy boots that are blessed for sure footing.  You'll be safe from being taken down by the heresy that is the banana peel."

/obj/item/weapon/storage/box/itemset/crusader
	name = "Crusader's Armour Set" //i can't into ck2 references
	desc = "This armour is said to be based on the armor of kings on another world thousands of years ago, who tended to assassinate, conspire, and plot against everyone who tried to do the same to them.  Some things never change."

/obj/item/weapon/storage/box/itemset/crusader/blue/New()
	..()
	contents = list()
	sleep(1)
	new /obj/item/clothing/suit/armor/plate/crusader/blue(src)
	new /obj/item/clothing/head/helmet/plate/crusader/blue(src)
	new /obj/item/clothing/gloves/plate/blue(src)
	new /obj/item/clothing/shoes/plate/blue(src)

/obj/item/weapon/storage/box/itemset/crusader/red/New()
	..()
	contents = list()
	sleep(1)
	new /obj/item/clothing/suit/armor/plate/crusader/red(src)
	new /obj/item/clothing/head/helmet/plate/crusader/red(src)
	new /obj/item/clothing/gloves/plate/red(src)
	new /obj/item/clothing/shoes/plate/red(src)

/obj/item/weapon/claymore/hog
	force = 30
	armour_penetration = 15