#On actions about titles

# All on-actions in this file provide scope:transfer_type unless otherwise noted
# scope:transfer_type has the following permutations:
# flag:conquest
# flag:conquest_holy_war
# flag:conquest_claim
# flag:conquest_populist
# flag:inheritance
# flag:abdication
# flag:destroyed
# flag:created
# flag:usurped
# flag:granted
# flag:revoked
# flag:election
# flag:independency
# flag:returned
# flag:leased_out
# flag:lease_revoked
# flag:faction_demand
# flag:swear_fealty
# flag:stepped_down

# A title is destroyed
# root = the holder before destruction
# scope:landed_title = the title that is being destroyed
# Does *not* provide scope:transfer_type
on_title_destroyed = {
	events = {
		british_isles.1031	# Danelaw-England partition calc.
	}

	effect = {
		scope:landed_title = {
			every_claimant = { remove_claim = prev } # remove existing claims
		}
		# Adjust the size of the laamps tally.
		if = {
			limit = {
				# Pre-filter out anything higher or lower.
				scope:landed_title = { tier = tier_duchy }
				has_global_variable_list = laamps_tally
			}
			# We don't need to check the list twice, since if they're not in it then removing them from it won't do anything.
			remove_list_global_variable = {
				name = laamps_tally
				target = scope:landed_title
			}
		}
		#Notify folks the latin empire has fallen
		if = {
			limit = { scope:landed_title = title:e_latin_empire }
			frankokratia_latin_emp_end_msg_effect = yes
		}
		#Create byz collapse variable that defines anarchy period
		if = {
			limit = {
				scope:landed_title = {
					this = title:e_byzantium
				}
			}
			if = {
				limit = {
					exists = global_var:byz_collapse_counter
				}
				remove_global_variable = byz_collapse_counter
			}
			set_global_variable = {
				name = byz_collapse_counter
				value = {
					value = current_year
					add = 100
				}
			}
		}
		
		# If the title of an independent admin ruler is destroyed, let's make sure we handle any stray admin vassals
		if = {
			limit = {
				government_has_flag = government_is_administrative
				is_independent_ruler = yes
				NOT = {
					any_held_title = {
						tier > tier_duchy
						NOT = { this = scope:landed_title }
						is_noble_family_title = no
					}
				}
			}
			admin_change_government_effect = yes
		}
	}
}

# A title is transferred to a new character
# root = the new holder
# scope:title = the title that changes hands
# scope:previous_holder = previous holder. Might be dead
on_title_gain = {
	effect = {
		# Nomads
		scope:title = {
			if = {
				limit = {
					is_nomad_title = yes
					exists = title_domicile
				}
				if = {
					limit = {
						root = {
							any_held_title = {
								is_nomad_title = yes
								exists = title_domicile
								NOT = { this = scope:title }
							}
						}
					}
					if = {
						limit = {
							root = {
								any_held_title = {
									is_nomad_title = yes
									exists = title_domicile
									NOT = { this = scope:title }
									exists = var:player_domicile_title
								}
							}
						}
						root = {
							random_held_title = {
								limit = {
									is_nomad_title = yes
									exists = title_domicile
									NOT = { this = scope:title }
									exists = var:player_domicile_title
								}
								title_domicile = {
									if = {
										limit = {
											exists = root.dynasty
											scope:previous_holder.dynasty ?= root.dynasty
										}
										change_herd = {
											value = scope:title.title_domicile.herd
										}
									}
								}
								root = {
									destroy_title = scope:title
								}
							}
						}
					}
					else_if = {
						limit = {
							is_nomad_title = yes
							exists = title_domicile
							exists = var:player_domicile_title
						}
						root = {
							random_held_title = {
								limit = {
									is_nomad_title = yes
									exists = title_domicile
									NOT = { this = scope:title }
								}
								save_scope_as = old_nomad_title_to_clean_up
							}
						}
						title_domicile = {
							if = {
								limit = {
									exists = root.dynasty
									scope:previous_holder.dynasty ?= root.dynasty
								}
								change_herd = {
									value = scope:old_nomad_title_to_clean_up.title_domicile.herd
								}
							}
						}
						root = {
							destroy_title = scope:old_nomad_title_to_clean_up
						}
					}
					else_if = {
						limit = {
							root = {
								any_held_title = {
									is_nomad_title = yes
									exists = title_domicile
									NOT = { this = scope:title }
									title_domicile.herd > scope:title.title_domicile.herd
								}
							}
						}
						root = {
							random_held_title = {
								limit = {
									is_nomad_title = yes
									exists = title_domicile
									NOT = { this = scope:title }
									title_domicile.herd > scope:title.title_domicile.herd
								}
								title_domicile = {
									if = {
										limit = {
											exists = root.dynasty
											scope:previous_holder.dynasty ?= root.dynasty
										}
										change_herd = {
											value = scope:title.title_domicile.herd
										}
									}
								}
							}
							destroy_title = scope:title
						}
					}
					else = {
						root = {
							random_held_title = {
								limit = {
									is_nomad_title = yes
									exists = title_domicile
									NOT = { this = scope:title }
								}
								save_scope_as = old_nomad_title_to_clean_up
							}
						}
						title_domicile = {
							if = {
								limit = {
									exists = root.dynasty
									scope:previous_holder.dynasty ?= root.dynasty
								}
								change_herd = {
									value = scope:old_nomad_title_to_clean_up.title_domicile.herd
								}
							}
						}
						root = {
							destroy_title = scope:old_nomad_title_to_clean_up
						}
					}
				}
				if = {
					limit = {
						exists = title_domicile
						exists = global_var:game_has_started
						NOT = {
							exists = previous_holder
						}
					}
					if = {
						limit = {
							root = {
								OR = {
									house.house_head ?= {
										this != root
										any_held_title = {
											is_nomad_title = yes
										}
									}
									dynasty.dynast ?= {
										this != root
										any_held_title = {
											is_nomad_title = yes
										}
									}
									any_close_family_member = {
										this != root
										any_held_title = {
											is_nomad_title = yes
										}
									}
								}
							}
						}
						generate_coa = yes # To lessen confusion thinking titles are the same
					}
					if = {
						limit = {
							current_year >= 1300
						}
						title_domicile = {
							add_domicile_building = yurt_main_02
							add_domicile_building = yurt_main_03
							add_domicile_building = yurt_main_04
							add_random_yurt_external_building_effect = yes
							add_random_yurt_external_building_effect = yes
							add_random_yurt_external_building_effect = yes
							add_random_yurt_external_building_effect = yes
							add_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
						}
					}
					else_if = {
						limit = {
							current_year >= 1200
						}
						title_domicile = {
							add_domicile_building = yurt_main_02
							add_domicile_building = yurt_main_03
							add_domicile_building = yurt_main_04
							add_random_yurt_external_building_effect = yes
							add_random_yurt_external_building_effect = yes
							add_random_yurt_external_building_effect = yes
							add_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
						}
					}
					else_if = {
						limit = {
							current_year >= 1100
						}
						title_domicile = {
							add_domicile_building = yurt_main_02
							if = {
								limit = {
									has_domicile_building = yurt_main_02
									owner ?= {
										OR = {
											has_realm_law = nomadic_authority_2
											has_realm_law = nomadic_authority_3
											has_realm_law = nomadic_authority_4
											has_realm_law = nomadic_authority_5
										}
									}
								}
								add_domicile_building = yurt_main_03
							}
							add_random_yurt_external_building_effect = yes
							add_random_yurt_external_building_effect = yes
							add_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
						}
					}
					else_if = {
						limit = {
							current_year >= 900
						}
						title_domicile = {
							add_domicile_building = yurt_main_02
							add_random_yurt_external_building_effect = yes
							add_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
							upgrade_random_yurt_external_building_effect = yes
						}
					}
				}
			}
			###########
			# Nomads switch faith/culture of conquered nomadic counties
			###########
			if = {
				limit = {
					tier = tier_county
					title_province ?= {
						OR = {
							has_holding_type = nomad_holding
							has_holding_type = herder_holding
						}
					}
					root = {
						government_has_flag = government_is_nomadic
						exists = domicile
					}
				}
				if = {
					limit = {
						root = {
							has_character_flag = domicile_culture_and_faith_check
							OR = {
								domicile.domicile_culture != scope:title.culture
								domicile.domicile_faith != scope:title.faith
							}
						}
					}
					root.domicile = {
						set_domicile_culture = scope:title.culture
						set_domicile_faith = scope:title.faith
					}
					root = {
						remove_character_flag = domicile_culture_and_faith_check
					}
				}
				else = {
					if = {
						limit = {
							root.domicile.domicile_culture != scope:title.culture
						}
						scope:title ?= {
							set_variable = {
								name = migration_previous_culture
								value = culture
							}
						}
						set_county_culture = root.domicile.domicile_culture
					}
					if = {
						limit = {
							root.domicile.domicile_faith != scope:title.faith
						}
						set_county_faith = root.domicile.domicile_faith
					}
				}
			}
		}
		###########
		# Nomads leaving confederacies
		###########
		if = {
			limit = { 
				is_confederation_member = yes
				scope:title.tier >= tier_kingdom
			}
			confederation = {
				remove_confederation_member = root
			}
		}
		# EP3 ADVENTURERS BECOMING LANDED
		if = {
			limit = {
				scope:title = { is_titular = no }
				any_held_title = { has_variable = adventurer_creation_reason }
			}
			save_scope_as = adventurer
			if = {
				limit = {
					NOR = { 
						has_trait = adventurer 
						government_has_flag = government_is_nomadic
					}
				}
				add_trait = adventurer
			}
			every_courtier = {
				set_variable = {
					name = former_camp_leader
					value = scope:adventurer
				}
				add_trait = adventurer_follower
			}
			if = {
				limit = {
					house = {
						has_house_modifier = legacy_adventurer_house_modifier
					}
				}
				add_legitimacy = massive_legitimacy_gain
				set_variable = {
					name = legacy_adventurers_to_levies
					value = 0
				}
				every_courtier = { 
					root = { 
						change_variable = { name = legacy_adventurers_to_levies add = 25 }
					} 
				}
				every_held_title = {
					limit = { has_variable = adventurer_creation_reason }
					save_scope_as = prev_title
				}
				spawn_army = {
					levies = var:legacy_adventurers_to_levies
					location = capital_province
					name = remnants_adventurer_army
				}
				remove_variable = legacy_adventurers_to_levies
			}
			destroy_laamp_effect = { ADVENTURER = scope:adventurer }
			# EP3 - Ensure NF holders are Admin
			if = {
				limit = {
					scope:title = { is_noble_family_title = yes }
					NOT = { government_has_flag = government_is_administrative }
				}
				change_government = administrative_government
			}
		}
		# Note: anything that should be run after creation can go in on_noble_family_title_created
		if = {
			limit = {
				OR = {
					government_has_flag = government_is_administrative
					government_has_flag = government_is_special_republic
				}
				highest_held_title_tier >= tier_county
				liege = {
					is_independent_ruler = yes
					government_has_flag = government_is_administrative
				}
			}
			domicile ?= { set_up_domicile_estate_effect = yes }
		}
		# Apply Law of the Land title succession law if appropriate 
		scope:title = {
			add_law_of_the_land_title_succession_law_if_appropriate_effect = yes
		}
		# MPO - edge case Nomadic Philosophy handover, factions, unlikely claimants, etc etc
		if = {
			limit = {
				primary_title = {
					this = scope:title
				}
				government_has_flag = government_is_nomadic
				NOT = {
					has_trait = nomadic_philosophy
				}
				exists = situation:the_great_steppe
				any_character_situation = {
					this = situation:the_great_steppe
				}
			}
			add_trait = nomadic_philosophy
			every_heir = {
				limit = {
					top_liege ?= root
					NOT = {
						has_trait = nomadic_philosophy
					}
				}
				add_trait = nomadic_philosophy
			}
		}
		# MPO - Siberian permafrost modifier switcharoo
		if = {
			limit = {
				scope:title = {
					tier = tier_county
					title_province = {
						geographical_region = geographical_region:mpo_region_permafrost
					}
				}
			}
			if = {
				limit = {
					scope:title = {
						has_county_modifier = mpo_siberian_permafrost_modifier_bad
					}	
					culture ?= scope:title.culture
					culture ?= { has_cultural_parameter = permafrost_modifier_mechanic }
				}
				scope:title = {
					remove_county_modifier = mpo_siberian_permafrost_modifier_bad
					add_county_modifier = mpo_siberian_permafrost_modifier
				}			
			}
			else_if = {
				limit = {
					scope:title = {
						has_county_modifier = mpo_siberian_permafrost_modifier
					}				
					NOT = {
						culture ?= scope:title.culture
						culture ?= { has_cultural_parameter = permafrost_modifier_mechanic }
					}
				}
				scope:title = {
					remove_county_modifier = mpo_siberian_permafrost_modifier
					add_county_modifier = mpo_siberian_permafrost_modifier_bad
				}	
			}
				
		}
		# EP3 - Ensure Emperor keeps old realm capital in admin realms & apply unique domicile building bonus if appropriate
		if = {
			limit = {
				government_has_flag = government_is_administrative
				is_independent_ruler = yes
				highest_held_title_tier >= tier_empire
			}
			if = { # Ensure we keep the old realm capital
				limit = {
					scope:title = {
						tier = tier_empire
						NOT = { title_capital_county = root.capital_county }
						# Constantinople must have been inherited
						title_capital_county.holder = root
					}
				}
				set_realm_capital = scope:title.title_capital_county
			}
			if = { # Get legitimacy from Reception Hall House Bonus
				limit = {
					house = { has_variable = ep3_legacy_legitimacy_counter }
					primary_title = scope:title
				}
				trigger_event = {
					id = ep3_admin_events.0010
					days = 1
				}
			}
		}
		# EP3 - Fire a became governor event
		else_if = {
			limit = {
				government_has_flag = government_is_administrative
				is_independent_ruler = no
				is_governor = yes
				any_held_title = {
					count < 1
					NOT = { this = scope:title }
					tier >= scope:title.tier
					is_landless_type_title = no
					is_noble_family_title = no
				}
			}
			trigger_event = {
				id = ep3_admin_events.0002
				delayed = yes
			}
		}

		scope:title = { update_dynamic_coa = yes }

		if = {
			limit = {
				scope:title = { is_holy_order = yes }
				NOT = { has_trait = order_member }
				government_has_flag = government_is_holy_order
			}
			add_trait = order_member
		}
		
		if = {
			limit = {
				has_character_flag = peasant_outfit
				NOT = { government_has_flag = government_is_herder }
			}
			remove_character_flag = peasant_outfit
		}

		# Did I receive a title from my sibling?
		if = {
			limit = {
				exists = scope:previous_holder
				scope:previous_holder = {
					is_alive = yes
					exists = var:sibling_waiting_for_land
					any_sibling = {
						this = root
						this = scope:previous_holder.var:sibling_waiting_for_land
					}
				}
			}
			add_character_flag = {
				flag = got_title_from_sibling
				years = 4
			}
		}

		# Grandeur in elective realms
		if = {
			limit = {
				exists = var:previous_holder_grandeur_value
				has_royal_court = yes
				has_dlc_feature = royal_court
			}
			hidden_effect = {
				change_current_court_grandeur = -100 # Reset to 0
				change_current_court_grandeur = var:previous_holder_grandeur_value
				remove_variable = previous_holder_grandeur_value
			}
		}

		# Petition allowed again
		if = {
			limit = { has_variable = petition_title_cooldown }
			remove_variable = petition_title_cooldown
		}

		# If a player is on their way to pay homage, invalidate.
		if = {
			limit = {
				exists = scope:previous_holder
				any_player = { var:homage_liege_scope ?= scope:previous_holder }
			}
			every_player = {
				limit = {
					var:homage_liege_scope ?= scope:previous_holder
					NOT = { has_character_flag = currently_invalidating_petition_liege_travel }
				}
				current_travel_plan = { cancel_travel_plan = yes }
				trigger_event = pay_homage.0601
				add_character_flag = {
					flag = currently_invalidating_petition_liege_travel
					days = 1
				}
			}
		}

		if = {
			limit = {
				exists = scope:previous_holder
				scope:previous_holder = {
					any_character_artifact = {
						has_variable = artifact_succession_title #Is this an artifact that should follow a title?
						var:artifact_succession_title = { is_title_created = yes } #Does the title the artifact should follow exist?
						var:artifact_succession_title = scope:title #Scope title is the artifact title
					}
				}
			}
			scope:previous_holder = {
				every_character_artifact = {
					limit = {
						has_variable = artifact_succession_title #Is this an artifact that should follow a title?
						var:artifact_succession_title = { is_title_created = yes } #Does the title the artifact should follow exist?
						var:artifact_succession_title = scope:title #Scope title is the artifact title
					}
					if = {
						limit = {
							OR = {
								scope:transfer_type = flag:conquest
								scope:transfer_type = flag:conquest_holy_war
								scope:transfer_type = flag:conquest_claim
								scope:transfer_type = flag:conquest_populist
								scope:transfer_type = flag:abdication
								scope:transfer_type = flag:usurped
								scope:transfer_type = flag:revoked
								scope:transfer_type = flag:faction_demand
							}
						}
						set_owner = {
							target = root
							history = {
								type = conquest
								actor = scope:previous_holder
								recipient = root
								location = scope:previous_holder.location
							}
						}
					}
					else = {
						set_owner = {
							target = root
							history = {
								type = inherited
								recipient = root
							}
						}
					}
				}
			}
		}

		# FP3 Title Transfer Notification
		if = {
			limit = {
				exists = struggle:persian_struggle
				OR = {
					scope:title = title:d_sunni
					scope:title = title:e_arabia
				}
			}
			struggle:persian_struggle = { # Wet script
				every_involved_ruler = {
					send_interface_toast = {
						type = event_toast_effect_bad
						title = persian_struggle_central_title_transfer.t
						left_icon = scope:previous_holder
						right_icon = scope:title.holder

						custom_tooltip = persian_struggle_central_title_transfer.desc
					}
				}
				every_interloper_ruler = {
					send_interface_toast = {
						type = event_toast_effect_bad
						title = persian_struggle_central_title_transfer.t
						left_icon = scope:previous_holder
						right_icon = scope:title.holder

						custom_tooltip = persian_struggle_central_title_transfer.desc
					}
				}
			}
		}

		#Struggle Catalyst
		if = {
			limit = {
				exists = struggle:persian_struggle
				exists = scope:title.empire
				scope:title = {
					empire = title:e_persia
					tier >= tier_county
					is_landless_type_title = no
				}
				NOR = {
					scope:transfer_type = flag:created
					scope:transfer_type = flag:inheritance
				}
			}
			if = {
				limit = {
					fp3_character_uninvolved_in_struggle_trigger = yes
					scope:previous_holder ?= {
						fp3_character_involved_in_struggle_trigger = yes
						any_character_struggle = {
							phase_has_catalyst = catalyst_interloper_uninvolved_gain_struggle_titles
						}
					}
				}
				scope:previous_holder ?= {
					every_character_struggle = {
						limit = { phase_has_catalyst = catalyst_interloper_uninvolved_gain_struggle_titles }
						activate_struggle_catalyst = {
							catalyst = catalyst_interloper_uninvolved_gain_struggle_titles
							character = root
						}
						log_debug_variable_for_persian_struggle_effect = { VAR = concession_catalyst_interloper_uninvolved_gain_struggle_titles }
					}
				}
			}
			if = {
				limit = {
					fp3_character_involved_in_struggle_trigger = yes
					any_character_struggle = {
						phase_has_catalyst = catalyst_gain_struggle_titles_from_interlopers_uninvolved
						# Stop catalyst from affecting those who are only just now uninvolved due to losing this title
						OR = {
							NOT = { is_culture_involved_in_struggle = scope:previous_holder.culture }
							NOT = { is_faith_involved_in_struggle = scope:previous_holder.faith }
						}
					}
					scope:previous_holder ?= {
						OR = {
							fp3_character_uninvolved_in_struggle_trigger = yes
							fp3_character_interloper_in_struggle_trigger = yes
						}
					}
				}
				every_character_struggle = {
					limit = { phase_has_catalyst = catalyst_gain_struggle_titles_from_interlopers_uninvolved }
					activate_struggle_catalyst = {
						catalyst = catalyst_gain_struggle_titles_from_interlopers_uninvolved
						character = root
					}
					log_debug_variable_for_persian_struggle_effect = { VAR = stabil_catalyst_gain_struggle_titles_from_interlopers_uninvolved }
				}
			}
		}

		# Achievements
		if = { # FP2 El Cid
			limit = {
				scope:title = title:k_valencia
				has_character_flag = fp2_el_cid_blood_relation_legacy
			}
			set_global_variable = { # DO. NOT. USE. add_achievement_global_variable_effect. IT BREAKS THE ACHIEVEMENT.
				name = fp2_el_cid_achievement_unlocked
				value = yes
			}
		}

		# Am I The Chad?
		if = {
			limit = { root = character:easteregg_chad_uhl }
			set_house = house:house_chad_uhl
		}

		if = {
			limit = {
				scope:transfer_type = flag:created
				is_alive = yes
			}
			every_vassal = {
				limit = {
					has_vassal_stance = courtly
				}
				if = {
					limit = {
						scope:title.tier = tier_duchy
					}
					add_opinion = {
						target = root
						modifier = courtly_title_creation_opinion
						opinion = 10
					}
				}
				else = {
					add_opinion = {
						target = root
						modifier = courtly_title_creation_opinion
						opinion = 30
					}
				}
			}
		}
		if = {
			limit = {
				scope:title = title:c_jerusalem
				# Samaritan HoF exists
				exists = title:d_samaritan.holder
				# Samaritan HoF is not independent
				title:d_samaritan.holder = { exists = liege }
				# Samaritan HoF is not Samaritan
				title:d_samaritan.holder = { NOT = { faith = faith:samaritan } }
				# root is at least a king, or their liege is, or their liege's liege is
				OR = {
					highest_held_title_tier >= tier_kingdom
					liege ?= { highest_held_title_tier >= tier_kingdom }
					liege.liege ?= { highest_held_title_tier >= tier_kingdom }
				}
			}
			create_title_and_vassal_change = {
				type = created
				save_scope_as = title_change
				add_claim_on_loss = no
			}
			if = {
				limit = {
					highest_held_title_tier >= tier_kingdom
				}
				title:d_samaritan.holder = {
					change_liege = {
						liege = root
						change = scope:title_change
					}
				}
			}
			else_if = {
				limit = {
					exists = liege
					liege = { highest_held_title_tier >= tier_kingdom }
				}
				title:d_samaritan.holder = {
					change_liege = {
						liege = root.liege
						change = scope:title_change
					}
				}
			}
			else_if = {
				limit = {
					exists = liege.liege
					liege.liege = { highest_held_title_tier >= tier_kingdom }
				}
				title:d_samaritan.holder = {
					change_liege = {
						liege = root.liege.liege
						change = scope:title_change
					}
				}
			}
			resolve_title_and_vassal_change = scope:title_change
		}

		# FP3 Struggle special cases
		## Convert detractors to supporters if they inherit either of the titles they're detracting against.
		if = {
			limit = {
				exists = struggle:persian_struggle
				NOT = { has_trait = fp3_struggle_supporter }
				OR = {
					scope:title = title:d_sunni
					scope:title = title:e_arabia
				}
			}
			if = {
				limit = { has_trait = fp3_struggle_detractor }
				remove_trait = fp3_struggle_detractor
			}
			add_trait = fp3_struggle_supporter
		}

		# Special Legitimacy gain for being elected
		if = {
			limit = {
				scope:title = {
					has_order_of_succession = election
				}
				has_legitimacy = yes
			}
			save_scope_value_as = {
				name = title_tier_minus_2
				value = {
					value = scope:title.tier
					subtract = 2
				}
			}
			send_interface_toast = {
				type = msg_legitimacy_gain
				title = legitimacy_gain_toast
				left_icon = root
				right_icon = scope:title
				add_legitimacy = {
					value = {
						value = major_legitimacy_gain
						multiply = scope:title_tier_minus_2
					}
				}
			}
		}

		# Did I conquer a place with holy order leases not of my faith?
		if = {
			limit = {
				scope:title = {
					any_in_de_jure_hierarchy = {
						tier = tier_barony
						is_under_holy_order_lease = yes
						county.holder = {
							any_liege_or_above = { this = root }
						}
						lessee = {
							NAND = { # Only for leases of people who are not of your faith or the holder's faith
								faith = root.faith
								faith = prev.county.holder.faith
							}
						}
					}
				}
			}
			scope:title = {
				every_in_de_jure_hierarchy = {
					limit = {
						tier = tier_barony
						is_under_holy_order_lease = yes
						county.holder = {
							any_liege_or_above = { this = root }
						}
						lessee = {
							NAND = { # Only for leases of people who are not of your faith or the holder's faith
								faith = root.faith
								faith = prev.county.holder.faith
							}
						}
					}
					revoke_lease = yes
				}
			}
		}

		# EP3 ADVENTURERS TELEPORT TO THEIR CAMP
		trigger_event = {
			id = title_event.9911
			days = 1
		}

		current_travel_plan ?= {
			if = {
				limit = { is_travel_with_domicile = yes }
				abort_travel_plan = yes
			}
		}

		# EP3 ADVENTURER BEING INHERITED BY LANDED
		if = {
			limit = {
				scope:title = {
					has_variable = adventurer_creation_reason
				}
				any_held_title = {
					NOT = { has_variable = adventurer_creation_reason }
				}
			}
			every_held_title = {
				limit = { has_variable = adventurer_creation_reason }
				save_scope_as = landless_adventurer_title
				root = { destroy_title = scope:landless_adventurer_title }
			}
		}

		# EP3 LAAMP SUPPORTER INVALIDATION
		if = {
			limit = {
				exists = var:adventurer_invasion_supporter
				NOT = { government_has_flag = government_is_landless_adventurer }
			}
			ep3_laamp_supporter_invalidated_effect = yes
		}

		### EP3 Admin Emperor Flavor ###
		if = {
			limit = {
				has_ep3_dlc_trigger = yes
				# You didn't just create the title
				scope:title = {
					tier >= tier_empire
					any_past_holder = {
						count >= 1
					}
					# Your predecessor wasn't from your same house - not much to celebrate if you got the title from dad!
					previous_holder ?= {
						NOT = { house = root.house }
					}
				}
				# Admin only
				government_has_flag = government_is_administrative
			}
			trigger_event = {
				id = ep3_emperor_yearly.2050
				days = 5
			}
		}

		# Admin vassals get the Governor trait when they first become a governor
		if = {
			limit = {
				is_governor = yes
				NOT = { has_trait = governor }
				scope:title = {
					tier >= tier_duchy
				}
			}
			add_trait = governor
		}

		# Additional Flavor Titles
		root = { additional_flavor_check_effect = yes }

		#Admin imperial succession notification event (it's a big deal)
		if = {
			limit = {
				has_ep3_dlc_trigger = yes
				government_has_flag = government_is_administrative
				is_independent_ruler = yes
				highest_held_title_tier >= tier_kingdom
				scope:title = {
					this = root.primary_title
				}
				#Checks so this event doesn't fire after character creation, although it's not really a problem if it does
				trigger_if = {
					limit = {
						game_start_date = 867.1.1
					}
					current_date >= 867.1.4
				}
				trigger_if = {
					limit = {
						game_start_date = 1066.9.15
					}
					current_date >= 1066.9.18
				}
				trigger_if = {
					limit = {
						game_start_date = 1178.10.1
					}
					current_date >= 1178.10.4
				}
			}
			save_scope_as = emperor
			#Should trigger special event during fourth crusade!
			if = {
				limit = {
					exists = global_var:byz_claimant_champion
					global_var:byz_claimant_champion = {
						any_owned_story = {
							story_type = frankokratia_story
							exists = var:byz_claimant
							var:byz_claimant = {
								this = root
							}
						}
					}
				}
				every_vassal_or_below = {
					limit = {
						is_playable_character = yes
					}
					trigger_event = ep3_frankokratia_events.0110
				}
			}
			else = {
				if = {
					limit = {
						exists = root.house
					}
					#normal triggering
					every_vassal_or_below = {
						limit = {
							is_playable_character = yes
							exists = scope:previous_holder
							government_has_flag = government_is_administrative
							OR = {
								highest_held_title_tier >= tier_duchy
								liege = root
							}
						}
						trigger_event = {
							id = ep3_governor_yearly.3060
							days = 1
						}
					}
				}
			}
		}
		# Reset raid remit
		if = {
			limit = {
				this = top_liege
				any_noble_family = { count > 0 }
			}
			every_noble_family = {
				holder = { remove_variable = raid_estate_permission }
			}
		}
		#Admin event about rewarding person who helped you get title
		if = {
			limit = {
				has_ep3_dlc_trigger = yes
				government_has_flag = government_is_administrative
				has_succession_appointment_investors = scope:title
				scope:title = {
					any_succession_appointment_investors = {
						count >= 1
						candidate = root
						value >= 20
						NOT = {
							house ?= root.house
						}
						is_alive = yes
						is_imprisoned = no
						NOR = {
							has_relation_rival = root
							is_at_war_with = root
						}
					}
				}
			}
			save_scope_as = new_landed_admin
			trigger_event = {
				id = ep3_interactions_events.0600
				days = { 5 10 }
			}
		}

		# Have we been given a fair shake as a laamp, but we're sucking?
		if = {
			limit = {
				is_landless_adventurer = yes
				is_ai = yes
				scope:previous_holder = { is_ai = yes }
				primary_title = {
					any_past_holder = { count >= 4 }
				}
				NOR = {
					# If the heir is sufficiently impressive, then we'll keep 'em around.
					prestige_level >= 2
					# Legitimists are always worthwhile.
					has_realm_law = camp_purpose_legitimists
					# Reserve successful mercenary outfits.
					AND = {
						max_military_strength >= 1500
						# Allow absolute decimations to destroy mercs from time to time.
						current_military_strength <= 150
					}
					# Or those currently fighting alongside/against players.
					AND = {
						is_at_war = yes
						OR = {
							any_war_ally = { is_ai = no }
							any_war_enemy = { is_ai = no }
						}
					}
					# Depending on camp purpose, we want various skills.
					AND = {
						has_realm_law = camp_purpose_wanderers
						OR = {
							highest_skill_value >= very_high_skill_rating
							prowess >= very_high_skill_rating
						}
					}
					AND = {
						has_realm_law = camp_purpose_mercenaries
						OR = {
							martial >= high_skill_rating
							prowess >= high_skill_rating
						}
					}
					AND = {
						has_realm_law = camp_purpose_scholars
						OR = {
							learning >= high_skill_rating
							diplomacy >= high_skill_rating
						}
					}
					AND = {
						has_realm_law = camp_purpose_explorers
						OR = {
							diplomacy >= high_skill_rating
							stewardship >= high_skill_rating
						}
					}
					AND = {
						has_realm_law = camp_purpose_brigands
						OR = {
							intrigue >= high_skill_rating
							prowess >= high_skill_rating
						}
					}
					# Finally, keep anyone who's important to the player.
					any_player = {
						OR = {
							root.dynasty ?= dynasty
							is_consort_of = root
							has_important_relationship_with_character_trigger = { CHARACTER = root }
							any_pinned_character = { this = root }
							any_pinned_character = { this = scope:previous_holder }
						}
					}
				}
			}
			destroy_laamp_effect = { ADVENTURER = root }
		}
		#Notification for house members of title holder
		if = {
			limit = {
				scope:title.tier > tier_barony
				primary_title.tier <= scope:title.tier
				government_has_flag = government_is_administrative
				NOT = { has_character_flag = admin_title_gain_notification_sent }
				house ?= {
					any_house_member = {
						is_ai = no
						top_liege = root.top_liege
						government_has_flag = government_is_administrative
						NOT = { this = root }
					}
				}
			}
			add_character_flag = {
				flag = admin_title_gain_notification_sent
				days = 10
			}
			save_scope_as = title_gainer
			house = {
				every_house_member = {
					limit = {
						is_ai = no
						top_liege = root.top_liege
						government_has_flag = government_is_administrative
						NOT = { this = scope:title_gainer }
					}
					send_interface_message = {
						type = msg_admin_title_gained
						title = msg_admin_title_gained_house.tt
						desc = msg_admin_title_gained.desc
						left_icon = scope:title_gainer
						right_icon = scope:title
					}
				}
			}
		}
		#Notification for admin investors in new title holder
		if = {
			limit = {
				NOT = { has_character_flag = admin_title_gain_notification_sent }
				scope:title = {
					tier > tier_barony
					any_succession_appointment_investors = {
						candidate = root
						is_ai = no
						trigger_if = {
							limit = { exists = root.house }
							NOT = { house ?= root.house }
						}
					}
				}
			}
			add_character_flag = {
				flag = admin_title_gain_notification_sent
				days = 10
			}
			save_scope_as = title_gainer
			scope:title = {
				every_succession_appointment_investors = {
					candidate = root
					value > 0
					limit = {
						is_ai = no
						trigger_if = {
							limit = { exists = root.house }
							NOT = { house ?= root.house }
						}
					}
					send_interface_message = {
						type = msg_admin_title_gained
						title = msg_admin_title_gained_investor.tt
						desc = msg_admin_title_gained.desc
						left_icon = scope:title_gainer
						right_icon = scope:title
					}
				}
				every_succession_appointment_investors = {
					candidate = root
					value < 0
					limit = {
						is_ai = no
						trigger_if = {
							limit = { exists = root.house }
							NOT = { house ?= root.house }
						}
					}
					send_interface_message = {
						type = msg_admin_title_gained_foe
						title = msg_admin_title_gained_foe.tt
						desc = msg_admin_title_gained.desc
						left_icon = scope:title_gainer
						right_icon = scope:title
					}
				}
			}
		}
		#Byzantium is reborn!
		if = {
			limit = {
				scope:title = {
					this = title:e_byzantium
				}
				exists = global_var:byz_collapse_counter
			}
			save_scope_as = byz_emperor
			title:e_byzantium = {
				every_in_de_jure_hierarchy = {
					limit = {
						tier <= tier_kingdom
						tier >= tier_county	
						is_title_created = yes
						exists = holder
					}
					if = {
						limit = {
							exists = holder
							holder = {
								is_alive = yes
								NOR = {
									is_in_list = byz_return_notify
									any_held_title = {
										this = title:e_byzantium
									}
								}
							}
						}
						holder = {
							add_to_list = byz_return_notify
						}
					}
				}
			}
			title:e_latin_empire = {
				every_in_de_jure_hierarchy = {
					limit = {
						tier <= tier_kingdom
						tier >= tier_county	
						is_title_created = yes
						exists = holder
					}
					if = {
						limit = {
							holder = {
								is_alive = yes
								NOR = {
									is_in_list = byz_return_notify
									any_held_title = {
										this = title:e_byzantium
									}
								}
							}
						}
						holder = {
							add_to_list = byz_return_notify
						}
					}
				}
			}
			every_in_list = {
				list = byz_return_notify
				trigger_event = ep3_frankokratia_events.0130
			}
			remove_global_variable = byz_collapse_counter
		}
		
		# Lil Johnny Lackland changes his nickname.
		if = {
			limit = {
				has_nickname = nick_lackland_young
				highest_held_title_tier >= tier_duchy
			}
			give_nickname = nick_lackland_ironic
		}

		# BP3 - Inspector perks cleanup effect
		landless_inspector_cleanup_modifier = yes
		
		### MEMORIES - SHOULD STAY AT BOTTOM ###
		# Ascended to the throne
		if = {
			limit = {
				OR = {
					is_ruler = no
					highest_held_title_tier <= scope:title.tier
					government_has_flag = government_is_landless_adventurer
					government_has_flag = government_is_administrative
				}
			}
			if = {
				limit = { exists = scope:title.var:adventurer_flavor_char }
				create_character_memory = {
					type = became_landless_adventurer_memory
					participants = {
						flavor_character = scope:title.var:adventurer_flavor_char
					}
				}
				#Only children should get childhood memories
				if = {
					limit = { is_adult = no }
					scope:new_memory = { set_variable = childhood_memory }
				}
				scope:new_memory = {
					save_scope_as = became_landless_adventurer_memory
					set_variable = {
						name = landless_title
						value = scope:title
					}
					set_variable = {
						name = reason
						value = scope:transfer_type
					}
					set_variable = {
						name = adventurer_creation_reason
						value = scope:title.var:adventurer_creation_reason
					}
					if = {
						limit = { exists = scope:lost_primary_title }
						set_variable = {
							name = old_primary_title
							value = scope:lost_primary_title
						}
					}
					if = { # Error suppression
						limit = { exists = var:landless_title }
					}
				}
			}
			else = {
				# Overwrite if there is a more specific Reason
				if = {
					limit = { exists = root.var:ascended_throne_reason }
					root.var:ascended_throne_reason = { save_scope_as = real_transfer_type }
					root = { remove_variable = ascended_throne_reason }
				}
				else = {
					scope:transfer_type = { save_scope_as = real_transfer_type }
				}
				root = {
					add_to_variable_list = {
						name = new_titles
						target = scope:title
					}
					trigger_event = {
						id = title_event.9900
						delayed = yes
					}
				}
			}
		}
		#Mongol empire and GoK should lose other empires
		if = {
			limit = {
				primary_title ?= {
					OR = {
						this = title:e_mongol_empire
						AND = {
							exists = global_var:greatest_of_khans_title
							this = global_var:greatest_of_khans_title
						}
					}
				}
				scope:title = {
					tier = tier_empire
					NOR = {
						this = title:e_mongol_empire
						AND = {
							exists = global_var:greatest_of_khans_title
							this = global_var:greatest_of_khans_title
						}
					}
				}
				is_ai = yes
			}
			destroy_title = scope:title
		}
	}
	events = {
		roman_restoration.0005		#New Roman Emperor gets Augustus trait. (old holder, if still alive, loses it)
		roman_restoration.0199		#Restoring the Pentarchy.
		religious_decision.0312		# Base game: new holder of a county with a runestone
		fp1_other_decisions.0113	# FP1: new holder of a county with a runestone
		delay = { days = 1 }
		realm_maintenance.2001		#Big notification about inheriting emperor tier title
		british_isles.1032			# Danelaw-England partition calc.
		fp1_major_decisions.1011	# Harald Tanglehair becomes Harald Fairhair.
		fp1_major_decisions.1012	# If Norway has just been created for the first time, flag that.
		title_event.0001			# Rename West Francia to France
		title_event.0002			# Rename East Francia to Germany
		title_event.0011			# Asturias becomes Leon upon emergence of Castille
		# If we weren't already in a diarchy but should be, put us in one.
		diarchy.0011
		ep3_emperor_yearly.2020		# EP3: The Patriarch refuses to crown you as new emperor because you have a criminal trait
	}
}

# A title is inherited by a character
# root = the new holder
# scope:title = the title that changes hands
# scope:previous_holder = previous holder. Should be dead
on_title_gain_inheritance = {
	events = {
		diarchy.0011
		delay = { days = 1 }
		# Try to end inherited entrenched regencies automatically — we need to launder this by a day to make sure the AI realises they've inherited a diarchy.
		diarchy.0113
	}
	effect = {
		if = {
			limit = {
				scope:title = {
					OR = {
						this = title:e_mongol_empire
						AND = {
							exists = global_var:greatest_of_khans_title
							this = global_var:greatest_of_khans_title
						}
					}
				}
				has_character_flag = gain_mongol_succession_dread
			}
			add_dread = 50
		}

		if = {
			limit = { scope:title = title:e_roman_empire }
			set_variable = uses_custom_caesar_flavourization
		}

		# Additional Flavor Title
		additional_flavor_check_effect = yes

		# BP3 - Inspector perks cleanup effect
		landless_inspector_cleanup_modifier = yes
	}
}

# A title is usurped by a character
# root = the new holder
# scope:title = the title that changes hands
# scope:previous_holder = previous holder. Shouldn't be dead
on_title_gain_usurpation = {
	events = {
	}
	effect = {
		# Struggle Catalysts
		if = {
			limit = { # FP2
				# We are only interested in the title within the Struggle Region
				title:e_spain = {
					any_in_de_jure_hierarchy = {
						this = 	scope:title
					}
				}
				# Only for usurpation
				scope:transfer_type = flag:usurped

				root = {
					any_character_struggle = {
						involvement = involved
						activate_struggle_catalyst_secondary_character_involvement_involved_trigger = {
							CATALYST = catalyst_usurp_title_fp2
							CHAR = root
						}
					}
				}
			}
			root = {
				every_character_struggle = {
					involvement = involved
					limit = {
						activate_struggle_catalyst_secondary_character_involvement_involved_trigger = {
							CATALYST = catalyst_usurp_title_fp2
							CHAR = root
						}
					}
					activate_struggle_catalyst = {
						catalyst = catalyst_usurp_title_fp2
						character = root
					}
				}
			}
		}

		if = {
			limit = { # FP3
				title:e_persia = { any_in_de_jure_hierarchy = { this = scope:title } }
				scope:transfer_type = flag:usurped

				root = {
					any_character_struggle = {
						involvement = involved
						activate_struggle_catalyst_secondary_character_involvement_involved_trigger = {
							CATALYST = catalyst_usurp_title_fp3
							CHAR = root
						}
					}
				}
			}
			root = {
				every_character_struggle = {
					involvement = involved
					limit = {
						activate_struggle_catalyst_secondary_character_involvement_involved_trigger = {
							CATALYST = catalyst_usurp_title_fp3
							CHAR = root
						}
					}
					activate_struggle_catalyst = {
						catalyst = catalyst_usurp_title_fp3
						character = root
					}
					log_debug_variable_for_persian_struggle_effect = { VAR = unrest_catalyst_usurp_title_fp3 }
				}
			}
		}

		# Additional Flavor Titles
		additional_flavor_check_effect = yes

		# BP3 - Inspector perks cleanup effect
		landless_inspector_cleanup_modifier = yes
	}
}

# A title is lost by a character
# root = the old holder
# scope:title = the title that changes hands
# scope:new_holder = new holder.
on_title_lost = {
	events = {
		british_isles.1033	# Danelaw-England partition calc.
	}

	effect = {
		#Make sure nobody ever has only the Kingdom of Fashion
		if = {
			limit = {
				scope:title = { tier = tier_kingdom }
				has_title = title:k_fashion
				NOT = {
					any_held_title = { # Only trigger if you don't have any kingdom titles other than Fashion and the kingdom you just lost. Double negative is confusing but it's the only way I could think to script it
						tier = tier_kingdom
						NOT = { this = title:k_fashion }
						NOT = { this = scope:title }
					}
				}
			}
			destroy_title = title:k_fashion
		}
		#Earmark landless Scandinavians for adventuring.
		if = {
			limit = {
				#We only want to grab tribal cultures.
				culture = {
					NOT = { has_cultural_era_or_later = culture_era_early_medieval }
				}
				#Must have lost their last piece of land.
				is_playable_character = no
				#If they've ventured far outside Europe, they're unlikely to come back, so we don't #want them.
				scope:title = {
					tier = tier_county
					title_province = {
						OR = {
							geographical_region = world_europe
							geographical_region = world_asia_minor
						}
					}
				}
			}
			#Norse, Norwegians, & Danes go into the western adventurer list.
			if = {
				limit = {
					OR = {
						has_culture = culture:norse
						has_culture = culture:norwegian
						has_culture = culture:danish
					}
				}
				add_to_global_variable_list = {
					name = western_scandinavian_adventurer_list
					target = this
				}
			}
			#Norse & Swedes go into the eastern adventurer list.
			if = {
				limit = {
					OR = {
						has_culture = culture:norse
						has_culture = culture:swedish
					}
				}
				add_to_global_variable_list = {
					name = eastern_scandinavian_adventurer_list
					target = this
				}
			}
		}

		#To remove concubines if a character becomes unlanded
		if = {
			limit = {
				is_playable_character = no
				any_concubine = { count >= 1 }
			}
			every_concubine = { root = { remove_concubine = prev } }
		}

		# Transfer co-monarchies.
		if = {
			limit = {
				OR = {
					scope:transfer_type = flag:inheritance
					scope:transfer_type = flag:abdication
					scope:transfer_type = flag:usurped
					scope:transfer_type = flag:election
					scope:transfer_type = flag:faction_demand
					scope:transfer_type = flag:stepped_down
				}
			}
			save_scope_as = old_holder
			trigger_event = {
				id = diarchy.0025
				days = 1
			}
		}

		#Apply loss of stress to the Rivals
		if = {
			limit = {
				scope:title.tier >= tier_county
				scope:title = { is_landless_type_title = no }
				OR = {
					scope:transfer_type = flag:conquest
					scope:transfer_type = flag:conquest_holy_war
					scope:transfer_type = flag:conquest_claim
					scope:transfer_type = flag:conquest_populist
					scope:transfer_type = flag:abdication
					scope:transfer_type = flag:usurped
					scope:transfer_type = flag:revoked
					scope:transfer_type = flag:faction_demand
				}
			}
			root = {
				save_scope_as = actor
			}
			every_relation ={
				type = rival

				send_interface_message = {
					type = event_generic_neutral
					title = msg_rival_dethroned
					left_icon = scope:actor
					right_icon = scope:title

					custom_tooltip = msg_rival_dethroned_desc

					stress_impact = {
						base = medium_stress_loss
						vengeful = medium_stress_loss
					}
				}
			}
		}

		# Struggle catalyst
		if = {
			limit = {
				any_character_struggle = {
					involvement = involved
					phase_has_catalyst = catalyst_revoke_title
				}
				OR = {
					scope:transfer_type = flag:revoked
					scope:transfer_type = flag:lease_revoked
				}
			}
			every_character_struggle = {
				activate_struggle_catalyst = {
					catalyst = catalyst_revoke_title
					character = scope:new_holder
				}
			}
		}

		# Memories
		# Lost a significant title
		if = {
			limit = {
				scope:title.tier >= highest_held_title_tier
				exists = scope:new_holder
			}
			if = {
				limit = { exists = root.var:lost_title_reason }
				root.var:lost_title_reason = { save_scope_as = real_transfer_type }
				root = { remove_variable = lost_title_reason }
			}
			else = {
				scope:transfer_type = { save_scope_as = real_transfer_type }
			}
			root = {
				add_to_variable_list = {
					name = lost_titles
					target = scope:title
				}
				trigger_event = {
					id = title_event.9901
					delayed = yes
				}
			}
		}

		# LEGITIMACY LOSS FROM USURPATION
		if = {
			limit = {
				scope:transfer_type ?= flag:usurped
				has_legitimacy = yes
				NOT = { exists = scope:suppress_legitimacy_loss }
			}
			# Minus 2, since we want Duchy to be 1, and it's normally 3
			save_scope_value_as = {
				name = title_tier_minus_2
				value = {
					value = scope:title.tier
					subtract = 2
				}
			}
			send_interface_toast = {
				type = msg_legitimacy_loss
				title = legitimacy_loss_toast
				left_icon = root
				right_icon = scope:title
				custom_tooltip = legitimacy_loss_usurpation_tt
				add_legitimacy = {
					value = {
						value = miniscule_legitimacy_loss
						multiply = scope:title_tier_minus_2
					}
				}
			}
		}

		# EP3 LAAMP SUPPORTER INVALIDATION
		ep3_laamp_supporter_invalidated_effect = yes

		# EP3 - Handle admin estates when they end up outside the realm
		if = {
			limit = {
				scope:new_holder = {
					any_sub_realm_barony = {
						title_province = {
							any_province_domicile = {
								is_domicile_type = estate
								owner ?= {
									NOT  = { top_liege = scope:new_holder.top_liege }
								}
							}
						}
					}
				}
			}
			scope:new_holder = {
				every_sub_realm_barony = {
					limit = {
						title_province = {
							any_province_domicile = {
								is_domicile_type = estate
								owner ?= {
									NOT  = { top_liege = scope:new_holder.top_liege }
								}
							}
						}
					}
					title_province = {
						every_province_domicile = {
							limit = {
								is_domicile_type = estate
								owner ?= {
									NOT  = { top_liege = scope:new_holder.top_liege }
								}
							}
							
							# First, let's do some damage to the estate - We randomize the level of damage taken
							random_list = {
								40 = { # Damage 1
									trigger = {
										num_domicile_buildings <= 6
									}
									set_variable = {
										name = domicile_damage_count
										value = 1
									}
								}
								35 = { # Damage 2
									trigger = {
										num_domicile_buildings > 2
									}
									set_variable = {
										name = domicile_damage_count
										value = 2
									}
								}
								30 = { # Damage 3
									trigger = {
										num_domicile_buildings > 4
									}
									set_variable = {
										name = domicile_damage_count
										value = 3
									}
								}
								25 = { # Damage 4
									trigger = {
										num_domicile_buildings > 6
									}
									set_variable = {
										name = domicile_damage_count
										value = 4
									}
								}
								20 = { # Damage 5
									trigger = {
										num_domicile_buildings > 8
									}
									set_variable = {
										name = domicile_damage_count
										value = 5
									}
								}
								15 = { # Damage 6
									trigger = {
										num_domicile_buildings > 10
									}
									set_variable = {
										name = domicile_damage_count
										value = 6
									}
								}
							}
							while = {
								count = var:domicile_damage_count
								destroy_random_estate_building_variable_effect = yes
								destroy_random_estate_building_effect = yes
							}
							
							# Clear the variable
							if = {
								limit = { has_variable = domicile_damage_count }
								remove_variable = domicile_damage_count
							}
							
							# Then we'll move the estate to keep it within the realm's borders
							if = { # If you have a capital (i.e. you are a governor) let's move the estate there
								limit = {
									owner = {
										is_landed = yes
										exists = capital_province
									}
								}
								move_domicile = owner.capital_province
							}
							else_if = { # If not, let's move it to a landed house member in the realm, if you have one
								limit = {
									owner = {
										top_liege ?= { save_temporary_scope_as = owner_top_liege }
										house ?= {
											any_house_member = {
												is_governor = yes
												top_liege = scope:owner_top_liege
											}
										}
									}
								}
								owner = {
									house = {
										random_house_member = {
											limit = {
												is_governor = yes
												exists = capital_province
												top_liege = scope:owner_top_liege
											}
											capital_province = { save_temporary_scope_as = house_member_location }
										}
									}
								}
								move_domicile = scope:house_member_location
							}
							else_if = { # Otherwise move it to the realm capital
								limit = {
									exists = owner.top_liege.capital_province
								}
								move_domicile = owner.top_liege.capital_province
							}
							
							# Save the new estate location for msg
							domicile_location.barony = {
								save_scope_as = new_estate_location
							}
							
							# Finally, let's make sure the owner moves to the new estate location
							owner = {
								if = {
									limit = {
										is_alive = yes
										is_imprisoned = no
										is_travelling = no
										NOT = {
											exists = involved_activity
										}
										is_commanding_army = no
									}
									set_location_to_default = yes
								}
								
								# And notify the owner that all of this just happened
								if = {
									limit = { is_ai = no }
									send_interface_message = {
										type = msg_domicile_damaged
										title = msg_estate_damaged.title
										desc = msg_estate_damaged.desc
										right_icon = scope:new_estate_location
									}
								}
							}
						}
					}
				}
			}
		}

		# Additional Flavor Title
		additional_flavor_check_effect = yes
		
		if = {
			limit = { scope:title = title:e_roman_empire }
			remove_variable = uses_custom_caesar_flavourization
		}
		#Notification for house members of loser
		if = {
			limit = {
				scope:title.tier > tier_barony
				trigger_if = { # Prevent msg spam when rulers give away or lose lower tier titles
					limit = {
						is_landed = yes
					}
					primary_title.tier <= scope:title.tier
				}
				is_alive = yes
				NOT = { has_character_flag = admin_title_loss_notification_sent }
				government_has_flag = government_is_administrative
				house ?= {
					any_house_member = {
						is_ai = no
						trigger_if = {
							limit = { exists = root.top_liege }
							top_liege = root.top_liege
						}
						government_has_flag = government_is_administrative
						NOT = { this = root }
					}
				}
			}
			add_character_flag = {
				flag = admin_title_loss_notification_sent
				days = 10
			}
			save_scope_as = title_loser
			house = {
				every_house_member = {
					limit = {
						is_ai = no
						trigger_if = {
							limit = { exists = root.top_liege }
							top_liege = root.top_liege
						}
						government_has_flag = government_is_administrative
						NOT = { this = scope:title_loser }
					}
					send_interface_message = {
						type = msg_admin_title_lost
						title = msg_admin_title_lost_house.tt
						desc = msg_admin_title_lost.desc
						left_icon = scope:title_loser
						right_icon = scope:title
					}
				}
			}
		}
		#Notification for admin investors in loser
		if = {
			limit = {
				is_alive = yes
				NOT = { has_character_flag = admin_title_loss_notification_sent }
				scope:title = {
					tier > tier_barony
					any_succession_appointment_investors = {
						candidate = root
						is_ai = no
						trigger_if = {
							limit = { exists = root.house }
							NOT = { house ?= root.house }
						}
					}
				}
			}
			add_character_flag = {
				flag = admin_title_loss_notification_sent
				days = 10
			}
			save_scope_as = title_loser
			scope:title = {
				every_succession_appointment_investors = {
					candidate = root
					value > 0
					limit = {
						is_ai = no
						trigger_if = {
							limit = { exists = root.house }
							NOT = { house ?= root.house }
						}
					}
					send_interface_message = {
						type = msg_admin_title_lost
						title = msg_admin_title_lost_investor.tt
						desc = msg_admin_title_lost.desc
						left_icon = scope:title_loser
						right_icon = scope:title
					}
				}
				every_succession_appointment_investors = {
					candidate = root
					value < 0
					limit = {
						is_ai = no
						trigger_if = {
							limit = { exists = root.house }
							NOT = { house ?= root.house }
						}
					}
					send_interface_message = {
						type = msg_admin_title_lost_foe
						title = msg_admin_title_lost_foe.tt
						desc = msg_admin_title_lost.desc
						left_icon = scope:title_loser
						right_icon = scope:title
					}
				}
			}
		}

		# Lil Johnny Lackland changes his nickname.
		if = {
			limit = {
				has_nickname = nick_lackland_ironic
				scope:title.tier >= tier_duchy
			}
			give_nickname = nick_lackland_old
		}

		# BP3 - Inspector perks cleanup effect
		landless_inspector_cleanup_modifier = yes

		#End Greatest of Khans story if title was lost
		if = {
			limit = {
				any_owned_story = {
					story_type = story_greatest_of_khans
				}
				global_var:greatest_of_khans_title ?= {
					this = scope:title
				}
				OR = {
					NOT = {
						exists = scope:new_holder
					}
					scope:new_holder = {
						NOR = {
							AND = {
								exists = dynasty
								dynasty ?= root.dynasty
							}
							is_grandchild_of = root
							is_child_of = root
						}
					}
				}
			}
			if = {
				limit = {
					is_alive = yes
				}
				trigger_event = {
					id = mpo_greatest_of_khans.0040
					days = 1
				}
			}
			else_if = {
				limit = {
					exists = root.player_heir
					exists = root.dynasty
					player_heir = {
						dynasty ?= story_owner.dynasty
					}
				}
				player_heir ?= {
					trigger_event = {
						id = mpo_greatest_of_khans.0040
						days = 1
					}
				}
			}
			else = {
				every_owned_story = {
					limit = { story_type = story_greatest_of_khans }
					end_story = yes
				}
				remove_character_modifier = the_great_khan_modifier
			}
		}
	}
}

# A claim is gained by a character
# root = the claimant
# scope:title = the title that is claimed
# scope:transfer_type = flag:inheritance or none
on_explicit_claim_gain = {
	effect = {
		if = {
			limit = {
				title:k_england.holder = root
			}
			title:k_england = {
				update_dynamic_coa = yes
			}
		}
		# Struggle Catalyst
		if = { # FP2
			limit = {
				NOT = { scope:transfer_type = flag:inheritance }

				root = {
					any_character_struggle = {
						is_struggle_type = iberian_struggle
						involvement = involved
					}
				}
				title:e_spain = { any_in_de_jure_hierarchy = { this = scope:title } }
			}
			root = {
				every_character_struggle = {
					involvement = involved
					limit = {
						activate_struggle_catalyst_secondary_character_involvement_involved_trigger = {
							CATALYST = catalyst_gain_claim_on_title_fp2
							CHAR = root
						}
					}
					activate_struggle_catalyst = {
						catalyst = catalyst_gain_claim_on_title_fp2
						character = root
					}
				}
			}
		}
		else_if = { # FP3
			limit = {
				NOT = { scope:transfer_type = flag:inheritance }

				root = {
					any_character_struggle = {
						is_struggle_type = persian_struggle
						involvement = involved
					}
				}
				title:e_persia = { any_in_de_jure_hierarchy = { this = scope:title } }
			}
			root = {
				every_character_struggle = {
					involvement = involved
					limit = {
						activate_struggle_catalyst_secondary_character_involvement_involved_trigger = {
							CATALYST = catalyst_gain_claim_on_title_fp3
							CHAR = root
						}
					}
					activate_struggle_catalyst = {
						catalyst = catalyst_gain_claim_on_title_fp3
						character = root
					}
					log_debug_variable_for_persian_struggle_effect = { VAR = unrest_catalyst_gain_claim_on_title_fp3 }
				}
			}
		}
	}
}

# A claim is lost by a character
# root = the claimant
# scope:title = the title that was claimed
on_explicit_claim_lost = {
	effect = {
		if = {
			limit = {
				title:k_england.holder = root
			}
			title:k_england = {
				update_dynamic_coa = yes
			}
		}
	}
}

# A title change makes the character rank up in the landed tiers (eg Duke -> King)
# root = character ranking up
# scope:title = old primary title
on_rank_up = { # Will not fire during history execution or for dying characters
	events = {
	}
	effect = {
		if = {
			limit = { is_landed = yes }
			add_achievement_flag_effect = { FLAG = achievement_moving_up_in_the_world_flag }
		}
		if = {
			limit = {
				is_ai = no
				is_landed = yes
				highest_held_title_tier = tier_empire
			}
			add_achievement_global_variable_effect = {
				VARIABLE = rags_to_riches_to_rags_to_riches_first_empire
				VALUE = yes
			}
		}
		if = {
			limit = {
				is_ai = no
				is_landed = yes
				highest_held_title_tier = tier_empire
				exists = global_var:rags_to_riches_to_rags_to_riches_adventurer
			}
			add_achievement_global_variable_effect = {
				VARIABLE = finished_rags_to_riches_to_rags_to_riches_achievement
				VALUE = yes
			}
		}
		update_embassies_effect = yes
		every_ally = {
			update_embassies_effect = yes
		}
		if = {
			limit = { is_independent_ruler = yes }
			remove_variable = use_co_ruler_title
		}
		# Make a note of ranking up for stele purposes.
		if = {
			limit = {
				# DLC check.
				has_fp1_dlc_trigger = yes
				# Is the culture eligible?
				fp1_can_raise_stele_trigger = yes
				# Aaaaand, for balance reasons, were they landed already?
				exists = scope:title
			}
			set_variable = {
				name = recent_rank_increase
				value = root.primary_title
				years = 5
			}
		}
		# Remove any rank-inappropriate modifiers (e.g., baron buffs).
		remove_character_modifier = mandate_baronial_troops_trained_modifier
		remove_character_modifier = mandate_baronial_troops_half_trained_modifier

		# Additional Flavor Title
		additional_flavor_check_effect = yes
		#Admin kings becoming emperors need their MAA transferred to new primary title
		if = {
			limit = {
				is_independent_ruler = yes
				government_has_flag = government_is_administrative
				scope:title = {
					any_title_maa_regiment = {
						count >= 1
					}
				}
			}
			scope:title = {
				transfer_title_maa_ownership = root.primary_title
			}
		}
	}
}

# A title change makes the character rank down in the landed tiers (eg King -> Duke)
# root = character ranking down
# scope:title = old primary title
on_rank_down = { # Will not fire during history execution or for dying characters
	events = {
	}
	effect = {
		if = {
			limit = {
				NOR = {
					has_trait = humble
					has_trait = content
					has_trait = generous
				}
			}
			add_character_flag = {
				flag = make_suicide_available
				years = 5
			}
			set_variable = {
				name = rank_demoted
				value = yes
			}
		}
		update_embassies_effect = yes
		every_ally = {
			update_embassies_effect = yes
		}
		# Inform hostage havers
		if = {
			limit = {
				any_home_court_hostage = { count >= 1 }
			}
			save_scope_as = home_court
			every_home_court_hostage = {
				save_scope_as = hostage
				warden = {
					save_scope_as = warden
					trigger_event = { id = bp2_hostage_system.0410 days = 5 }
				}
			}
		}

		# Additional Flavor Title
		additional_flavor_check_effect = yes
	}
}

# A character gains a vassal
# root = character gaining vassal
# scope:vassal = vassal being gained
# scope:old_liege = the previous liege of the vassal. Might be the null character (vassal used to be a non-ruler or independent), so make sure to use "exists" checks where relevant
on_vassal_gained = {
	events = {
		realm_maintenance.1000 # Notify vassals of new liege
	}
	effect = {
		#Confederation members must be independent
		if = {
			limit = {
				scope:vassal = {
					is_confederation_member = yes
				}
			}
			scope:vassal.confederation = {
				remove_confederation_member = scope:vassal
			}
		}
		# EP3 LANDLESS CANNOT HAVE VASSALS
		if = {
			limit = { has_any_landed_title_trigger = no }
			save_scope_as = new_liege
			if = {
				limit = { is_independent_ruler = no }
				create_title_and_vassal_change = {
					type = swear_fealty
					save_scope_as = change
					add_claim_on_loss = no
				}
				change_liege = {
					liege = scope:new_liege.liege
					change = scope:change
				}
				resolve_title_and_vassal_change = scope:change
			}
			else = {
				create_title_and_vassal_change = {
					type = independency
					save_scope_as = change
					add_claim_on_loss = no
				}
				scope:vassal = {
					becomes_independent = { change = scope:change }
				}
				resolve_title_and_vassal_change = scope:change
			}
		}

		# Additional Flavor Title
		scope:vassal = {
			additional_flavor_check_effect = yes
		}
	}
}

# A vassal changes their liege
# root = vassal changing their status
# scope:old_liege = the previous liege of the vassal
# It is also fired for rulers gaining independence, those can be identified by checking current liege
on_vassal_change = {
	effect = {
		if = {
			limit = {
				OR = {
					liege ?= {
						NOT = { government_has_flag = government_is_administrative }
					}
					AND = {
						is_independent_ruler = yes
						primary_title.tier <= tier_duchy
					}
				}
				any_held_title = { is_noble_family_title = yes }
			}
			every_held_title = {
				limit = { is_noble_family_title = yes }
				save_scope_as = title_to_destroy
				root = { destroy_title = scope:title_to_destroy }
			}
		}
		### GOVERNORS CHANGE GOVERNMENT IF NEW LIEGE IS NOT ADMINISTRATIVE
		if = {
			limit = {
				exists = top_liege
				government_has_flag = government_is_administrative
				NOT = {
					top_liege = { government_has_flag = government_is_administrative }
				}
			}
			top_liege = { save_scope_as = new_liege }
			send_interface_message = {
				type = msg_government_changed
				title = new_liege_government_changed_title
				desc = new_liege_government_changed_desc
				right_icon = scope:new_liege
				admin_change_government_effect = yes
			}
			hidden_effect = {
				# VASSALS AND BELOW
				every_vassal_or_below = {
					limit = { government_has_flag = government_is_administrative }
					send_interface_message = {
						type = msg_government_changed
						title = new_liege_government_changed_title
						desc = new_liege_government_changed_desc
						right_icon = scope:new_liege
						admin_change_government_effect = yes
					}
				}
			}
		}
		### If a admin duke-tier character becomes the top-liege's direct vassal, ensure that they have a noble family title
		if = {
			limit = {
				government_has_flag = government_is_administrative
				is_house_head = yes
				highest_held_title_tier >= tier_duchy
				liege = {
					is_independent_ruler = yes
					government_has_flag = government_is_administrative
				}
				NOR = {
					any_held_title = { is_noble_family_title = yes }
					house = {
						any_house_member = {
							any_held_title = { is_noble_family_title = yes }
						}
					}
				}
			}
			create_noble_family_effect = yes
			domicile ?= { set_up_domicile_estate_effect = yes }
		}
		### If an admin ruler becomes independent, who are not of a high enough rank, changes government
		if = {
			limit = {
				liege = root # I.e. root is independent
				government_has_flag = government_is_administrative
				highest_held_title_tier < tier_kingdom
			}
			admin_change_government_effect = yes
		}

		# Additional Flavor Title
		additional_flavor_check_effect = yes
	}
}

# A baron is found or created for a title, E.G., due to the player using the "Give to Low Noble" action
# No transfer type here; it's always a grant
# root = the baron
# scope:liege = the person who wanted them created
# scope:title = the barony
on_baron_found_or_created_for_title = {
	effect = {
		add_opinion = {
			target = scope:liege
			modifier = received_title_barony
		}
	}
}

# Called when realm capital changes. It can be manual move, loss in conquest, move after inheritance,
# move when granted a better title, becoming landed for the first time
# root: New realm capital barony
# scope:old_capital - previous capital barony. Can be empty, can be owned by someone else
on_realm_capital_change = {
	effect = {
		holder ?= {
			# Do we need to refresh their vizier's modifiers?
			if = {
				limit = { has_diarchy_parameter = diarchy_is_vizierate }
				diarch = {
					# What we're doing here is regenerating loc on the diarchs that might refer to a specific place which they no longer have access to.
					## This is gonna get real gross, folks, so my apologies.
					if = {
						limit = { has_character_modifier = vizier_extravagance_t1_treasure_modifier }
						remove_character_modifier = vizier_extravagance_t1_treasure_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t1_treasure_modifier
							desc = vizier_extravagance_t1_treasure_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t1_activities_modifier }
						remove_character_modifier = vizier_extravagance_t1_activities_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t1_activities_modifier
							desc = vizier_extravagance_t1_activities_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t1_property_modifier }
						remove_character_modifier = vizier_extravagance_t1_property_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t1_property_modifier
							desc = vizier_extravagance_t1_property_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t1_charity_modifier }
						remove_character_modifier = vizier_extravagance_t1_charity_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t1_charity_modifier
							desc = vizier_extravagance_t1_charity_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t2_treasure_modifier }
						remove_character_modifier = vizier_extravagance_t2_treasure_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t2_treasure_modifier
							desc = vizier_extravagance_t2_treasure_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t2_activities_modifier }
						remove_character_modifier = vizier_extravagance_t2_activities_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t2_activities_modifier
							desc = vizier_extravagance_t2_activities_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t2_property_modifier }
						remove_character_modifier = vizier_extravagance_t2_property_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t2_property_modifier
							desc = vizier_extravagance_t2_property_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t2_charity_modifier }
						remove_character_modifier = vizier_extravagance_t2_charity_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t2_charity_modifier
							desc = vizier_extravagance_t2_charity_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t3_treasure_modifier }
						remove_character_modifier = vizier_extravagance_t3_treasure_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t3_treasure_modifier
							desc = vizier_extravagance_t3_treasure_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t3_activities_modifier }
						remove_character_modifier = vizier_extravagance_t3_activities_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t3_activities_modifier
							desc = vizier_extravagance_t3_activities_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t3_property_modifier }
						remove_character_modifier = vizier_extravagance_t3_property_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t3_property_modifier
							desc = vizier_extravagance_t3_property_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t3_charity_modifier }
						remove_character_modifier = vizier_extravagance_t3_charity_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t3_charity_modifier
							desc = vizier_extravagance_t3_charity_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t4_treasure_modifier }
						remove_character_modifier = vizier_extravagance_t4_treasure_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t4_treasure_modifier
							desc = vizier_extravagance_t4_treasure_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t4_activities_modifier }
						remove_character_modifier = vizier_extravagance_t4_activities_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t4_activities_modifier
							desc = vizier_extravagance_t4_activities_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t4_property_modifier }
						remove_character_modifier = vizier_extravagance_t4_property_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t4_property_modifier
							desc = vizier_extravagance_t4_property_modifier_custom_desc.on_action
						}
					}
					if = {
						limit = { has_character_modifier = vizier_extravagance_t4_charity_modifier }
						remove_character_modifier = vizier_extravagance_t4_charity_modifier
						add_character_modifier = {
							modifier = vizier_extravagance_t4_charity_modifier
							desc = vizier_extravagance_t4_charity_modifier_custom_desc.on_action
						}
					}
				}
			}
		}
	}
}
