code:
/*NOTES:
These are general powers. Specific powers are stored under the appropriate alien creature type.
*/

/*Alien spit now works like a taser shot. It won't home in on the target but will act the same once it does hit.
Doesn't work on other aliens/AI.*/

/obj/effect/proc_holder/alien
	name = "Alien Power"
	panel = "Alien"
	var/plasma_cost = 0
	var/check_turf = 0

	var/has_action = 1
	var/datum/action/spell_action/alien/action = null
	var/action_icon = 'icons/mob/actions.dmi'
	var/action_icon_state = "spell_default"
	var/action_background_icon_state = "bg_alien"

/obj/effect/proc_holder/alien/New()
	..()
	action = new(src)

/obj/effect/proc_holder/alien/Click()
	if(!istype(usr,/mob/living/carbon))
		return 1
	var/mob/living/carbon/user = usr
	if(cost_check(check_turf,user))
		if(fire(user) && user) // Second check to prevent runtimes when evolving
			user.adjustPlasma(-plasma_cost)
	return 1

/obj/effect/proc_holder/alien/proc/on_gain(mob/living/carbon/user)
	return

/obj/effect/proc_holder/alien/proc/on_lose(mob/living/carbon/user)
	return

/obj/effect/proc_holder/alien/proc/fire(mob/living/carbon/user)
	return 1

/obj/effect/proc_holder/alien/proc/cost_check(check_turf=0,mob/living/carbon/user,silent = 0)
	if(user.stat)
		if(!silent)
			user << "You must be conscious to do this."
		return 0
	if(user.getPlasma() < plasma_cost)
		if(!silent)
			user << "Not enough plasma stored."
		return 0
	if(check_turf && (!isturf(user.loc) || istype(user.loc, /turf/open/space)))
		if(!silent)
			user << "Bad place for a garden!"
		return 0
	return 1

/obj/effect/proc_holder/alien/plant
	name = "Plant Weeds"
	desc = "Plants some alien weeds"
	plasma_cost = 50
	check_turf = 1
	action_icon_state = "alien_plant"

/obj/effect/proc_holder/alien/plant/fire(mob/living/carbon/user)
	if(locate(/obj/structure/alien/weeds/node) in get_turf(user))
		src << "There's already a weed node here."
		return 0
	user.visible_message("[user] has planted some alien weeds!")
	new/obj/structure/alien/weeds/node(user.loc)
	return 1

/obj/effect/proc_holder/alien/whisper
	name = "Whisper"
	desc = "Whisper to someone"
	plasma_cost = 10
	action_icon_state = "alien_whisper"

/obj/effect/proc_holder/alien/whisper/fire(mob/living/carbon/user)
	var/list/options = list()
	for(var/mob/living/Ms in oview(user))
		options += Ms
	var/mob/living/M = input("Select who to whisper to:","Whisper to?",null) as null|mob in options
	if(!M)
		return 0
	var/msg = sanitize(input("Message:", "Alien Whisper") as text|null)
	if(msg)
		log_say("AlienWhisper: [key_name(user)]->[M.key] : [msg]")
		M << "You hear a strange, alien voice in your head...[msg]"
		user << {"You said: "[msg]" to [M]"}
	else
		return 0
	return 1

/obj/effect/proc_holder/alien/transfer
	name = "Transfer Plasma"
	desc = "Transfer Plasma to another alien"
	plasma_cost = 0
	action_icon_state = "alien_transfer"

/obj/effect/proc_holder/alien/transfer/fire(mob/living/carbon/user)
	var/list/mob/living/carbon/aliens_around = list()
	for(var/mob/living/carbon/A  in oview(user))
		if(A.getorgan(/obj/item/organ/internal/alien/plasmavessel))
			aliens_around.Add(A)
	var/mob/living/carbon/M = input("Select who to transfer to:","Transfer plasma to?",null) as mob in aliens_around
	if(!M)
		return 0
	var/amount = input("Amount:", "Transfer Plasma to [M]") as num
	if (amount)
		amount = min(abs(round(amount)), user.getPlasma())
		if (get_dist(user,M) <= 1)
			M.adjustPlasma(amount)
			user.adjustPlasma(-amount)
			M << "[user] has transfered [amount] plasma to you."
			user << {"You trasfer [amount] plasma to [M]"}
		else
			user << "You need to be closer!"
	return

/obj/effect/proc_holder/alien/acid
	name = "Corrossive Acid"
	desc = "Drench an object in acid, destroying it over time."
	plasma_cost = 200
	action_icon_state = "alien_acid"

/obj/effect/proc_holder/alien/acid/on_gain(mob/living/carbon/user)
	user.verbs.Add(/mob/living/carbon/proc/corrosive_acid)

/obj/effect/proc_holder/alien/acid/on_lose(mob/living/carbon/user)
	user.verbs.Remove(/mob/living/carbon/proc/corrosive_acid)

/obj/effect/proc_holder/alien/acid/proc/corrode(target,mob/living/carbon/user = usr)
	if(target in oview(1,user))
		// OBJ CHECK
		if(isobj(target))
			var/obj/I = target
			if(I.unacidable)	//So the aliens don't destroy energy fields/singularies/other aliens/etc with their acid.
				user << "You cannot dissolve this object."
				return 0
		// TURF CHECK
		else if(istype(target, /turf))
			var/turf/T = target
			// R WALL
			if(istype(T, /turf/closed/wall/r_wall))
				user << "You cannot dissolve this object."
				return 0
			// R FLOOR
			if(istype(T, /turf/open/floor/engine))
				user << "You cannot dissolve this object."
				return 0
		else// Not a type we can acid.
			return 0
		new /obj/effect/acid(get_turf(target), target)
		user.visible_message("[user] vomits globs of vile stuff all over [target]. It begins to sizzle and melt under the bubbling mess of acid!")
		return 1
	else
		src << "Target is too far away."
		return 0

/obj/effect/proc_holder/alien/acid/fire(mob/living/carbon/alien/user)
	var/O = input("Select what to dissolve:","Dissolve",null) as obj|turf in oview(1,user)
	if(!O) return 0
	return corrode(O,user)

/mob/living/carbon/proc/corrosive_acid(O as obj|turf in oview(1)) // right click menu verb ugh
	set name = "Corrossive Acid"

	if(!iscarbon(usr))
		return
	var/mob/living/carbon/user = usr
	var/obj/effect/proc_holder/alien/acid/A = locate() in user.abilities
	if(!A) return
	if(user.getPlasma() > A.plasma_cost && A.corrode(O))
		user.adjustPlasma(-A.plasma_cost)

/obj/effect/proc_holder/alien/neurotoxin
	name = "Spit Neurotoxin"
	desc = "Spits neurotoxin at someone, paralyzing them for a short time."
	plasma_cost = 50
	action_icon_state = "alien_neurotoxin"

/obj/effect/proc_holder/alien/neurotoxin/fire(mob/living/carbon/alien/user)
	user.visible_message("[user] spits neurotoxin!", "You spit neurotoxin.")

	var/turf/T = user.loc
	var/turf/U = get_step(user, user.dir) // Get the tile infront of the move, based on their direction
	if(!isturf(U) || !isturf(T))
		return 0

	var/obj/item/projectile/bullet/neurotoxin/A = new /obj/item/projectile/bullet/neurotoxin(user.loc)
	A.current = U
	A.yo = U.y - T.y
	A.xo = U.x - T.x
	A.fire()

	return 1

/obj/effect/proc_holder/alien/resin
	name = "Secrete Resin"
	desc = "Secrete tough malleable resin."
	plasma_cost = 55
	check_turf = 1
	var/list/structures = list(
		"resin wall" = /obj/structure/alien/resin/wall,
		"resin membrane" = /obj/structure/alien/resin/membrane,
		"resin nest" = /obj/structure/bed/nest)

	action_icon_state = "alien_resin"

/obj/effect/proc_holder/alien/resin/fire(mob/living/carbon/user)
	if(locate(/obj/structure/alien/resin) in user.loc)
		user << "There is already a resin structure there."
		return 0
	var/choice = input("Choose what you wish to shape.","Resin building") as null|anything in structures
	if(!choice)
		return 0
	if (!cost_check(check_turf,user))
		return 0
	user << "You shape a [choice]."
	user.visible_message("[user] vomits up a thick purple substance and begins to shape it.")

	choice = structures[choice]
	new choice(user.loc)
	return 1

/obj/effect/proc_holder/alien/regurgitate
	name = "Regurgitate"
	desc = "Empties the contents of your stomach"
	plasma_cost = 0
	action_icon_state = "alien_barf"

/obj/effect/proc_holder/alien/regurgitate/fire(mob/living/carbon/user)
	if(user.stomach_contents.len)
		for(var/atom/movable/A in user.stomach_contents)
			user.stomach_contents.Remove(A)
			A.loc = user.loc
			if(isliving(A))
				var/mob/M = A
				M.reset_perspective()
		user.visible_message("[user] hurls out the contents of their stomach!")
	return

/obj/effect/proc_holder/alien/nightvisiontoggle
	name = "Toggle Night Vision"
	desc = "Toggles Night Vision"
	plasma_cost = 0
	has_action = 0 // Has dedicated GUI button already

/obj/effect/proc_holder/alien/nightvisiontoggle/fire(mob/living/carbon/alien/user)
	if(!user.nightvision)
		user.see_in_dark = 8
		user.see_invisible = SEE_INVISIBLE_MINIMUM
		user.nightvision = 1
		user.hud_used.nightvisionicon.icon_state = "nightvision1"
	else if(user.nightvision == 1)
		user.see_in_dark = 4
		user.see_invisible = 45
		user.nightvision = 0
		user.hud_used.nightvisionicon.icon_state = "nightvision0"

	return 1

/obj/effect/proc_holder/alien/sneak
	name = "Sneak"
	desc = "Blend into the shadows to stalk your prey."
	var/active = 0

	action_icon_state = "alien_sneak"

/obj/effect/proc_holder/alien/sneak/fire(mob/living/carbon/alien/humanoid/user)
	if(!active)
		user.alpha = 75 //Still easy to see in lit areas with bright tiles, almost invisible on resin.
		user.sneaking = 1
		active = 1
		user << "You blend into the shadows..."
	else
		user.alpha = initial(user.alpha)
		user.sneaking = 0
		active = 0
		user << "You reveal yourself!"

/mob/living/carbon/proc/getPlasma()
	var/obj/item/organ/internal/alien/plasmavessel/vessel = getorgan(/obj/item/organ/internal/alien/plasmavessel)
	if(!vessel) return 0
	return vessel.storedPlasma

/mob/living/carbon/proc/adjustPlasma(amount)
	var/obj/item/organ/internal/alien/plasmavessel/vessel = getorgan(/obj/item/organ/internal/alien/plasmavessel)
	if(!vessel) return 0
	vessel.storedPlasma = max(vessel.storedPlasma + amount,0)
	vessel.storedPlasma = min(vessel.storedPlasma, vessel.max_plasma) //upper limit of max_plasma, lower limit of 0
	for(var/X in abilities)
		var/obj/effect/proc_holder/alien/APH = X
		if(APH.has_action)
			APH.action.UpdateButtonIcon()
	return 1

/mob/living/carbon/alien/adjustPlasma(amount)
	. = ..()
	updatePlasmaDisplay()

/mob/living/carbon/proc/usePlasma(amount)
	if(getPlasma() >= amount)
		adjustPlasma(-amount)
		return 1

	return 0

/proc/cmp_abilities_cost(obj/effect/proc_holder/alien/a, obj/effect/proc_holder/alien/b)
	return b.plasma_cost - a.plasma_cost


code:
/mob/living/carbon/alien/humanoid/drone
	name = "alien drone"
	caste = "d"
	maxHealth = 125
	health = 125
	icon_state = "aliend_s"

/mob/living/carbon/alien/humanoid/drone/New()
	internal_organs += new /obj/item/organ/internal/alien/plasmavessel/large
	internal_organs += new /obj/item/organ/internal/alien/resinspinner
	internal_organs += new /obj/item/organ/internal/alien/acid

	AddAbility(new/obj/effect/proc_holder/alien/evolve(null))
	..()

/mob/living/carbon/alien/humanoid/drone/movement_delay()
	. = ..()

/obj/effect/proc_holder/alien/evolve
	name = "Evolve to Praetorian"
	desc = "Praetorian"
	plasma_cost = 500

	action_icon_state = "alien_evolve_drone"

/obj/effect/proc_holder/alien/evolve/fire(mob/living/carbon/alien/humanoid/user)
	var/obj/item/organ/internal/alien/hivenode/node = user.getorgan(/obj/item/organ/internal/alien/hivenode)
	if(!node) //Players are Murphy's Law. We may not expect there to ever be a living xeno with no hivenode, but they _WILL_ make it happen.
		user << "Without the hivemind, you can't possibly hold the responsibility of leadership!"
		return 0
	if(node.recent_queen_death)
		user << "Your thoughts are still too scattered to take up the position of leadership."
		return 0

	if(!isturf(user.loc))
		user << "You can't evolve here!"
		return 0
	if(!alien_type_present(/mob/living/carbon/alien/humanoid/royal))
		var/mob/living/carbon/alien/humanoid/royal/praetorian/new_xeno = new (user.loc)
		user.alien_evolve(new_xeno)
		return 1
	else
		user << "We already have a living royal!"
		return 0

license: mit


code:
/mob/living/carbon/alien/humanoid/hunter
	name = "alien hunter"
	caste = "h"
	maxHealth = 125
	health = 125
	icon_state = "alienh_s"
	var/obj/screen/leap_icon = null

/mob/living/carbon/alien/humanoid/hunter/New()
	internal_organs += new /obj/item/organ/internal/alien/plasmavessel/small
	..()

/mob/living/carbon/alien/humanoid/hunter/movement_delay()
	. = -1		//hunters are sanic
	. += ..()	//but they still need to slow down on stun

//Hunter verbs

/mob/living/carbon/alien/humanoid/hunter/proc/toggle_leap(message = 1)
	leap_on_click = !leap_on_click
	leap_icon.icon_state = "leap_[leap_on_click ? "on":"off"]"
	update_icons()
	if(message)
		src << "You will now [leap_on_click ? "leap at":"slash at"] enemies!"
	else
		return

/mob/living/carbon/alien/humanoid/hunter/ClickOn(atom/A, params)
	face_atom(A)
	if(leap_on_click)
		leap_at(A)
	else
		..()

#define MAX_ALIEN_LEAP_DIST 7

/mob/living/carbon/alien/humanoid/hunter/proc/leap_at(atom/A)
	if(pounce_cooldown)
		src << "You are too fatigued to pounce right now!"
		return

	if(leaping || stat || buckled || lying)
		return

	if(!has_gravity(src) || !has_gravity(A))
		src << "It is unsafe to leap without gravity!"
		//It's also extremely buggy visually, so it's balance+bugfix
		return

	else //Maybe uses plasma in the future, although that wouldn't make any sense...
		leaping = 1
		update_icons()
		throw_at(A,MAX_ALIEN_LEAP_DIST,1, spin=0, diagonals_first = 1)
		leaping = 0
		update_icons()

/mob/living/carbon/alien/humanoid/hunter/throw_impact(atom/A)

	if(!leaping)
		return ..()

	if(A)
		if(istype(A, /mob/living))
			var/mob/living/L = A
			var/blocked = 0
			if(ishuman(A))
				var/mob/living/carbon/human/H = A
				if(H.check_shields(90, "the [name]", src, attack_type = THROWN_PROJECTILE_ATTACK))
					blocked = 1
			if(!blocked)
				L.visible_message("[src] pounces on [L]!", "[src] pounces on you!")
				L.Weaken(5)
				sleep(2)//Runtime prevention (infinite bump() calls on hulks)
				step_towards(src,L)

			toggle_leap(0)
			pounce_cooldown = !pounce_cooldown
			spawn(pounce_cooldown_time) //3s by default
				pounce_cooldown = !pounce_cooldown
		else if(A.density && !A.CanPass(src))
			visible_message("[src] smashes into [A]!", "[src] smashes into [A]!")
			weakened = 2

		if(leaping)
			leaping = 0
			update_icons()
			update_canmove()

/mob/living/carbon/alien/humanoid/float(on)
	if(leaping)
		return
	..()


code:
/mob/living/carbon/alien/humanoid/royal/praetorian
	name = "alien praetorian"
	caste = "p"
	maxHealth = 250
	health = 250
	icon_state = "alienp"

/mob/living/carbon/alien/humanoid/royal/praetorian/New()

	real_name = name

	internal_organs += new /obj/item/organ/internal/alien/plasmavessel/large
	internal_organs += new /obj/item/organ/internal/alien/resinspinner
	internal_organs += new /obj/item/organ/internal/alien/acid
	internal_organs += new /obj/item/organ/internal/alien/neurotoxin
	AddSpell(new /obj/effect/proc_holder/spell/aoe_turf/repulse/xeno(src))
	AddAbility(new /obj/effect/proc_holder/alien/royal/praetorian/evolve())
	..()

/mob/living/carbon/alien/humanoid/royal/praetorian/movement_delay()
	. = ..()
	. += 1

/obj/effect/proc_holder/alien/royal/praetorian/evolve
	name = "Evolve"
	desc = "Produce an interal egg sac capable of spawning children. Only one queen can exist at a time."
	plasma_cost = 500

	action_icon_state = "alien_evolve_praetorian"

/obj/effect/proc_holder/alien/royal/praetorian/evolve/fire(mob/living/carbon/alien/humanoid/user)
	var/obj/item/organ/internal/alien/hivenode/node = user.getorgan(/obj/item/organ/internal/alien/hivenode)
	if(!node) //Just in case this particular Praetorian gets violated and kept by the RD as a replacement for Lamarr.
		user << "Without the hivemind, you would be unfit to rule as queen!"
		return 0
	if(node.recent_queen_death)
		user << "You are still too burdened with guilt to evolve into a queen."
		return 0
	if(!alien_type_present(/mob/living/carbon/alien/humanoid/royal/queen))
		var/mob/living/carbon/alien/humanoid/royal/queen/new_xeno = new (user.loc)
		user.alien_evolve(new_xeno)
		return 1
	else
		user << "We already have an alive queen."
		return 0


code:
/mob/living/carbon/alien/humanoid/sentinel
	name = "alien sentinel"
	caste = "s"
	maxHealth = 150
	health = 150
	icon_state = "aliens_s"

/mob/living/carbon/alien/humanoid/sentinel/New()
	internal_organs += new /obj/item/organ/internal/alien/plasmavessel
	internal_organs += new /obj/item/organ/internal/alien/acid
	internal_organs += new /obj/item/organ/internal/alien/neurotoxin
	AddAbility(new /obj/effect/proc_holder/alien/sneak)
	..()

/mob/living/carbon/alien/humanoid/sentinel/movement_delay()
	. = ..()


code:
/mob/living/carbon/alien/humanoid/death(gibbed)
	if(stat == DEAD)
		return

	stat = DEAD

	if(!gibbed)
		playsound(loc, 'sound/voice/hiss6.ogg', 80, 1, 1)
		visible_message("[src] lets out a waning guttural screech, green blood bubbling from its maw...")
		update_canmove()
		update_icons()
		status_flags |=CANPUSH

	return ..(gibbed)

//When the alien queen dies, all others must pay the price for letting her die.
/mob/living/carbon/alien/humanoid/royal/queen/death(gibbed)
	if(stat == DEAD)
		return

	for(var/mob/living/carbon/C in living_mob_list)
		if(C == src) //Make sure not to proc it on ourselves.
			continue
		var/obj/item/organ/internal/alien/hivenode/node = C.getorgan(/obj/item/organ/internal/alien/hivenode)
		if(istype(node)) // just in case someone would ever add a diffirent node to hivenode slot
			node.queen_death()

	return ..(gibbed)


code:
/mob/living/carbon/alien/humanoid/emote(act,m_type=1,message = null)

	var/param = null
	if (findtext(act, "-", 1, null))
		var/t1 = findtext(act, "-", 1, null)
		param = copytext(act, t1 + 1, length(act) + 1)
		act = copytext(act, 1, t1)

	var/muzzled = is_muzzled()

	switch(act) //Alphabetical please
		if ("deathgasp","deathgasps")
			message = "[src] lets out a waning guttural screech, green blood bubbling from its maw..."
			m_type = 2

		if ("gnarl","gnarls")
			if (!muzzled)
				message = "[src] gnarls and shows its teeth.."
				m_type = 2

		if ("hiss","hisses")
			if(!muzzled)
				message = "[src] hisses."
				m_type = 2

		if ("me")
			..()
			return

		if ("moan","moans")
			message = "[src] moans!"
			m_type = 2

		if ("roar","roars")
			if (!muzzled)
				message = "[src] roars."
				m_type = 2

		if ("roll","rolls")
			if (!src.restrained())
				message = "[src] rolls."
				m_type = 1

		if ("scratch","scratches")
			if (!src.restrained())
				message = "[src] scratches."
				m_type = 1

		if ("screech","screeches")
			if (!muzzled)
				message = "[src] screeches."
				m_type = 2

		if ("shiver","shivers")
			message = "[src] shivers."
			m_type = 2

		if ("sign","signs")
			if (!src.restrained())
				message = text("[src] signs[].", (text2num(param) ? text(" the number []", text2num(param)) : null))
				m_type = 1

		if ("tail")
			message = "[src] waves its tail."
			m_type = 1

		if ("help") //This is an exception
			src << "Help for xenomorph emotes. You can use these emotes with say \"*emote\":\n\naflap, airguitar, blink, blink_r, blush, bow, burp, choke, chucke, clap, collapse, cough, dance, deathgasp, drool, flap, frown, gasp, giggle, glare-(none)/mob, gnarl, hiss, jump, laugh, look-atom, me, moan, nod, point-atom, roar, roll, scream, scratch, screech, shake, shiver, sign-#, sit, smile, sneeze, sniff, snore, stare-(none)/mob, sulk, sway, tail, tremble, twitch, twitch_s, wave, whimper, wink, yawn"

		else
			..(act)

	if ((message && src.stat == 0))
		log_emote("[name]/[key] : [message]")
		if (act == "roar")
			playsound(src.loc, 'sound/voice/hiss5.ogg', 40, 1, 1)

		if (act == "hiss")
			playsound(src.loc, "hiss", 40, 1, 1)

		if (act == "deathgasp")
			playsound(src.loc, 'sound/voice/hiss6.ogg', 80, 1, 1)

		if (m_type & 1)
			visible_message(message)
		else
			audible_message(message)
	return


code:
/mob/living/carbon/alien/humanoid
	name = "alien"
	icon_state = "alien_s"
	pass_flags = PASSTABLE
	butcher_results = list(/obj/item/weapon/reagent_containers/food/snacks/meat/slab/xeno = 5, /obj/item/stack/sheet/animalhide/xeno = 1)
	var/obj/item/r_store = null
	var/obj/item/l_store = null
	var/caste = ""
	var/alt_icon = 'icons/mob/alienleap.dmi' //used to switch between the two alien icon files.
	var/leap_on_click = 0
	var/pounce_cooldown = 0
	var/pounce_cooldown_time = 30
	var/custom_pixel_x_offset = 0 //for admin fuckery.
	var/custom_pixel_y_offset = 0
	var/sneaking = 0 //For sneaky-sneaky mode and appropriate slowdown

//This is fine right now, if we're adding organ specific damage this needs to be updated
/mob/living/carbon/alien/humanoid/New()
	AddAbility(new/obj/effect/proc_holder/alien/regurgitate(null))
	..()

/mob/living/carbon/alien/humanoid/movement_delay()
	. = ..()
	. += move_delay_add + config.alien_delay + sneaking	//move_delay_add is used to slow aliens with stuns

/mob/living/carbon/alien/humanoid/emp_act(severity)
	if(r_store) r_store.emp_act(severity)
	if(l_store) l_store.emp_act(severity)
	..()

/mob/living/carbon/alien/humanoid/attack_hulk(mob/living/carbon/human/user)
	if(user.a_intent == "harm")
		..(user, 1)
		adjustBruteLoss(15)
		var/hitverb = "punched"
		if(mob_size < MOB_SIZE_LARGE)
			Paralyse(1)
			step_away(src,user,15)
			sleep(1)
			step_away(src,user,15)
			hitverb = "slammed"
		playsound(loc, "punch", 25, 1, -1)
		visible_message("[user] has [hitverb] [src]!", \
		"[user] has [hitverb] [src]!")
		return 1

/mob/living/carbon/alien/humanoid/attack_hand(mob/living/carbon/human/M)
	if(..())
		switch(M.a_intent)
			if ("harm")
				var/damage = rand(1, 9)
				if (prob(90))
					playsound(loc, "punch", 25, 1, -1)
					visible_message("[M] has punched [src]!", \
							"[M] has punched [src]!")
					if ((stat != DEAD) && (damage > 9 || prob(5)))//Regular humans have a very small chance of weakening an alien.
						Paralyse(2)
						visible_message("[M] has weakened [src]!", \
								"[M] has weakened [src]!")
					adjustBruteLoss(damage)
					add_logs(M, src, "attacked")
					updatehealth()
				else
					playsound(loc, 'sound/weapons/punchmiss.ogg', 25, 1, -1)
					visible_message("[M] has attempted to punch [src]!")

			if ("disarm")
				if (!lying)
					if (prob(5))
						Paralyse(2)
						playsound(loc, 'sound/weapons/thudswoosh.ogg', 50, 1, -1)
						add_logs(M, src, "pushed")
						visible_message("[M] has pushed down [src]!", \
							"[M] has pushed down [src]!")
					else
						if (prob(50))
							drop_item()
							playsound(loc, 'sound/weapons/thudswoosh.ogg', 50, 1, -1)
							visible_message("[M] has disarmed [src]!", \
							"[M] has disarmed [src]!")
						else
							playsound(loc, 'sound/weapons/punchmiss.ogg', 25, 1, -1)
							visible_message("[M] has attempted to disarm [src]!")

/mob/living/carbon/alien/humanoid/restrained()
	if (handcuffed)
		return 1
	return 0

/mob/living/carbon/alien/humanoid/show_inv(mob/user)
	user.set_machine(src)
	var/dat = {"

	[name]

Left Hand: 		[l_hand		? l_hand	: "Nothing"]

Right Hand: 		[r_hand		? r_hand	: "Nothing"]

Empty Pouches"}

	if(handcuffed)
		dat += "
Handcuffed"
	if(legcuffed)
		dat += "
Legcuffed"

	dat += {"

Close
	"}
	user << browse(dat, "window=mob\ref[src];size=325x500")
	onclose(user, "mob\ref[src]")

/mob/living/carbon/alien/humanoid/Topic(href, href_list)
	..()
	//strip panel
	if(usr.canUseTopic(src, BE_CLOSE, NO_DEXTERY))
		if(href_list["pouches"])
			visible_message("[usr] tries to empty [src]'s pouches.", \
							"[usr] tries to empty [src]'s pouches.")
			if(do_mob(usr, src, POCKET_STRIP_DELAY * 0.5))
				unEquip(r_store)
				unEquip(l_store)

/mob/living/carbon/alien/humanoid/cuff_resist(obj/item/I)
	playsound(src, 'sound/voice/hiss5.ogg', 40, 1, 1)  //Alien roars when starting to break free
	..(I, cuff_break = 1)

/mob/living/carbon/alien/humanoid/get_standard_pixel_y_offset(lying = 0)
	if(leaping)
		return -32
	else if(custom_pixel_y_offset)
		return custom_pixel_y_offset
	else
		return initial(pixel_y)

/mob/living/carbon/alien/humanoid/get_standard_pixel_x_offset(lying = 0)
	if(leaping)
		return -32
	else if(custom_pixel_x_offset)
		return custom_pixel_x_offset
	else
		return initial(pixel_x)

/mob/living/carbon/alien/humanoid/check_ear_prot()
	return 1

/mob/living/carbon/alien/humanoid/get_permeability_protection()
	return 0.8

/mob/living/carbon/alien/humanoid/alien_evolve(mob/living/carbon/alien/humanoid/new_xeno)
	drop_l_hand()
	drop_r_hand()
	for(var/atom/movable/A in stomach_contents)
		stomach_contents.Remove(A)
		new_xeno.stomach_contents.Add(A)
		A.loc = new_xeno
	..()

//For alien evolution/promotion procs. Checks for
proc/alien_type_present(var/alienpath)
	for(var/mob/living/carbon/alien/humanoid/A in living_mob_list)
		if(!istype(A, alienpath))
			continue
		if(!A.key || A.stat == DEAD) //Only living aliens with a ckey are valid.
			continue
		return 1
	return 0

/mob/living/carbon/alien/humanoid/check_breath(datum/gas_mixture/breath)
	if(breath && breath.total_moles() > 0 && !sneaking)
		playsound(get_turf(src), pick('sound/voice/lowHiss2.ogg', 'sound/voice/lowHiss3.ogg', 'sound/voice/lowHiss4.ogg'), 50, 0, -5)
	..()


code:
/mob/living/carbon/alien/humanoid/unEquip(obj/item/I)
	. = ..()
	if(!. || !I)
		return


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

/mob/living/carbon/alien/humanoid/proc/adjust_body_temperature(current, loc_temp, boost)
	var/temperature = current
	var/difference = abs(current-loc_temp)	//get difference
	var/increments// = difference/10			//find how many increments apart they are
	if(difference > 50)
		increments = difference/5
	else
		increments = difference/10
	var/change = increments*boost	// Get the amount to change by (x per increment)
	var/temp_change
	if(current < loc_temp)
		temperature = min(loc_temp, temperature+change)
	else if(current > loc_temp)
		temperature = max(loc_temp, temperature-change)
	temp_change = (temperature - current)
	return temp_change


code:
/mob/living/carbon/alien/humanoid/royal
	//Common stuffs for Praetorian and Queen
	icon = 'icons/mob/alienqueen.dmi'
	status_flags = 0
	ventcrawler = 0 //pull over that ass too fat
	unique_name = 0
	pixel_x = -16
	bubble_icon = "alienroyal"
	mob_size = MOB_SIZE_LARGE
	layer = MOB_LAYER + 0.5 //above most mobs, but below speechbubbles
	pressure_resistance = 200 //Because big, stompy xenos should not be blown around like paper.
	butcher_results = list(/obj/item/weapon/reagent_containers/food/snacks/meat/slab/xeno = 20, /obj/item/stack/sheet/animalhide/xeno = 3)

	var/alt_inhands_file = 'icons/mob/alienqueen.dmi'

/mob/living/carbon/alien/humanoid/royal/can_inject()
	return 0

/mob/living/carbon/alien/humanoid/royal/queen
	name = "alien queen"
	caste = "q"
	maxHealth = 400
	health = 400
	icon_state = "alienq"

/mob/living/carbon/alien/humanoid/royal/queen/New()
	//there should only be one queen
	for(var/mob/living/carbon/alien/humanoid/royal/queen/Q in living_mob_list)
		if(Q == src)
			continue
		if(Q.stat == DEAD)
			continue
		if(Q.client)
			name = "alien princess ([rand(1, 999)])"	//if this is too cutesy feel free to change it/remove it.
			break

	real_name = src.name

	internal_organs += new /obj/item/organ/internal/alien/plasmavessel/large/queen
	internal_organs += new /obj/item/organ/internal/alien/resinspinner
	internal_organs += new /obj/item/organ/internal/alien/acid
	internal_organs += new /obj/item/organ/internal/alien/neurotoxin
	internal_organs += new /obj/item/organ/internal/alien/eggsac
	AddSpell(new /obj/effect/proc_holder/spell/aoe_turf/repulse/xeno(src))
	AddAbility(new/obj/effect/proc_holder/alien/royal/queen/promote())
	..()

/mob/living/carbon/alien/humanoid/royal/queen/movement_delay()
	. = ..()
	. += 5

//Queen verbs
/obj/effect/proc_holder/alien/lay_egg
	name = "Lay Egg"
	desc = "Lay an egg to produce huggers to impregnate prey with."
	plasma_cost = 75
	check_turf = 1
	action_icon_state = "alien_egg"

/obj/effect/proc_holder/alien/lay_egg/fire(mob/living/carbon/user)
	if(locate(/obj/structure/alien/egg) in get_turf(user))
		user << "There's already an egg here."
		return 0
	user.visible_message("[user] has laid an egg!")
	new /obj/structure/alien/egg(user.loc)
	return 1

//Button to let queen choose her praetorian.
/obj/effect/proc_holder/alien/royal/queen/promote
	name = "Create Royal Parasite"
	desc = "Produce a royal parasite to grant one of your children the honor of being your Praetorian."
	plasma_cost = 500 //Plasma cost used on promotion, not spawning the parasite.

	action_icon_state = "alien_queen_promote"

/obj/effect/proc_holder/alien/royal/queen/promote/fire(mob/living/carbon/alien/user)
	var/obj/item/queenpromote/prom
	if(alien_type_present(/mob/living/carbon/alien/humanoid/royal/praetorian/))
		user << "You already have a Praetorian!"
		return 0
	else
		for(prom in user)
			user << "You discard [prom]."
			qdel(prom)
			return 0

		prom = new (user.loc)
		if(!user.put_in_active_hand(prom, 1))
			user << "You must empty your hands before preparing the parasite."
			return 0
		else //Just in case telling the player only once is not enough!
			user << "Use the royal parasite on one of your children to promote her to Praetorian!"
	return 0

/obj/item/queenpromote
	name = "\improper royal parasite"
	desc = "Inject this into one of your grown children to promote her to a Praetorian!"
	icon_state = "alien_medal"
	flags = ABSTRACT|NODROP
	icon = 'icons/mob/alien.dmi'

/obj/item/queenpromote/attack(mob/living/M, mob/living/carbon/alien/humanoid/user)
	if(!isalienadult(M) || istype(M, /mob/living/carbon/alien/humanoid/royal))
		user << "You may only use this with your adult, non-royal children!"
		return
	if(alien_type_present(/mob/living/carbon/alien/humanoid/royal/praetorian/))
		user << "You already have a Praetorian!"
		return

	var/mob/living/carbon/alien/humanoid/A = M
	if(A.stat == CONSCIOUS && A.mind && A.key)
		if(!user.usePlasma(500))
			user << "You must have 500 plasma stored to use this!"
			return

		A << "The queen has granted you a promotion to Praetorian!"
		user.visible_message("[A] begins to expand, twist and contort!")
		var/mob/living/carbon/alien/humanoid/royal/praetorian/new_prae = new (A.loc)
		A.mind.transfer_to(new_prae)
		qdel(A)
		qdel(src)
		return
	else
		user << "This child must be alert and responsive to become a Praetorian!"

/obj/item/queenpromote/attack_self(mob/user)
	user << "You discard [src]."
	qdel(src)


code:
/mob/living/carbon/alien/humanoid/update_icons()
	overlays.Cut()
	for(var/image/I in overlays_standing)
		overlays += I

	if(stat == DEAD)
		//If we mostly took damage from fire
		if(fireloss > 125)
			icon_state = "alien[caste]_husked"
		else
			icon_state = "alien[caste]_dead"

	else if((stat == UNCONSCIOUS && !sleeping) || weakened)
		icon_state = "alien[caste]_unconscious"
	else if(leap_on_click)
		icon_state = "alien[caste]_pounce"

	else if(lying || resting || sleeping)
		icon_state = "alien[caste]_sleep"
	else if(mob_size == MOB_SIZE_LARGE)
		icon_state = "alien[caste]"
	else
		icon_state = "alien[caste]_s"

	if(leaping)
		if(alt_icon == initial(alt_icon))
			var/old_icon = icon
			icon = alt_icon
			alt_icon = old_icon
		icon_state = "alien[caste]_leap"
		pixel_x = -32
		pixel_y = -32
	else
		if(alt_icon != initial(alt_icon))
			var/old_icon = icon
			icon = alt_icon
			alt_icon = old_icon
		pixel_x = get_standard_pixel_x_offset(lying)
		pixel_y = get_standard_pixel_y_offset(lying)

/mob/living/carbon/alien/humanoid/regenerate_icons()
	if(!..())
	//	update_icons() //Handled in update_transform(), leaving this here as a reminder
		update_transform()

/mob/living/carbon/alien/humanoid/update_transform() //The old method of updating lying/standing was update_icons(). Aliens still expect that.
	if(lying > 0)
		lying = 90 //Anything else looks retarded
	..()
	update_icons()

//Royals have bigger sprites, so inhand things must be handled differently.
/mob/living/carbon/alien/humanoid/royal/update_inv_r_hand()
	..()
	remove_overlay(R_HAND_LAYER)
	if(r_hand)
		var/itm_state = r_hand.item_state
		if(!itm_state)
			itm_state = r_hand.icon_state

		var/image/I = image("icon" = alt_inhands_file , "icon_state"="[itm_state][caste]_r", "layer"=-R_HAND_LAYER)
		overlays_standing[R_HAND_LAYER] = I

		apply_overlay(R_HAND_LAYER)

/mob/living/carbon/alien/humanoid/royal/update_inv_l_hand()
	..()
	remove_overlay(L_HAND_LAYER)
	if(l_hand)
		var/itm_state = l_hand.item_state
		if(!itm_state)
			itm_state = l_hand.icon_state

		var/image/I = image("icon" = alt_inhands_file , "icon_state"="[itm_state][caste]_l", "layer"=-L_HAND_LAYER)
		overlays_standing[L_HAND_LAYER] = I
		apply_overlay(L_HAND_LAYER)


code:
/mob/living/carbon/alien/larva/death(gibbed)
	if(stat == DEAD)
		return
	stat = DEAD
	icon_state = "larva_dead"

	if(!gibbed)
		visible_message("[src] lets out a waning high-pitched cry.")

	return ..(gibbed)


code:
/mob/living/carbon/alien/larva/emote(act,m_type=1,message = null)

	var/param = null
	if (findtext(act, "-", 1, null))
		var/t1 = findtext(act, "-", 1, null)
		param = copytext(act, t1 + 1, length(act) + 1)
		act = copytext(act, 1, t1)

	var/muzzled = is_muzzled()

	switch(act) //Alphabetically sorted please.
		if ("burp","burps")
			if (!muzzled)
				message = "[src] burps."
				m_type = 2
		if ("choke","chokes")
			message = "[src] chokes."
			m_type = 2
		if ("collapse","collapses")
			Paralyse(2)
			message = "[src] collapses!"
			m_type = 2
		if ("dance","dances")
			if (!src.restrained())
				message = "[src] dances around happily."
				m_type = 1
		if ("deathgasp","deathgasps")
			message = "[src] lets out a sickly hiss of air and falls limply to the floor..."
			m_type = 2
		if ("drool","drools")
			message = "[src] drools."
			m_type = 1
		if ("gasp","gasps")
			message = "[src] gasps."
			m_type = 2
		if ("gnarl","gnarls")
			if (!muzzled)
				message = "[src] gnarls and shows its teeth.."
				m_type = 2
		if ("hiss","hisses")
			message = "[src] hisses softly."
			m_type = 1
		if ("jump","jumps")
			message = "[src] jumps!"
			m_type = 1
		if ("me")
			..()
			return
		if ("moan","moans")
			message = "[src] moans!"
			m_type = 2
		if ("nod","nods")
			message = "[src] nods its head."
			m_type = 1
		if ("roar","roars")
			if (!muzzled)
				message = "[src] softly roars."
				m_type = 2
		if ("roll","rolls")
			if (!src.restrained())
				message = "[src] rolls."
				m_type = 1
		if ("scratch","scratches")
			if (!src.restrained())
				message = "[src] scratches."
				m_type = 1
		if ("screech","screeches") //This orignally was called scretch, changing it. -Sum99
			if (!muzzled)
				message = "[src] screeches."
				m_type = 2
		if ("shake","shakes")
			message = "[src] shakes its head."
			m_type = 1
		if ("shiver","shivers")
			message = "[src] shivers."
			m_type = 2
		if ("sign","signs")
			if (!src.restrained())
				message = text("[src] signs[].", (text2num(param) ? text(" the number []", text2num(param)) : null))
				m_type = 1
		if ("snore","snores")
			message = "[src] snores."
			m_type = 2
		if ("sulk","sulks")
			message = "[src] sulks down sadly."
			m_type = 1
		if ("sway","sways")
			message = "[src] sways around dizzily."
			m_type = 1
		if ("tail")
			message = "[src] waves its tail."
			m_type = 1
		if ("twitch")
			message = "[src] twitches violently."
			m_type = 1
		if ("whimper","whimpers")
			if (!muzzled)
				message = "[src] whimpers."
				m_type = 2

		if ("help") //"The exception"
			src << "Help for larva emotes. You can use these emotes with say \"*emote\":\n\nburp, choke, collapse, dance, deathgasp, drool, gasp, gnarl, hiss, jump, me, moan, nod, roll, roar, scratch, screech, shake, shiver, sign-#, sulk, sway, tail, twitch, whimper"

		else
			src << "Unusable emote '[act]'. Say *help for a list."

	if ((message && src.stat == 0))
		log_emote("[name]/[key] : [message]")
		if (m_type & 1)
			visible_message(message)
		else
			audible_message(message)
	return


code:
//can't unequip since it can't equip anything
/mob/living/carbon/alien/larva/unEquip(obj/item/W)
	return


code:
/mob/living/carbon/alien/larva
	name = "alien larva"
	real_name = "alien larva"
	icon_state = "larva0"
	pass_flags = PASSTABLE | PASSMOB
	mob_size = MOB_SIZE_SMALL
	density = 0

	maxHealth = 25
	health = 25

	var/amount_grown = 0
	var/max_grown = 100
	var/time_of_birth

	rotate_on_lying = 0

//This is fine right now, if we're adding organ specific damage this needs to be updated
/mob/living/carbon/alien/larva/New()
	regenerate_icons()
	internal_organs += new /obj/item/organ/internal/alien/plasmavessel/small/tiny

	AddAbility(new/obj/effect/proc_holder/alien/hide(null))
	AddAbility(new/obj/effect/proc_holder/alien/larva_evolve(null))
	..()

//This needs to be fixed
/mob/living/carbon/alien/larva/Stat()
	..()
	if(statpanel("Status"))
		stat(null, "Progress: [amount_grown]/[max_grown]")

/mob/living/carbon/alien/larva/adjustPlasma(amount)
	if(stat != DEAD && amount > 0)
		amount_grown = min(amount_grown + 1, max_grown)
	..(amount)

//can't equip anything
/mob/living/carbon/alien/larva/attack_ui(slot_id)
	return

/mob/living/carbon/alien/larva/attack_hulk(mob/living/carbon/human/user)
	if(user.a_intent == "harm")
		..(user, 1)
		adjustBruteLoss(5 + rand(1,9))
		Paralyse(1)
		spawn()
			step_away(src,user,15)
			sleep(1)
			step_away(src,user,15)
		return 1

/mob/living/carbon/alien/larva/attack_hand(mob/living/carbon/human/M)
	if(..())
		var/damage = rand(1, 9)
		if (prob(90))
			playsound(loc, "punch", 25, 1, -1)
			add_logs(M, src, "attacked")
			visible_message("[M] has kicked [src]!", \
					"[M] has kicked [src]!")
			if ((stat != DEAD) && (damage > 4.9))
				Paralyse(rand(5,10))

			adjustBruteLoss(damage)
			updatehealth()
		else
			playsound(loc, 'sound/weapons/punchmiss.ogg', 25, 1, -1)
			visible_message("[M] has attempted to kick [src]!", \
					"[M] has attempted to kick [src]!")

	return

/mob/living/carbon/alien/larva/restrained()
	return 0

// new damage icon system
// now constructs damage icon for each organ from mask * damage field

/mob/living/carbon/alien/larva/show_inv(mob/user)
	return

/mob/living/carbon/alien/larva/toggle_throw_mode()
	return

/mob/living/carbon/alien/larva/start_pulling()
	return

/mob/living/carbon/alien/larva/stripPanelUnequip(obj/item/what, mob/who)
	src << "You don't have the dexterity to do this!"
	return

/mob/living/carbon/alien/larva/stripPanelEquip(obj/item/what, mob/who)
	src << "You don't have the dexterity to do this!"
	return


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

/mob/living/carbon/alien/larva/Life()
	set invisibility = 0
	set background = BACKGROUND_ENABLED

	if (notransform)
		return
	if(..())
		// GROW!
		if(amount_grown < max_grown)
			amount_grown++
			update_icons()

/mob/living/carbon/alien/larva/update_stat()
	if(status_flags & GODMODE)
		return
	if(stat != DEAD)
		if(health<= -maxHealth || !getorgan(/obj/item/organ/internal/brain))
			death()
			return
		if(paralysis || sleeping || getOxyLoss() > 50 || (status_flags & FAKEDEATH) || health <= config.health_threshold_crit)
			if(stat == CONSCIOUS)
				stat = UNCONSCIOUS
				blind_eyes(1)
				update_canmove()
		else
			if(stat == UNCONSCIOUS)
				stat = CONSCIOUS
				resting = 0
				adjust_blindness(-1)
				update_canmove()
	update_damage_hud()
	update_health_hud()


code:
/obj/effect/proc_holder/alien/hide
	name = "Hide"
	desc = "Allows to hide beneath tables or certain items. Toggled on or off."
	plasma_cost = 0

	action_icon_state = "alien_hide"

/obj/effect/proc_holder/alien/hide/fire(mob/living/carbon/alien/user)
	if(user.stat != CONSCIOUS)
		return

	if (user.layer != TURF_LAYER+0.2)
		user.layer = TURF_LAYER+0.2
		user.visible_message("[user] scurries to the ground!", \
						"You are now hiding.")
	else
		user.layer = MOB_LAYER
		user.visible_message("[user.] slowly peaks up from the ground...", \
					"You stop hiding.")
	return 1

/obj/effect/proc_holder/alien/larva_evolve
	name = "Evolve"
	desc = "Evolve into a fully grown Alien."
	plasma_cost = 0

	action_icon_state = "alien_evolve_larva"

/obj/effect/proc_holder/alien/larva_evolve/fire(mob/living/carbon/alien/user)
	if(!islarva(user))
		return
	var/mob/living/carbon/alien/larva/L = user

	if(L.handcuffed || L.legcuffed) // Cuffing larvas ? Eh ?
		user << "You cannot evolve when you are cuffed."

	if(L.amount_grown >= L.max_grown)	//TODO ~Carn
		L << "You are growing into a beautiful alien! It is time to choose a caste."
		L << "There are three to choose from:"
		L << "Hunters are the most agile caste tasked with hunting for hosts. They are faster than a human and can even pounce, but are not much tougher than a drone."
		L << "Sentinels are tasked with protecting the hive. With their ranged spit, invisibility, and high health, they make formidable guardians and acceptable secondhand hunters."
		L << "Drones are the weakest and slowest of the castes, but can grow into the queen if there is none, and are vital to maintaining a hive with their resin secretion abilities."
		var/alien_caste = alert(L, "Please choose which alien caste you shall belong to.",,"Hunter","Sentinel","Drone")

		if(user.incapacitated()) //something happened to us while we were choosing.
			return

		var/mob/living/carbon/alien/humanoid/new_xeno
		switch(alien_caste)
			if("Hunter")
				new_xeno = new /mob/living/carbon/alien/humanoid/hunter(L.loc)
			if("Sentinel")
				new_xeno = new /mob/living/carbon/alien/humanoid/sentinel(L.loc)
			if("Drone")
				new_xeno = new /mob/living/carbon/alien/humanoid/drone(L.loc)

		L.alien_evolve(new_xeno)
		return 0
	else
		user << "You are not fully grown."
		return 0


code:
/mob/living/carbon/alien/larva/regenerate_icons()
	overlays = list()
	update_icons()

/mob/living/carbon/alien/larva/update_icons()
	var/state = 0
	if(amount_grown > 150)
		state = 2
	else if(amount_grown > 50)
		state = 1

	if(stat == DEAD)
		icon_state = "larva[state]_dead"
	else if (handcuffed || legcuffed) //This should be an overlay. Who made this an icon_state?
		icon_state = "larva[state]_cuff"
	else if(stat == UNCONSCIOUS || lying || resting)
		icon_state = "larva[state]_sleep"
	else if (stunned)
		icon_state = "larva[state]_stun"
	else
		icon_state = "larva[state]"

/mob/living/carbon/alien/larva/update_transform() //All this is handled in update_icons()
	..()
	return update_icons()

/mob/living/carbon/alien/larva/update_inv_handcuffed()
	update_icons() //larva icon_state changes if cuffed/uncuffed.


code:
/mob/living/carbon/alien/check_breath(datum/gas_mixture/breath)
	if(status_flags & GODMODE)
		return

	if(!breath || (breath.total_moles() == 0))
		//Aliens breathe in vaccuum
		return 0

	var/toxins_used = 0
	var/breath_pressure = (breath.total_moles()*R_IDEAL_GAS_EQUATION*breath.temperature)/BREATH_VOLUME
	var/list/breath_gases = breath.gases

	breath.assert_gases("plasma", "o2")

	//Partial pressure of the toxins in our breath
	var/Toxins_pp = (breath_gases["plasma"][MOLES]/breath.total_moles())*breath_pressure

	if(Toxins_pp) // Detect toxins in air
		adjustPlasma(breath_gases["plasma"][MOLES]*250)
		throw_alert("alien_tox", /obj/screen/alert/alien_tox)

		toxins_used = breath_gases["plasma"][MOLES]

	else
		clear_alert("alien_tox")

	//Breathe in toxins and out oxygen
	breath_gases["plasma"][MOLES] -= toxins_used
	breath_gases["o2"][MOLES] += toxins_used

	breath.garbage_collect()

	//BREATH TEMPERATURE
	handle_breath_temperature(breath)

/mob/living/carbon/alien/handle_status_effects()
	..()
	//natural reduction of movement delay due to stun.
	if(move_delay_add > 0)
		move_delay_add = max(0, move_delay_add - rand(1, 2))

/mob/living/carbon/alien/handle_changeling()
	return


code:
/mob/living/carbon/alien/Login()
	..()
	AddInfectionImages()
	return


code:
/mob/living/carbon/alien/Logout()
	..()
	RemoveInfectionImages()
	return


code:
/obj/item/organ/internal/alien
	origin_tech = "biotech=5"
	icon_state = "xgibmid2"
	var/list/alien_powers = list()

/obj/item/organ/internal/alien/New()
	for(var/A in alien_powers)
		if(ispath(A))
			alien_powers -= A
			alien_powers += new A(src)
	..()

/obj/item/organ/internal/alien/Insert(mob/living/carbon/M, special = 0)
	..()
	for(var/obj/effect/proc_holder/alien/P in alien_powers)
		M.AddAbility(P)

/obj/item/organ/internal/alien/Remove(mob/living/carbon/M, special = 0)
	for(var/obj/effect/proc_holder/alien/P in alien_powers)
		M.RemoveAbility(P)
	..()

/obj/item/organ/internal/alien/prepare_eat()
	var/obj/S = ..()
	S.reagents.add_reagent("sacid", 10)
	return S

/obj/item/organ/internal/alien/plasmavessel
	name = "plasma vessel"
	icon_state = "plasma"
	origin_tech = "biotech=5;plasmatech=2"
	w_class = 3
	zone = "chest"
	slot = "plasmavessel"
	alien_powers = list(/obj/effect/proc_holder/alien/plant, /obj/effect/proc_holder/alien/transfer)

	var/storedPlasma = 100
	var/max_plasma = 250
	var/heal_rate = 5
	var/plasma_rate = 10

/obj/item/organ/internal/alien/plasmavessel/prepare_eat()
	var/obj/S = ..()
	S.reagents.add_reagent("plasma", storedPlasma/10)
	return S

/obj/item/organ/internal/alien/plasmavessel/large
	name = "large plasma vessel"
	icon_state = "plasma_large"
	w_class = 4
	storedPlasma = 200
	max_plasma = 500
	plasma_rate = 15

/obj/item/organ/internal/alien/plasmavessel/large/queen
	origin_tech = "biotech=6;plasmatech=3"
	plasma_rate = 20

/obj/item/organ/internal/alien/plasmavessel/small
	name = "small plasma vessel"
	icon_state = "plasma_small"
	w_class = 2
	storedPlasma = 100
	max_plasma = 150
	plasma_rate = 5

/obj/item/organ/internal/alien/plasmavessel/small/tiny
	name = "tiny plasma vessel"
	icon_state = "plasma_tiny"
	w_class = 1
	max_plasma = 100
	alien_powers = list(/obj/effect/proc_holder/alien/transfer)

/obj/item/organ/internal/alien/plasmavessel/on_life()
	//If there are alien weeds on the ground then heal if needed or give some plasma
	if(locate(/obj/structure/alien/weeds) in owner.loc)
		if(owner.health >= owner.maxHealth)
			owner.adjustPlasma(plasma_rate)
		else
			var/heal_amt = heal_rate
			if(!isalien(owner))
				heal_amt *= 0.2
			owner.adjustPlasma(plasma_rate*0.5)
			owner.adjustBruteLoss(-heal_amt)
			owner.adjustFireLoss(-heal_amt)
			owner.adjustOxyLoss(-heal_amt)
			owner.adjustCloneLoss(-heal_amt)

/obj/item/organ/internal/alien/plasmavessel/Insert(mob/living/carbon/M, special = 0)
	..()
	if(isalien(M))
		var/mob/living/carbon/alien/A = M
		A.updatePlasmaDisplay()

/obj/item/organ/internal/alien/plasmavessel/Remove(mob/living/carbon/M, special = 0)
	..()
	if(isalien(M))
		var/mob/living/carbon/alien/A = M
		A.updatePlasmaDisplay()

/obj/item/organ/internal/alien/hivenode
	name = "hive node"
	icon_state = "hivenode"
	zone = "head"
	slot = "hivenode"
	origin_tech = "biotech=5;magnets=4;bluespace=3"
	w_class = 1
	var/recent_queen_death = 0 //Indicates if the queen died recently, aliens are heavily weakened while this is active.
	alien_powers = list(/obj/effect/proc_holder/alien/whisper)

/obj/item/organ/internal/alien/hivenode/Insert(mob/living/carbon/M, special = 0)
	..()
	M.faction |= "alien"

/obj/item/organ/internal/alien/hivenode/Remove(mob/living/carbon/M, special = 0)
	M.faction -= "alien"
	..()

//When the alien queen dies, all aliens suffer a penalty as punishment for failing to protect her.
/obj/item/organ/internal/alien/hivenode/proc/queen_death()
	if(!owner|| owner.stat == DEAD)
		return
	if(isalien(owner)) //Different effects for aliens than humans
		owner << "Your Queen has been struck down!"
		owner << "You are struck with overwhelming agony! You feel confused, and your connection to the hivemind is severed."
		owner.emote("roar")
		owner.Stun(10) //Actually just slows them down a bit.

	else if(ishuman(owner)) //Humans, being more fragile, are more overwhelmed by the mental backlash.
		owner << "You feel a splitting pain in your head, and are struck with a wave of nausea. You cannot hear the hivemind anymore!"
		owner.emote("scream")
		owner.Weaken(5)

	owner.jitteriness += 30
	owner.confused += 30
	owner.stuttering += 30

	recent_queen_death = 1
	owner.throw_alert("alien_noqueen", /obj/screen/alert/alien_vulnerable)
	spawn(2400) //four minutes
		if(qdeleted(src)) //In case the node is deleted
			return
		recent_queen_death = 0
		if(!owner) //In case the xeno is butchered or subjected to surgery after death.
			return
		owner << "The pain of the queen's death is easing. You begin to hear the hivemind again."
		owner.clear_alert("alien_noqueen")

/obj/item/organ/internal/alien/resinspinner
	name = "resin spinner"
	icon_state = "stomach-x"
	zone = "mouth"
	slot = "resinspinner"
	origin_tech = "biotech=5;materials=4"
	alien_powers = list(/obj/effect/proc_holder/alien/resin)

/obj/item/organ/internal/alien/acid
	name = "acid gland"
	icon_state = "acid"
	zone = "mouth"
	slot = "acidgland"
	origin_tech = "biotech=5;materials=2;combat=2"
	alien_powers = list(/obj/effect/proc_holder/alien/acid)

/obj/item/organ/internal/alien/neurotoxin
	name = "neurotoxin gland"
	icon_state = "neurotox"
	zone = "mouth"
	slot = "neurotoxingland"
	origin_tech = "biotech=5;combat=5"
	alien_powers = list(/obj/effect/proc_holder/alien/neurotoxin)

/obj/item/organ/internal/alien/eggsac
	name = "egg sac"
	icon_state = "eggsac"
	zone = "groin"
	slot = "eggsac"
	w_class = 4
	origin_tech = "biotech=8"
	alien_powers = list(/obj/effect/proc_holder/alien/lay_egg)


code:
/mob/living/carbon/alien/say(message)
	. = ..()
	if(.)
		playsound(loc, "hiss", 25, 1, 1) //erp just isn't the same without sound feedback

/mob/living/proc/alien_talk(message, shown_name = name)
	log_say("[key_name(src)] : [message]")
	message = trim(message)
	if(!message) return

	var/message_a = say_quote(message, get_spans())
	var/rendered = "Hivemind, [shown_name] [message_a]"
	for(var/mob/S in player_list)
		if(!S.stat && S.hivecheck())
			S << rendered
		if(S in dead_mob_list)
			S << "(F) [rendered]"

/mob/living/carbon/alien/humanoid/royal/queen/alien_talk(message, shown_name = name)
	shown_name = "[shown_name]"
	..(message, shown_name)

/mob/living/carbon/hivecheck()
	var/obj/item/organ/internal/alien/hivenode/N = getorgan(/obj/item/organ/internal/alien/hivenode)
	if(N && !N.recent_queen_death) //Mob has alien hive node and is not under the dead queen special effect.
		return N


code:
/mob/living/carbon/alien/proc/updatePlasmaDisplay()
	if(hud_used) //clientless aliens
		hud_used.alien_plasma_display.maptext = "
[round(getPlasma())]
"

/mob/living/carbon/alien/larva/updatePlasmaDisplay()
	return


code:
// This is to replace the previous datum/disease/alien_embryo for slightly improved handling and maintainability
// It functions almost identically (see code/datums/diseases/alien_embryo.dm)
var/const/ALIEN_AFK_BRACKET = 450 // 45 seconds

/obj/item/organ/internal/body_egg/alien_embryo
	name = "alien embryo"
	icon = 'icons/mob/alien.dmi'
	icon_state = "larva0_dead"
	var/stage = 0

/obj/item/organ/internal/body_egg/alien_embryo/on_find(mob/living/finder)
	..()
	if(stage < 4)
		finder << "It's small and weak, barely the size of a foetus."
	else
		finder << "It's grown quite large, and writhes slightly as you look at it."
		if(prob(10))
			AttemptGrow(0)

/obj/item/organ/internal/body_egg/alien_embryo/prepare_eat()
	var/obj/S = ..()
	S.reagents.add_reagent("sacid", 10)
	return S

/obj/item/organ/internal/body_egg/alien_embryo/on_life()
	switch(stage)
		if(2, 3)
			if(prob(2))
				owner.emote("sneeze")
			if(prob(2))
				owner.emote("cough")
			if(prob(2))
				owner << "Your throat feels sore."
			if(prob(2))
				owner << "Mucous runs down the back of your throat."
		if(4)
			if(prob(2))
				owner.emote("sneeze")
			if(prob(2))
				owner.emote("cough")
			if(prob(4))
				owner << "Your muscles ache."
				if(prob(20))
					owner.take_organ_damage(1)
			if(prob(4))
				owner << "Your stomach hurts."
				if(prob(20))
					owner.adjustToxLoss(1)
		if(5)
			owner << "You feel something tearing its way out of your stomach..."
			owner.adjustToxLoss(10)

/obj/item/organ/internal/body_egg/alien_embryo/egg_process()
	if(stage < 5 && prob(3))
		stage++
		spawn(0)
			RefreshInfectionImage()

	if(stage == 5 && prob(50))
		for(var/datum/surgery/S in owner.surgeries)
			if(S.location == "chest" && istype(S.get_surgery_step(), /datum/surgery_step/manipulate_organs))
				AttemptGrow(0)
				return
		AttemptGrow()

/obj/item/organ/internal/body_egg/alien_embryo/proc/AttemptGrow(gib_on_success = 1)
	if(!owner) return
	var/list/candidates = get_candidates(ROLE_ALIEN, ALIEN_AFK_BRACKET, "alien candidate")
	var/client/C = null

	// To stop clientless larva, we will check that our host has a client
	// if we find no ghosts to become the alien. If the host has a client
	// he will become the alien but if he doesn't then we will set the stage
	// to 4, so we don't do a process heavy check everytime.

	if(candidates.len)
		C = pick(candidates)
	else if(owner.client && !(jobban_isbanned(owner, "alien candidate") || jobban_isbanned(owner, "Syndicate")))
		C = owner.client
	else
		stage = 4 // Let's try again later.
		return

	var/overlay = image('icons/mob/alien.dmi', loc = owner, icon_state = "burst_lie")
	owner.overlays += overlay

	var/atom/xeno_loc = get_turf(owner)
	var/mob/living/carbon/alien/larva/new_xeno = new(xeno_loc)
	new_xeno.key = C.key
	new_xeno << sound('sound/voice/hiss5.ogg',0,0,0,100)	//To get the player's attention
	new_xeno.canmove = 0 //so we don't move during the bursting animation
	new_xeno.notransform = 1
	new_xeno.invisibility = INVISIBILITY_MAXIMUM
	spawn(6)
		if(new_xeno)
			new_xeno.canmove = 1
			new_xeno.notransform = 0
			new_xeno.invisibility = 0
		if(gib_on_success)
			owner.gib()
		else
			owner.adjustBruteLoss(40)
			owner.overlays -= overlay
		qdel(src)

/*----------------------------------------
Proc: AddInfectionImages(C)
Des: Adds the infection image to all aliens for this embryo
----------------------------------------*/
/obj/item/organ/internal/body_egg/alien_embryo/AddInfectionImages()
	for(var/mob/living/carbon/alien/alien in player_list)
		if(alien.client)
			var/I = image('icons/mob/alien.dmi', loc = owner, icon_state = "infected[stage]")
			alien.client.images += I

/*----------------------------------------
Proc: RemoveInfectionImage(C)
Des: Removes all images from the mob infected by this embryo
----------------------------------------*/
/obj/item/organ/internal/body_egg/alien_embryo/RemoveInfectionImages()
	for(var/mob/living/carbon/alien/alien in player_list)
		if(alien.client)
			for(var/image/I in alien.client.images)
				if(dd_hasprefix_case(I.icon_state, "infected") && I.loc == owner)
					qdel(I)


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

//TODO: Make these simple_animals

var/const/MIN_IMPREGNATION_TIME = 100 //time it takes to impregnate someone
var/const/MAX_IMPREGNATION_TIME = 150

var/const/MIN_ACTIVE_TIME = 200 //time between being dropped and going idle
var/const/MAX_ACTIVE_TIME = 400

/obj/item/clothing/mask/facehugger
	name = "alien"
	desc = "It has some sort of a tube at the end of its tail."
	icon = 'icons/mob/alien.dmi'
	icon_state = "facehugger"
	item_state = "facehugger"
	w_class = 1 //note: can be picked up by aliens unlike most other items of w_class below 4
	flags = MASKINTERNALS
	throw_range = 5
	tint = 3
	flags_cover = MASKCOVERSEYES | MASKCOVERSMOUTH
	layer = MOB_LAYER

	var/stat = CONSCIOUS //UNCONSCIOUS is the idle state in this case

	var/sterile = 0
	var/real = 1 //0 for the toy, 1 for real. Sure I could istype, but fuck that.
	var/strength = 5

	var/attached = 0

/obj/item/clothing/mask/facehugger/attack_alien(mob/user) //can be picked up by aliens
	attack_hand(user)
	return

/obj/item/clothing/mask/facehugger/attack_hand(mob/user)
	if((stat == CONSCIOUS && !sterile) && !isalien(user))
		if(Attach(user))
			return
	..()

/obj/item/clothing/mask/facehugger/attack(mob/living/M, mob/user)
	..()
	user.unEquip(src)
	Attach(M)

/obj/item/clothing/mask/facehugger/examine(mob/user)
	..()
	if(!real)//So that giant red text about probisci doesn't show up.
		return
	switch(stat)
		if(DEAD,UNCONSCIOUS)
			user << "[src] is not moving."
		if(CONSCIOUS)
			user << "[src] seems to be active!"
	if (sterile)
		user << "It looks like the proboscis has been removed."

/obj/item/clothing/mask/facehugger/attackby(obj/item/O,mob/m, params)
	if(O.force)
		Die()
	return

/obj/item/clothing/mask/facehugger/bullet_act(obj/item/projectile/P)
	if(P.damage)
		Die()
	return

/obj/item/clothing/mask/facehugger/temperature_expose(datum/gas_mixture/air, exposed_temperature, exposed_volume)
	if(exposed_temperature > 300)
		Die()
	return

/obj/item/clothing/mask/facehugger/equipped(mob/M)
	Attach(M)

/obj/item/clothing/mask/facehugger/Crossed(atom/target)
	HasProximity(target)
	return

/obj/item/clothing/mask/facehugger/on_found(mob/finder)
	if(stat == CONSCIOUS)
		return HasProximity(finder)
	return 0

/obj/item/clothing/mask/facehugger/HasProximity(atom/movable/AM as mob|obj)
	if(CanHug(AM) && Adjacent(AM))
		return Attach(AM)
	return 0

/obj/item/clothing/mask/facehugger/throw_at(atom/target, range, speed, mob/thrower, spin)
	if(!..())
		return
	if(stat == CONSCIOUS)
		icon_state = "[initial(icon_state)]_thrown"
		spawn(15)
			if(icon_state == "[initial(icon_state)]_thrown")
				icon_state = "[initial(icon_state)]"

/obj/item/clothing/mask/facehugger/throw_impact(atom/hit_atom)
	..()
	if(stat == CONSCIOUS)
		icon_state = "[initial(icon_state)]"
		Attach(hit_atom)

/obj/item/clothing/mask/facehugger/proc/Attach(mob/living/M)
	if(!isliving(M))
		return 0
	if((!iscorgi(M) && !iscarbon(M)) || isalien(M))
		return 0
	if(attached)
		return 0
	else
		attached++
		spawn(MAX_IMPREGNATION_TIME)
			attached = 0
	if(M.getorgan(/obj/item/organ/internal/alien/hivenode))
		return 0
	if(M.getorgan(/obj/item/organ/internal/body_egg/alien_embryo))
		return 0
	if(loc == M)
		return 0
	if(stat != CONSCIOUS)
		return 0
	if(!sterile) M.take_organ_damage(strength,0) //done here so that even borgs and humans in helmets take damage
	M.visible_message("[src] leaps at [M]'s face!", \
						"[src] leaps at [M]'s face!")
	if(ishuman(M))
		var/mob/living/carbon/human/H = M
		if(H.is_mouth_covered(head_only = 1))
			H.visible_message("[src] smashes against [H]'s [H.head]!", \
								"[src] smashes against [H]'s [H.head]!")
			Die()
			return 0
	if(iscarbon(M))
		var/mob/living/carbon/target = M
		if(target.wear_mask)
			if(prob(20))
				return 0
			var/obj/item/clothing/W = target.wear_mask
			if(W.flags & NODROP)
				return 0
			target.unEquip(W)

			target.visible_message("[src] tears [W] off of [target]'s face!", \
									"[src] tears [W] off of [target]'s face!")

		src.loc = target
		target.equip_to_slot(src, slot_wear_mask,,0)
		if(!sterile)
			M.Paralyse(MAX_IMPREGNATION_TIME/6) //something like 25 ticks = 20 seconds with the default settings
	else if (iscorgi(M))
		var/mob/living/simple_animal/pet/dog/corgi/C = M
		loc = C
		C.facehugger = src
		C.regenerate_icons()

	GoIdle() //so it doesn't jump the people that tear it off

	spawn(rand(MIN_IMPREGNATION_TIME,MAX_IMPREGNATION_TIME))
		Impregnate(M)

	return 1

/obj/item/clothing/mask/facehugger/proc/Impregnate(mob/living/target)
	if(!target || target.stat == DEAD) //was taken off or something
		return

	if(iscarbon(target))
		var/mob/living/carbon/C = target
		if(C.wear_mask != src)
			return

	if(!sterile)
		//target.contract_disease(new /datum/disease/alien_embryo(0)) //so infection chance is same as virus infection chance
		target.visible_message("[src] falls limp after violating [target]'s face!", \
								"[src] falls limp after violating [target]'s face!")

		Die()
		icon_state = "[initial(icon_state)]_impregnated"

		if(!target.getlimb(/obj/item/organ/limb/robot/chest) && !target.getorgan(/obj/item/organ/internal/body_egg/alien_embryo))
			new /obj/item/organ/internal/body_egg/alien_embryo(target)

		if(iscorgi(target))
			var/mob/living/simple_animal/pet/dog/corgi/C = target
			src.loc = get_turf(C)
			C.facehugger = null
	else
		target.visible_message("[src] violates [target]'s face!", \
								"[src] violates [target]'s face!")

/obj/item/clothing/mask/facehugger/proc/GoActive()
	if(stat == DEAD || stat == CONSCIOUS)
		return

	stat = CONSCIOUS
	icon_state = "[initial(icon_state)]"

/obj/item/clothing/mask/facehugger/proc/GoIdle()
	if(stat == DEAD || stat == UNCONSCIOUS)
		return

	stat = UNCONSCIOUS
	icon_state = "[initial(icon_state)]_inactive"

	spawn(rand(MIN_ACTIVE_TIME,MAX_ACTIVE_TIME))
		GoActive()
	return

/obj/item/clothing/mask/facehugger/proc/Die()
	if(stat == DEAD)
		return

	icon_state = "[initial(icon_state)]_dead"
	item_state = "facehugger_inactive"
	stat = DEAD

	visible_message("[src] curls up into a ball!")

/proc/CanHug(mob/living/M)
	if(!istype(M))
		return 0
	if(M.stat == DEAD)
		return 0
	if(M.getorgan(/obj/item/organ/internal/alien/hivenode))
		return 0

	if(iscorgi(M) || ismonkey(M))
		return 1

	var/mob/living/carbon/C = M
	if(ishuman(C) && !(slot_wear_mask in C.dna.species.no_equip))
		var/mob/living/carbon/human/H = C
		if(H.is_mouth_covered(head_only = 1))
			return 0
		return 1
	return 0


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

/obj/item/device/mmi
	name = "Man-Machine Interface"
	desc = "The Warrior's bland acronym, MMI, obscures the true horror of this monstrosity, that nevertheless has become standard-issue on Nanotrasen stations."
	icon = 'icons/obj/assemblies.dmi'
	icon_state = "mmi_empty"
	w_class = 3
	origin_tech = "biotech=3"
	var/braintype = "Cyborg"
	var/obj/item/device/radio/radio = null //Let's give it a radio.
	var/syndiemmi = 0 //Whether or not this is a Syndicate MMI
	var/mob/living/carbon/brain/brainmob = null //The current occupant.
	var/mob/living/silicon/robot = null //Appears unused.
	var/obj/mecha = null //This does not appear to be used outside of reference in mecha.dm.
	var/obj/item/organ/internal/brain/brain = null //The actual brain

/obj/item/device/mmi/update_icon()
	if(brain)
		if(istype(brain,/obj/item/organ/internal/brain/alien))
			if(brainmob && brainmob.stat == DEAD)
				icon_state = "mmi_alien_dead"
			else
				icon_state = "mmi_alien"
			braintype = "Xenoborg" //HISS....Beep.
		else
			if(brainmob && brainmob.stat == DEAD)
				icon_state = "mmi_dead"
			else
				icon_state = "mmi_full"
			braintype = "Cyborg"
	else
		icon_state = "mmi_empty"

/obj/item/device/mmi/New()
	..()
	radio = new(src) //Spawns a radio inside the MMI.
	radio.broadcasting = 0 //researching radio mmis turned the robofabs into radios because this didnt start as 0.

/obj/item/device/mmi/attackby(obj/item/O, mob/user, params)
	user.changeNext_move(CLICK_CD_MELEE)
	if(istype(O,/obj/item/organ/internal/brain)) //Time to stick a brain in it --NEO
		var/obj/item/organ/internal/brain/newbrain = O
		if(brain)
			user << "There's already a brain in the MMI!"
			return
		if(!newbrain.brainmob)
			user << "You aren't sure where this brain came from, but you're pretty sure it's a useless brain!"
			return

		if(!user.unEquip(O))
			return
		var/mob/living/carbon/brain/B = newbrain.brainmob
		if(!B.key)
			B.notify_ghost_cloning("Someone has put your brain in a MMI!", source = src)
		visible_message("[user] sticks \a [newbrain] into \the [src].")

		brainmob = newbrain.brainmob
		newbrain.brainmob = null
		brainmob.loc = src
		brainmob.container = src
		if(!newbrain.damaged_brain) // the brain organ hasn't been beaten to death.
			brainmob.stat = CONSCIOUS //we manually revive the brain mob
			dead_mob_list -= brainmob
			living_mob_list += brainmob

		brainmob.reset_perspective()
		newbrain.loc = src //P-put your brain in it
		brain = newbrain

		name = "Man-Machine Interface: [brainmob.real_name]"
		update_icon()

		feedback_inc("cyborg_mmis_filled",1)

		return

	else if(brainmob)
		O.attack(brainmob, user) //Oh noooeeeee
		return
	..()

/obj/item/device/mmi/attack_self(mob/user)
	if(!brain)
		radio.on = !radio.on
		user << "You toggle the MMI's radio system [radio.on==1 ? "on" : "off"]."
	else
		user << "You unlock and upend the MMI, spilling the brain onto the floor."

		brainmob.container = null //Reset brainmob mmi var.
		brainmob.loc = brain //Throw mob into brain.
		brainmob.stat = DEAD
		brainmob.emp_damage = 0
		brainmob.reset_perspective() //so the brainmob follows the brain organ instead of the mmi. And to update our vision
		living_mob_list -= brainmob //Get outta here
		dead_mob_list += brainmob
		brain.brainmob = brainmob //Set the brain to use the brainmob
		brainmob = null //Set mmi brainmob var to null

		user.put_in_hands(brain) //puts brain in the user's hand or otherwise drops it on the user's turf
		brain = null //No more brain in here

		update_icon()
		name = "Man-Machine Interface"

/obj/item/device/mmi/proc/transfer_identity(mob/living/L) //Same deal as the regular brain proc. Used for human-->robot people.
	if(!brainmob)
		brainmob = new(src)
	brainmob.name = L.real_name
	brainmob.real_name = L.real_name
	if(L.has_dna())
		var/mob/living/carbon/C = L
		if(!brainmob.dna)
			brainmob.dna = new /datum/dna(brainmob)
		C.dna.copy_dna(brainmob.dna)
	brainmob.container = src

	if(ishuman(L))
		var/mob/living/carbon/human/H = L
		var/obj/item/organ/internal/brain/newbrain = H.getorgan(/obj/item/organ/internal/brain)
		newbrain.loc = src
		brain = newbrain
	else if(!brain)
		brain = new(src)
		brain.name = "[L.real_name]'s brain"

	name = "Man-Machine Interface: [brainmob.real_name]"
	update_icon()
	return

/obj/item/device/mmi/verb/Toggle_Listening()
	set name = "Toggle Listening"
	set desc = "Toggle listening channel on or off."
	set category = "MMI"
	set src = usr.loc
	set popup_menu = 0

	if(brainmob.stat)
		brainmob << "Can't do that while incapacitated or dead!"
	if(!radio.on)
		brainmob << "Your radio is disabled!"
		return

	radio.listening = radio.listening==1 ? 0 : 1
	brainmob << "Radio is [radio.listening==1 ? "now" : "no longer"] receiving broadcast."

/obj/item/device/mmi/emp_act(severity)
	if(!brainmob)
		return
	else
		switch(severity)
			if(1)
				brainmob.emp_damage = min(brainmob.emp_damage + rand(20,30), 30)
			if(2)
				brainmob.emp_damage = min(brainmob.emp_damage + rand(10,20), 30)
			if(3)
				brainmob.emp_damage = min(brainmob.emp_damage + rand(0,10), 30)
		brainmob.emote("alarm")
	..()

/obj/item/device/mmi/Destroy()
	if(isrobot(loc))
		var/mob/living/silicon/robot/borg = loc
		borg.mmi = null
	if(brainmob)
		qdel(brainmob)
		brainmob = null
	return ..()

/obj/item/device/mmi/examine(mob/user)
	..()
	if(brainmob)
		var/mob/living/carbon/brain/B = brainmob
		if(!B.key || !B.mind || B.stat == DEAD)
			user << "The MMI indicates the brain is completely unresponsive."

		else if(!B.client)
			user << "The MMI indicates the brain is currently inactive; it might change."

		else
			user << "The MMI indicates the brain is active."

/obj/item/device/mmi/syndie
	name = "Syndicate Man-Machine Interface"
	desc = "Syndicate's own brand of MMI. It enforces laws designed to help Syndicate agents achieve their goals upon cyborgs created with it, but doesn't fit in Nanotrasen AI cores."
	syndiemmi = 1

/obj/item/device/mmi/syndie/New()
	..()
	radio.on = 0


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

/mob/living/carbon/brain
	languages = HUMAN
	var/obj/item/device/mmi/container = null
	var/timeofhostdeath = 0
	var/emp_damage = 0//Handles a type of MMI damage
	has_limbs = 0
	stat = DEAD //we start dead by default
	see_invisible = SEE_INVISIBLE_MINIMUM

/mob/living/carbon/brain/New(loc)
	..()
	if(isturf(loc)) //not spawned in an MMI or brain organ (most likely adminspawned)
		var/obj/item/organ/internal/brain/OB = new(loc) //we create a new brain organ for it.
		src.loc = OB
		OB.brainmob = src

/mob/living/carbon/brain/Destroy()
	if(key)				//If there is a mob connected to this thing. Have to check key twice to avoid false death reporting.
		if(stat!=DEAD)	//If not dead.
			death(1)	//Brains can die again. AND THEY SHOULD AHA HA HA HA HA HA
		ghostize()		//Ghostize checks for key so nothing else is necessary.
	container = null
	return ..()

/mob/living/carbon/brain/update_canmove()
	if(in_contents_of(/obj/mecha))
		canmove = 1
	else
		canmove = 0
	return canmove

/mob/living/carbon/brain/toggle_throw_mode()
	return

/mob/living/carbon/brain/ex_act() //you cant blow up brainmobs because it makes transfer_to() freak out when borgs blow up.
	return

/mob/living/carbon/brain/blob_act()
	return

/mob/living/carbon/brain/UnarmedAttack(atom/A)//Stops runtimes due to attack_animal being the default
	return

/mob/living/carbon/brain/check_ear_prot()
	return 1

/mob/living/carbon/brain/flash_eyes(intensity = 1, override_blindness_check = 0, affect_silicon = 0)
	return // no eyes, no flashing

/mob/living/carbon/brain/update_damage_hud()
	return //no red circles for brain

/mob/living/carbon/brain/can_be_revived()
	. = 1
	if(!container || health <= config.health_threshold_dead)
		return 0

/mob/living/carbon/brain/update_sight()
	return


code:
/obj/item/organ/internal/brain
	name = "brain"
	desc = "A piece of juicy meat found in a person's head."
	icon_state = "brain"
	throw_speed = 3
	throw_range = 5
	layer = 4.1
	zone = "head"
	slot = "brain"
	vital = 1
	origin_tech = "biotech=4"
	attack_verb = list("attacked", "slapped", "whacked")
	var/mob/living/carbon/brain/brainmob = null
	var/damaged_brain = 0 //whether the brain organ is damaged.

/obj/item/organ/internal/brain/Insert(mob/living/carbon/M, special = 0)
	..()
	name = "brain"
	if(brainmob)
		if(M.key)
			M.ghostize()

		if(brainmob.mind)
			brainmob.mind.transfer_to(M)
		else
			M.key = brainmob.key

		qdel(brainmob)

	//Update the body's icon so it doesnt appear debrained anymore
	if(ishuman(M))
		var/mob/living/carbon/human/H = M
		H.update_hair(0)

/obj/item/organ/internal/brain/Remove(mob/living/carbon/M, special = 0)
	..()
	if(!special)
		transfer_identity(M)
	if(ishuman(M))
		var/mob/living/carbon/human/H = M
		H.update_hair(0)

/obj/item/organ/internal/brain/prepare_eat()
	return // Too important to eat.

/obj/item/organ/internal/brain/proc/transfer_identity(mob/living/L)
	name = "[L.name]'s brain"
	brainmob = new(src)
	brainmob.name = L.real_name
	brainmob.real_name = L.real_name
	brainmob.timeofhostdeath = L.timeofdeath
	if(L.has_dna())
		var/mob/living/carbon/C = L
		if(!brainmob.dna)
			brainmob.dna = new /datum/dna(brainmob)
		C.dna.copy_dna(brainmob.dna)
	if(L.mind && L.mind.current && (L.mind.current.stat == DEAD))
		L.mind.transfer_to(brainmob)
	brainmob << "You feel slightly disoriented. That's normal when you're just a brain."

/obj/item/organ/internal/brain/attackby(obj/item/O, mob/user, params)
	user.changeNext_move(CLICK_CD_MELEE)
	if(brainmob)
		O.attack(brainmob, user) //Oh noooeeeee

/obj/item/organ/internal/brain/examine(mob/user)
	..()

	if(brainmob)
		if(brainmob.client)
			if(brainmob.health <= config.health_threshold_dead)
				user << "It's lifeless and severely damaged."
			else
				user << "You can feel the small spark of life still left in this one."
		else
			user << "This one seems particularly lifeless. Perhaps it will regain some of its luster later."
	else
		user << "This one is completely devoid of life."

/obj/item/organ/internal/brain/attack(mob/living/carbon/M, mob/user)
	if(!istype(M))
		return ..()

	add_fingerprint(user)

	if(user.zone_selected != "head")
		return ..()

	var/mob/living/carbon/human/H = M
	if(istype(M, /mob/living/carbon/human) && ((H.head && H.head.flags_cover & HEADCOVERSEYES) || (H.wear_mask && H.wear_mask.flags_cover & MASKCOVERSEYES) || (H.glasses && H.glasses.flags & GLASSESCOVERSEYES)))
		user << "You're going to need to remove their head cover first!"
		return

//since these people will be dead M != usr

	if(!M.getorgan(/obj/item/organ/internal/brain))
		user.drop_item()
		for(var/mob/O in viewers(M, null))
			if(O == (user || M))
				continue
			if(M == user)
				O << "[user] inserts [src] into \his head!"
			else
				O << "[M] has [src] inserted into \his head by [user]."

		if(M != user)
			M << "[user] inserts [src] into your head."
			user << "You insert [src] into [M]'s head."
		else
			user << "You insert [src] into your head."	//LOL

		Insert(M)
	else
		..()

/obj/item/organ/internal/brain/Destroy() //copypasted from MMIs.
	if(brainmob)
		qdel(brainmob)
		brainmob = null
	return ..()

/obj/item/organ/internal/brain/alien
	name = "alien brain"
	desc = "We barely understand the brains of terrestial animals. Who knows what we may find in the brain of such an advanced species?"
	icon_state = "brain-x"
	origin_tech = "biotech=7"


code:
/mob/living/carbon/brain/death(gibbed)
	if(stat == DEAD)
		return
	stat = DEAD

	if(!gibbed && container)//If not gibbed but in a container.
		var/obj/item/device/mmi = container
		mmi.visible_message("[src]'s MMI flatlines!", \
					"You hear something flatline.")
		mmi.update_icon()

	return ..()

/mob/living/carbon/brain/gib(animation = 0)
	if(container)
		qdel(container)//Gets rid of the MMI if there is one
	if(loc)
		if(istype(loc,/obj/item/organ/internal/brain))
			qdel(loc)//Gets rid of the brain item
	..()


code:
/mob/living/carbon/brain/emote(act,m_type=1,message = null)
	if(!(container && istype(container, /obj/item/device/mmi)))//No MMI, no emotes
		return

	if (findtext(act, "-", 1, null))
		var/t1 = findtext(act, "-", 1, null)
		act = copytext(act, 1, t1)

	if(src.stat == DEAD)
		return
	switch(act)
		if ("alarm")
			src << "You sound an alarm."
			message = "[src] sounds an alarm."
			m_type = 2

		if ("alert")
			src << "You let out a distressed noise."
			message = "[src] lets out a distressed noise."
			m_type = 2

		if ("beep","beeps")
			src << "You beep."
			message = "[src] beeps."
			m_type = 2

		if ("blink","blinks")
			message = "[src] blinks."
			m_type = 1

		if ("boop","boops")
			src << "You boop."
			message = "[src] boops."
			m_type = 2

		if ("flash")
			message = "The lights on [src] flash quickly."
			m_type = 1

		if ("notice")
			src << "You play a loud tone."
			message = "[src] plays a loud tone."
			m_type = 2

		if ("whistle","whistles")
			src << "You whistle."
			message = "[src] whistles."
			m_type = 2

		if ("help")
			src << "Help for MMI emotes. You can use these emotes with say \"*emote\":\nalarm, alert, beep, blink, boop, flash, notice, whistle"

		else
			src << "Unusable emote '[act]'. Say *help for a list."
			return

	if (message)
		log_emote("[name]/[key] : [message]")

		for(var/mob/M in dead_mob_list)
			if (!M.client || istype(M, /mob/new_player))
				continue //skip monkeys, leavers, and new_players
			if(M.stat == DEAD && (M.client && (M.client.prefs.chat_toggles & CHAT_GHOSTSIGHT)) && !(M in viewers(src,null)))
				M.show_message(message)

		if (m_type & 1)
			visible_message(message)
		else if (m_type & 2)
			audible_message(message)


code:
/mob/living/carbon/brain/Life()
	set invisibility = 0
	set background = BACKGROUND_ENABLED

	if (notransform)
		return
	if(!loc)
		return
	. = ..()
	handle_emp_damage()

/mob/living/carbon/brain/handle_breathing()
	return

/mob/living/carbon/brain/handle_mutations_and_radiation()
	return

/mob/living/carbon/brain/handle_environment(datum/gas_mixture/environment)
	return

/mob/living/carbon/brain/update_stat()
	if(status_flags & GODMODE)
		return
	if(health <= config.health_threshold_dead)
		if(stat != DEAD)
			death()
		var/obj/item/organ/internal/brain/BR
		if(container && container.brain)
			BR = container.brain
		else if(istype(loc, /obj/item/organ/internal/brain))
			BR = loc
		if(BR)
			BR.damaged_brain = 1 //beaten to a pulp

/* //currently unused feature, since brain outside a mmi is always dead.
/mob/living/carbon/brain/proc/handle_brain_revival_life()
	if(stat != DEAD)
		if(config.revival_brain_life != -1)
			if( !container && (world.time - timeofhostdeath) > config.revival_brain_life)
				death()
*/

/mob/living/carbon/brain/proc/handle_emp_damage()
	if(emp_damage)
		if(stat == DEAD)
			emp_damage = 0
		else
			emp_damage = max(emp_damage-1, 0)

/mob/living/carbon/brain/handle_status_effects()
	return

/mob/living/carbon/brain/handle_disabilities()
	return

/mob/living/carbon/brain/setEarDamage() // no ears to damage or heal
	return

/mob/living/carbon/brain/adjustEarDamage()
	return

/mob/living/carbon/brain/blind_eyes() // no eyes to damage or heal
	return

/mob/living/carbon/brain/blur_eyes()
	return

/mob/living/carbon/brain/adjust_blindness()
	return

/mob/living/carbon/brain/adjust_blurriness()
	return

/mob/living/carbon/brain/set_blindness()
	return

/mob/living/carbon/brain/set_blurriness()
	return

/mob/living/carbon/brain/become_blind()
	return

/mob/living/carbon/brain/handle_changeling()
	return


code:
var/global/posibrain_notif_cooldown = 0

/obj/item/device/mmi/posibrain
	name = "positronic brain"
	desc = "A cube of shining metal, four inches to a side and covered in shallow grooves."
	icon = 'icons/obj/assemblies.dmi'
	icon_state = "posibrain"
	w_class = 3
	origin_tech = "biotech=3;programming=2"
	var/notified = 0
	var/askDelay = 10 * 60 * 1
	var/used = 0 //Prevents split personality virus. May be reset if personality deletion code is added.
	brainmob = null
	req_access = list(access_robotics)
	mecha = null//This does not appear to be used outside of reference in mecha.dm.
	braintype = "Android"

/obj/item/device/mmi/posibrain/Topic(href, href_list)
	if(href_list["activate"])
		var/mob/dead/observer/ghost = usr
		if(istype(ghost))
			activate(ghost)

/obj/item/device/mmi/posibrain/proc/ping_ghosts(msg)
	if(!posibrain_notif_cooldown)
		notify_ghosts("Positronic brain [msg] in [get_area(src)]!", 'sound/effects/ghost2.ogg', enter_link="(Click to enter)", source = src, attack_not_jump = 1)
		posibrain_notif_cooldown = 1
		spawn(askDelay) //Global one minute cooldown to avoid spam.
			posibrain_notif_cooldown = 0

/obj/item/device/mmi/posibrain/attack_self(mob/user)
	if(brainmob && !brainmob.key && !notified)
		//Start the process of requesting a new ghost.
		user << "You carefully locate the manual activation switch and start the positronic brain's boot process."
		ping_ghosts("requested")
		notified = 1
		used = 0
		update_icon()
		spawn(askDelay) //Seperate from the global cooldown.
			notified = 0
			update_icon()
			if(brainmob.client)
				visible_message("The positronic brain pings, and its lights start flashing. Success!")
			else
				visible_message("The positronic brain buzzes quietly, and the golden lights fade away. Perhaps you could try again?")

	return //Code for deleting personalities recommended here.

/obj/item/device/mmi/posibrain/attack_ghost(mob/user)
	activate(user)

//Two ways to activate a positronic brain. A clickable link in the ghost notif, or simply clicking the object itself.
/obj/item/device/mmi/posibrain/proc/activate(mob/user)
	if(used || (brainmob && brainmob.key) || jobban_isbanned(user,"posibrain"))
		return

	var/posi_ask = alert("Become a positronic brain? (Warning, You can no longer be cloned, and all past lives will be forgotten!)","Are you positive?","Yes","No")
	if(posi_ask == "No" || qdeleted(src))
		return
	transfer_personality(user)

/obj/item/device/mmi/posibrain/transfer_identity(mob/living/carbon/C)
	name = "positronic brain ([C])"
	brainmob.name = C.real_name
	brainmob.real_name = C.real_name
	brainmob.dna = C.dna
	if(C.has_dna())
		if(!brainmob.dna)
			brainmob.dna = new /datum/dna(brainmob)
		C.dna.copy_dna(brainmob.dna)
	brainmob.timeofhostdeath = C.timeofdeath
	brainmob.stat = CONSCIOUS
	if(brainmob.mind)
		brainmob.mind.assigned_role = "Positronic Brain"
	if(C.mind)
		C.mind.transfer_to(brainmob)

	brainmob.mind.remove_all_antag()
	brainmob.mind.wipe_memory()

	brainmob << "ALL PAST LIVES ARE FORGOTTEN."

	brainmob << "Hello World!"
	update_icon()
	return

/obj/item/device/mmi/posibrain/proc/transfer_personality(mob/candidate)
	if(used || (brainmob && brainmob.key)) //Prevents hostile takeover if two ghosts get the prompt or link for the same brain.
		candidate << "This brain has already been taken! Please try your possesion again later!"
		return
	notified = 0
	brainmob.ckey = candidate.ckey
	name = "positronic brain ([brainmob.name])"

	brainmob << "ALL PAST LIVES ARE FORGOTTEN."

	brainmob << "You are a positronic brain, brought into existence on [station_name()]."
	brainmob << "As a synthetic intelligence, you answer to all crewmembers, as well as the AI."
	brainmob << "Remember, the purpose of your existence is to serve the crew and the station. Above all else, do no harm."
	brainmob.mind.assigned_role = "Positronic Brain"
	brainmob.stat = CONSCIOUS
	dead_mob_list -= brainmob
	living_mob_list += brainmob

	visible_message("The positronic brain chimes quietly.")
	update_icon()
	used = 1

/obj/item/device/mmi/posibrain/examine()

	set src in oview()

	if(!usr || !src)
		return
	if( (usr.disabilities & BLIND || usr.stat) && !istype(usr,/mob/dead/observer) )
		usr << "Something is there but you can't see it."
		return

	var/msg = "*---------*\nThis is \icon[src] \a [src]!\n[desc]\n"
	msg += ""

	if(brainmob && brainmob.key)
		switch(brainmob.stat)
			if(CONSCIOUS)
				if(!src.brainmob.client)
					msg += "It appears to be in stand-by mode.\n" //afk
			if(DEAD)
				msg += "It appears to be completely inactive.\n"
	else
		msg += "It appears to be completely inactive. The reset light is blinking.\n"
	msg += "*---------*"
	usr << msg
	return

/obj/item/device/mmi/posibrain/New()
	brainmob = new(src)
	brainmob.name = "[pick(list("PBU","HIU","SINA","ARMA","OSI","HBL","MSO","RR","CHRI","CDB","HG","XSI","ORNG","GUN","KOR","MET","FRE","XIS","SLI","PKP","HOG","RZH","GOOF","MRPR","JJR","FIRC","INC","PHL","BGB","ANTR","MIW","WJ","JRD","CHOC","ANCL","JLLO","JNLG","KOS","TKRG","XAL","STLP","CBOS","DUNC","FXMC","DRSD"))]-[rand(100, 999)]"
	brainmob.real_name = brainmob.name
	brainmob.loc = src
	brainmob.container = src
	ping_ghosts("created")
	..()

/obj/item/device/mmi/posibrain/attackby(obj/item/O, mob/user)
	return

/obj/item/device/mmi/posibrain/update_icon()
	if(notified)
		icon_state = "posibrain-searching"
		return
	if(brainmob && brainmob.key)
		icon_state = "posibrain-occupied"
	else
		icon_state = "posibrain"


code:
/mob/living/carbon/brain/say(message)
	if(!(container && istype(container, /obj/item/device/mmi)))
		return //No MMI, can't speak, bucko./N
	else
		if(prob(emp_damage*4))
			if(prob(10))//10% chane to drop the message entirely
				return
			else
				message = Gibberish(message, (emp_damage*6))//scrambles the message, gets worse when emp_damage is higher
		..()

/mob/living/carbon/brain/radio(message, message_mode, list/spans)
	if(message_mode && istype(container, /obj/item/device/mmi))
		var/obj/item/device/mmi/R = container
		if(R.radio)
			R.radio.talk_into(src, message, , spans)
			return ITALICS | REDUCE_RANGE

/mob/living/carbon/brain/lingcheck()
	return 0