code:
using System.Text;
using RimWorld;
using UnityEngine;
using Verse;
using System;
using System.Collections.Generic;
using System.Linq;
using Multiplayer.API;
using Verse.AI.Group;

namespace rjw
{
	//TODO: check slime stuff working in mp
	//TODO: separate menus in sub scripts
	//TODO: add demon switch parts
	//TODO: figure out and make interface?
	//TODO: add vibration toggle for bionics(+50% partner satisfaction?)
	public class Dialog_Sexcard : Window
	{
		private readonly Pawn pawn;

		public Dialog_Sexcard(Pawn editFor)
		{
			pawn = editFor;
		}

		public static breasts Breasts;
		public enum breasts
		{
			selectone,
			none,
			featureless_chest,
			flat_breasts,
			small_breasts,
			average_breasts,
			large_breasts,
			huge_breasts,
			slime_breasts,
		};

		public static anuses Anuses;
		public enum anuses
		{
			selectone,
			none,
			micro_anus,
			tight_anus,
			average_anus,
			loose_anus,
			gaping_anus,
			slime_anus,
		};

		public static vaginas Vaginas;
		public enum vaginas
		{
			selectone,
			none,
			micro_vagina,
			tight_vagina,
			average_vagina,
			loose_vagina,
			gaping_vagina,
			slime_vagina,
			feline_vagina,
			canine_vagina,
			equine_vagina,
			dragon_vagina,
		};

		public static penises Penises;
		public enum penises
		{
			selectone,
			none,
			micro_penis,
			small_penis,
			average_penis,
			big_penis,
			huge_penis,
			slime_penis,
			feline_penis,
			canine_penis,
			equine_penis,
			dragon_penis,
			raccoon_penis,
			hemipenis,
			crocodilian_penis,
		};

		public void SexualityCard(Rect rect, Pawn pawn)
		{
			CompRJW comp = pawn.TryGetComp<CompRJW>();
			if (pawn == null || comp == null) return;

			Text.Font = GameFont.Medium;
			Rect rect1 = new Rect(8f, 4f, rect.width - 8f, rect.height - 20f);
			Widgets.Label(rect1, SaveStorage.ModId);//rjw

			Text.Font = GameFont.Tiny;
			float num = rect1.y + 40f;
			Rect row1 = new Rect(10f, num, rect.width - 8f, 24f);//sexuality
			Rect row2 = new Rect(10f, num + 24, rect.width - 8f, 24f);//quirks
			Rect row3 = new Rect(10f, num + 48, rect.width - 8f, 24f);//whore price

			//Rect sexuality_button = new Rect(10f, rect1.height - 0f, rect.width - 8f, 24f);//change sex pref
			Rect button1 = new Rect(10f, rect1.height - 10f, rect.width - 8f, 24f);//re sexualize
			Rect button2 = new Rect(10f, rect1.height - 34f, rect.width - 8f, 24f);//archtech toggle
			Rect button3 = new Rect(10f, rect1.height - 58f, rect.width - 8f, 24f);//breast
			Rect button4 = new Rect(10f, rect1.height - 82f, rect.width - 8f, 24f);//anus
			Rect button5 = new Rect(10f, rect1.height - 106f, rect.width - 8f, 24f);//vagina
			Rect button6 = new Rect(10f, rect1.height - 130f, rect.width - 8f, 24f);//penis 1
			Rect button7 = new Rect(10f, rect1.height - 154f, rect.width - 8f, 24f);//penis 2
			Rect button8 = new Rect(10f, rect1.height + 14f, rect.width/2 - 8f, 24f);//show Would_fuck
			Rect button9 = new Rect(10f + rect.width / 2, rect1.height + 14f, rect.width/2 - 8f, 24f);//show Would_fuck table

			DrawSexuality(pawn, row1);
			DrawQuirks(pawn, row2);
			//DrawWhoring(pawn, row3);

			// TODO: Add translations. or not
			if (RJWSettings.DevMode || Current.ProgramState != ProgramState.Playing)
			{
				if (Widgets.ButtonText(button1, Current.ProgramState != ProgramState.Playing ? "Reroll" : "[DEV] Reroll"))
				{
					Re_sexualize(pawn);
				}
			}
			if (RJWSettings.DevMode && Current.ProgramState == ProgramState.Playing)
			{
				if (Widgets.ButtonText(button8, "Would_fuck chances"))
				{
					Would_fuck(pawn);
				}
				if (Widgets.ButtonText(button9, "Would_fuck chances (CSV Table)"))
				{
					Would_fuckT(pawn);
				}
			}
			//Archotech genitals FertilityToggle
			List<Hediff> parts = new List<Hediff>();
			var GenitalBPR = Genital_Helper.get_genitalsBPR(pawn);
			parts = Genital_Helper.get_PartsHediffList(pawn, GenitalBPR);

			if (!parts.NullOrEmpty())
			{
				foreach (var p in parts)
				{
					if (PartProps.TryGetProps(p, out List<string> l) && l.Contains("FertilityToggle"))
					{
						if (pawn.health.hediffSet.HasHediff(HediffDef.Named("ImpregnationBlocker")))
						{
							if (Widgets.ButtonText(button2, "Enable reproduction"))
							{
								Change_Fertility(pawn);
							}
						}
						else if (!pawn.health.hediffSet.HasHediff(HediffDef.Named("FertilityEnhancer")))
						{
							if (Widgets.ButtonText(button2, "Enchance fertility"))
							{
								Change_Fertility(pawn);
							}
						}
						else
						{
							if (Widgets.ButtonText(button2, "Disable reproduction"))
							{
								Change_Fertility(pawn);
							}
						}
						break;
					}
				}
			}

			// TODO: add mp synchronizers
			// TODO: clean that mess
			// TODO: add demon toggles
			if (MP.IsInMultiplayer)
				return;

			//List<String> Parts = null;
			//if (xxx.is_slime(pawn))
			//	Parts = new List<string>(DefDatabase<StringListDef>.GetNamed("SlimeMorphFilters").strings);
			//if (xxx.is_demon(pawn))
			//	Parts = new List<string>(DefDatabase<StringListDef>.GetNamed("DemonMorphFilters").strings);

			//if (Parts.Any() && (pawn.IsColonistPlayerControlled || pawn.IsPrisonerOfColony || pawn.IsSlaveOfColony))
				//if (xxx.is_slime(pawn) && (pawn.IsColonistPlayerControlled || pawn.IsPrisonerOfColony || pawn.IsSlaveOfColony))
			if (pawn.IsColonistPlayerControlled || pawn.IsPrisonerOfColony || pawn.IsSlaveOfColony)
			{
				BodyPartRecord bpr_genitalia = Genital_Helper.get_genitalsBPR(pawn);
				BodyPartRecord bpr_breasts = Genital_Helper.get_breastsBPR(pawn);
				BodyPartRecord bpr_anus = Genital_Helper.get_anusBPR(pawn);
				BodyPartRecord partBPR = null;
				Rect Button = new Rect();

				Button = button3;
				partBPR = bpr_breasts;
				Make_button(Button, pawn, partBPR);

				Button = button4;
				partBPR = bpr_anus;
				Make_button(Button, pawn, partBPR);

				Button = button5;
				partBPR = bpr_genitalia;
				Make_button(Button, pawn, partBPR, "p");

				Button = button6;
				partBPR = bpr_genitalia;
				Make_button(Button, pawn, partBPR, "v");
			}
		}

		static void DrawSexuality(Pawn pawn, Rect row)
		{
			string sexuality;

			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Vanilla)
				CompRJW.VanillaTraitCheck(pawn);
			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.SYRIndividuality)
				CompRJW.CopyIndividualitySexuality(pawn);
			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.Psychology)
				CompRJW.CopyPsychologySexuality(pawn);

			switch (CompRJW.Comp(pawn).orientation)
			{
				case Orientation.Asexual:
					sexuality = "Asexual";
					break;
				case Orientation.Bisexual:
					sexuality = "Bisexual";
					break;
				case Orientation.Heterosexual:
					sexuality = "Hetero";
					break;
				case Orientation.Homosexual:
					sexuality = "Gay";
					break;
				case Orientation.LeaningHeterosexual:
					sexuality = "Bisexual, leaning hetero";
					break;
				case Orientation.LeaningHomosexual:
					sexuality = "Bisexual, leaning gay";
					break;
				case Orientation.MostlyHeterosexual:
					sexuality = "Mostly hetero";
					break;
				case Orientation.MostlyHomosexual:
					sexuality = "Mostly gay";
					break;
				case Orientation.Pansexual:
					sexuality = "Pansexual";
					break;
				default:
					sexuality = "None";
					break;
			}

			//allow to change pawn sexuality for:
			//own hero, game start
			if (RJWPreferenceSettings.sexuality_distribution == RJWPreferenceSettings.Rjw_sexuality.RimJobWorld &&
				(((Current.ProgramState == ProgramState.Playing &&
				pawn.IsDesignatedHero() && pawn.IsHeroOwner()) ||
				Prefs.DevMode) ||
				Current.ProgramState == ProgramState.Entry))

			{
				if (Widgets.ButtonText(row, "Sexuality: " + sexuality, false))
				{
					Find.WindowStack.Add(new FloatMenu(new List<FloatMenuOption>()			//this needs fixing in 1.1 with vanilla orientation traits
					{
						new FloatMenuOption("Asexual", (() => Change_orientation(pawn, Orientation.Asexual)), MenuOptionPriority.Default),
						new FloatMenuOption("Pansexual", (() => Change_orientation(pawn, Orientation.Pansexual)), MenuOptionPriority.Default),
						new FloatMenuOption("Heterosexual", (() => Change_orientation(pawn, Orientation.Heterosexual)), MenuOptionPriority.Default),
						new FloatMenuOption("MostlyHeterosexual", (() => Change_orientation(pawn, Orientation.MostlyHeterosexual)), MenuOptionPriority.Default),
						new FloatMenuOption("LeaningHeterosexual", (() => Change_orientation(pawn, Orientation.LeaningHeterosexual)), MenuOptionPriority.Default),
						new FloatMenuOption("Bisexual", (() => Change_orientation(pawn, Orientation.Bisexual)), MenuOptionPriority.Default),
						new FloatMenuOption("LeaningHomosexual", (() => Change_orientation(pawn, Orientation.LeaningHomosexual)), MenuOptionPriority.Default),
						new FloatMenuOption("MostlyHomosexual", (() => Change_orientation(pawn, Orientation.MostlyHomosexual)), MenuOptionPriority.Default),
						new FloatMenuOption("Homosexual", (() => Change_orientation(pawn, Orientation.Homosexual)), MenuOptionPriority.Default),
					}));
				}
			}
			else
			{
				Widgets.Label(row, "Sexuality: " + sexuality);
				if (Mouse.IsOver(row))
					Widgets.DrawHighlight(row);
			}
		}

		static void DrawQuirks(Pawn pawn, Rect row)
		{

			var quirks = Quirk.All
				.Where(quirk => pawn.Has(quirk))
				.OrderBy(quirk => quirk.Key)
				.ToList();

			// Not actually localized.
			var quirkString = quirks.Select(quirk => quirk.Key).ToCommaList();

			if ((Current.ProgramState == ProgramState.Playing &&
				pawn.IsDesignatedHero() && pawn.IsHeroOwner() ||
				Prefs.DevMode) ||
				Current.ProgramState == ProgramState.Entry)

			{
				var quirksAll = Quirk.All
								.OrderBy(quirk => quirk.Key)
								.ToList();

				if (!RJWSettings.DevMode)
				{
					quirksAll.Remove(Quirk.Breeder);
					quirksAll.Remove(Quirk.Incubator);
				}

				if (xxx.is_insect(pawn))
					quirksAll.Add(Quirk.Incubator);

				if (Widgets.ButtonText(row, "Quirks".Translate() + quirkString, false))
				{
					var list = new List<FloatMenuOption>();
					list.Add(new FloatMenuOption("Reset", (() => QuirkAdder.Clear(pawn)), MenuOptionPriority.Default));
					foreach (Quirk quirk in quirksAll)
					{
						if (!pawn.Has(quirk))
							list.Add(new FloatMenuOption(quirk.Key, (() => QuirkAdder.Add(pawn, quirk, warnOnFail: true))));
						//else
						//	list.Add(new FloatMenuOption(quirk.Key, (() => QuirkAdder.Remove(pawn, quirk))));
						//TODO: fix quirk description box in 1.1 menus
						//list.Add(new FloatMenuOption(quirk.Key, (() => QuirkAdder.Add(pawn, quirk)), MenuOptionPriority.Default, delegate
						//{
						//	TooltipHandler.TipRegion(row, quirk.LocaliztionKey.Translate(pawn.Named("pawn")));
						//}
						//));
					}
					Find.WindowStack.Add(new FloatMenu(list));
				}
			}
			else
			{
				// TODO: long quirk list support
				// This can be too long and line wrap.
				// Should probably be a vertical list like traits.
				Widgets.Label(row, "Quirks".Translate() + quirkString);

			}

			if (!Mouse.IsOver(row)) return;

			Widgets.DrawHighlight(row);
			if (quirks.NullOrEmpty())
			{
				TooltipHandler.TipRegion(row, "NoQuirks".Translate());
			}
			else
			{
				StringBuilder stringBuilder = new StringBuilder();
				foreach (var q in quirks)
				{
					stringBuilder.AppendLine(q.Key.Colorize(Color.yellow));
					stringBuilder.AppendLine(q.LocaliztionKey.Translate(pawn.Named("pawn")).AdjustedFor(pawn).Resolve());
					stringBuilder.AppendLine("");
				}
				string str = stringBuilder.ToString().TrimEndNewlines();
				TooltipHandler.TipRegion(row, str);
			}
		}

		//static string DrawWhoring(Pawn pawn, Rect row)
		//{
			//string price;
			//if (RJWSettings.sex_age_legacymode && pawn.ageTracker.AgeBiologicalYears < RJWSettings.sex_minimum_age)
			//	price = "Inapplicable (too young)";
			//else if (!RJWSettings.sex_age_legacymode && pawn.ageTracker.Growth < 1 && !pawn.ageTracker.CurLifeStage.reproductive)
			//	price = "Inapplicable (too young)";
			//else if (pawn.ownership.OwnedRoom == null)
			//{
			//	if (Current.ProgramState == ProgramState.Playing)
			//		price = WhoringHelper.WhoreMinPrice(pawn) + " - " + WhoringHelper.WhoreMaxPrice(pawn) + " (base, needs suitable bedroom)";
			//	else
			//		price = WhoringHelper.WhoreMinPrice(pawn) + " - " + WhoringHelper.WhoreMaxPrice(pawn) + " (base, modified by bedroom quality)";
			//}
			//else if (xxx.is_animal(pawn))
			//	price = "Incapable of whoring";
			//else
			//	price = WhoringHelper.WhoreMinPrice(pawn) + " - " + WhoringHelper.WhoreMaxPrice(pawn);

			//Widgets.Label(row, "WhorePrice".Translate() + price);
			//if (Mouse.IsOver(row))
			//	Widgets.DrawHighlight(row);
			//return price;
		//}

		[SyncMethod]
		static void Change_orientation(Pawn pawn, Orientation orientation)
		{
			CompRJW.Comp(pawn).orientation = orientation;
		}

		[SyncMethod]
		static void Change_Fertility(Pawn pawn)
		{
			BodyPartRecord genitalia = Genital_Helper.get_genitalsBPR(pawn);
			Hediff blocker = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("ImpregnationBlocker"));
			Hediff enhancer = pawn.health.hediffSet.GetFirstHediffOfDef(HediffDef.Named("FertilityEnhancer"));

			if (blocker != null)
			{
				pawn.health.RemoveHediff(blocker);
			}
			else if (enhancer == null)
			{
				pawn.health.AddHediff(HediffDef.Named("FertilityEnhancer"), genitalia);
			}
			else
			{
				if (enhancer != null)
					pawn.health.RemoveHediff(enhancer);
				pawn.health.AddHediff(HediffDef.Named("ImpregnationBlocker"), genitalia);
			}
		}

		[SyncMethod]
		static void Re_sexualize(Pawn pawn)
		{
			CompRJW.Comp(pawn).Sexualize(pawn, true);
		}

		static void Would_fuck(Pawn pawn)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine();
			stringBuilder.AppendLine("canFuck: " + xxx.can_fuck(pawn) + ", canBeFucked: " + xxx.can_be_fucked(pawn) + ", canDoLoving: " + xxx.can_do_loving(pawn));
			stringBuilder.AppendLine("canRape: " + xxx.can_rape(pawn) + ", canBeRaped: " + xxx.can_get_raped(pawn));

			if (!pawn.IsColonist)
				if (pawn.Faction != null)
				{
					int pawnAmountOfSilvers = pawn.inventory.innerContainer.TotalStackCountOfDef(ThingDefOf.Silver);
					int caravanAmountOfSilvers = 0;
					Lord lord = pawn.GetLord();
					List<Pawn> caravanMembers = pawn.Map.mapPawns.PawnsInFaction(pawn.Faction).Where(x => x.GetLord() == lord && x.inventory?.innerContainer?.TotalStackCountOfDef(ThingDefOf.Silver) > 0).ToList();

					caravanAmountOfSilvers += caravanMembers.Sum(member => member.inventory.innerContainer.TotalStackCountOfDef(ThingDefOf.Silver));

					stringBuilder.AppendLine("pawnSilvers: " + pawnAmountOfSilvers + ", caravanSilvers: " + caravanAmountOfSilvers);
				}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Humans - Colonists:");
			List<Pawn> pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Humanlike && x.IsColonist).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Humans - Prisoners:");
			pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Humanlike && !x.IsColonist && x.IsPrisonerOfColony).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Humans - Slaves:");
			pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Humanlike && !x.IsColonist && x.IsSlaveOfColony).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Humans - non Colonists:");
			pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Humanlike && !x.IsColonist && !x.IsPrisonerOfColony && !x.IsSlaveOfColony).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Animals - Colony:");
			pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Animal && x.Faction == Faction.OfPlayer).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					//", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			stringBuilder.AppendLine();

			stringBuilder.AppendLine("Animals - non Colony:");
			pawns = pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != pawn && x.RaceProps.Animal && x.Faction != Faction.OfPlayer).OrderBy(x => xxx.get_pawnname(x)).ToList();
			foreach (Pawn partner in pawns)
			{
				stringBuilder.AppendLine(partner.LabelShort + " (" + partner.gender.GetLabel() +
					", age: " + partner.ageTracker.AgeBiologicalYears +
					//", " + CompRJW.Comp(partner).orientation +
					"): (would fuck) " + SexAppraiser.would_fuck(pawn, partner).ToString("F3") +
					"): (be fucked) " + SexAppraiser.would_fuck(partner, pawn).ToString("F3") +
					": (rape) " + SexAppraiser.would_rape(pawn, partner));
			}
			Find.WindowStack.Add(new Dialog_MessageBox(stringBuilder.ToString(), null, null, null, null, null, false, null, null));
		}
		static void Would_fuckT(Pawn pawn)
		{
			{
				DebugTables.MakeTablesDialog(pawn.Map.mapPawns.AllPawnsSpawned.Where(x => x != null & x != pawn),
					new TableDataGetter<Pawn>("Name", (Pawn p) => p.NameFullColored),
					new TableDataGetter<Pawn>("Age", (Pawn p) => p.ageTracker.AgeBiologicalYears),
					new TableDataGetter<Pawn>("Gender", (Pawn p) => p.gender.GetLabel()),
					new TableDataGetter<Pawn>("isAnimal", (Pawn p) => p.RaceProps.Animal),
					new TableDataGetter<Pawn>("isAnimalOfColony", (Pawn p) => p.RaceProps.Animal & p.Faction == Faction.OfPlayer),
					new TableDataGetter<Pawn>("IsColonist", (Pawn p) => p.IsColonist),
					new TableDataGetter<Pawn>("IsPrisonerOfColony", (Pawn p) => p.IsPrisonerOfColony),
					new TableDataGetter<Pawn>("IsSlaveOfColony", (Pawn p) => p.IsSlaveOfColony),
					new TableDataGetter<Pawn>("would fuck score", (Pawn p) => SexAppraiser.would_fuck(pawn, p).ToStringPercent()),
					new TableDataGetter<Pawn>("be fucked score", (Pawn p) => SexAppraiser.would_fuck(p, pawn).ToStringPercent()),
					new TableDataGetter<Pawn>("would rape", (Pawn p) => SexAppraiser.would_rape(pawn, p)),
					new TableDataGetter<Pawn>("be raped", (Pawn p) => SexAppraiser.would_rape(p, pawn))
				);
			}
		}

		static void Make_button(Rect Button, Pawn pawn, BodyPartRecord partBPR, string gen = "")
		{
			string ButtonLabel = "nothing here";
			bool resizable = RJWSettings.DevMode;
			List<Hediff> parts = new List<Hediff>();
			List<Hediff> parts1 = new List<Hediff>();
			Hediff hed = null;

			parts = Genital_Helper.get_PartsHediffList(pawn, partBPR);
			if (!parts.NullOrEmpty())
			{
				if (gen == "p")
					parts1.AddRange(parts.Where(x => Genital_Helper.is_penis(x)));
				if (gen == "v")
					parts1.AddRange(parts.Where(x => Genital_Helper.is_vagina(x)));
				if (gen != "")
					parts = parts1;

				if (!parts.NullOrEmpty())
					hed = parts.FirstOrDefault();

				if (hed != null)
				{
					//ButtonLabel = "Morph breasts";
					ButtonLabel = "Change " + hed.Label + " size";

					if (!resizable)
						foreach (var p in parts)
						{
							if (PartProps.TryGetProps(p, out List<string> l) && l.Contains("Resizable"))
								resizable = true;
						}

					if (resizable)
						if (hed is Hediff_PartBaseNatural)
						{
							Make_resize_button(Button, ButtonLabel, hed, parts);
						}
						else if (hed is Hediff_PartBaseArtifical)
						{
							Make_resize_button(Button, ButtonLabel, hed, parts);
						}
				}
			}
		}

		static void Make_resize_button(Rect Button, string ButtonLabel, Hediff hed, List<Hediff> parts)
		{
			if (Widgets.ButtonText(Button, ButtonLabel))
			{
				var stages = hed.def.stages;
				var opts = new List<FloatMenuOption>();

				foreach (var s in stages)
				{
					opts.Add(new FloatMenuOption(hed.def.label.CapitalizeFirst() + "(" + s.label.CapitalizeFirst() + ")", () =>
					{
						foreach (var p in parts)
						{
							if (RJWSettings.DevMode ||
							(PartProps.TryGetProps(p, out List<string> l) && l.Contains("Resizable")))
								p.Severity = s.minSeverity;
						}
					}, MenuOptionPriority.Default));
				}

				Find.WindowStack.Add(new FloatMenu(opts));
			}
		}

		public override void DoWindowContents(Rect inRect)
		{
			bool flag = false;
			soundClose = SoundDefOf.InfoCard_Close;
			closeOnClickedOutside = true;
			absorbInputAroundWindow = false;
			forcePause = true;
			preventCameraMotion = false;
			if (Event.current.type == EventType.KeyDown && (Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.Escape))
			{
				flag = true;
				Event.current.Use();
			}
			Rect windowRect = inRect.ContractedBy(17f);
			Rect mainRect = new Rect(windowRect.x, windowRect.y, windowRect.width, windowRect.height - 20f);
			Rect okRect = new Rect(inRect.width / 3, mainRect.yMax + 10f, inRect.width / 3f, 30f);
			SexualityCard(mainRect, pawn);
			if (Widgets.ButtonText(okRect, "CloseButton".Translate()) || flag)
			{
				Close();
			}
		}
	}
}


code:
using HarmonyLib;
using Verse;
using System;
using RimWorld;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// patches PawnUtility to fix humanlike childrens post birth
/// </summary>
namespace rjw
{
	[HarmonyPatch(typeof(PawnRenderer), "DrawBodyApparel")]
	static class Patch_PawnRenderer_DrawBodyApparel
	{
		//[HarmonyPrefix]
		//static void prefix_TrySpawnHatchedOrBornPawn(ref Pawn pawn, Thing motherOrEgg)
		//{
		//	//ModLog.Message("prefix_TrySpawnHatchedOrBornPawn::");
		//	//ModLog.Message(" " + __result);
		//	//ModLog.Message(" " + xxx.get_pawnname(pawn));
		//	//ModLog.Message(" " + xxx.get_pawnname(motherOrEgg as Pawn));
		//	//ModLog.Message(" " + RJWPregnancySettings.humanlike_pregnancy_enabled);
		//	//ModLog.Message(" " + xxx.is_human(pawn));
		//	//ModLog.Message(" " + !xxx.is_mechanoid(pawn));
		//	//string last_name = NameTriple.FromString(pawn.Name.ToStringFull).Last;
		//	//ModLog.Message(" prefix_TrySpawnHatchedOrBornPawn Baby surname will be " + last_name);
		//}

		//resets pawn/doesn't work for some races with C# constructors
		[HarmonyPrefix]
		static bool prefix_DrawBodyApparel(ref Pawn pawn)
		{
			if (pawn.jobs?.curDriver is JobDriver_Sex)
			{
				ModLog.Message(pawn.Name+ " sex");
				SexUtility.DrawNude(pawn);
				return false;
			}
			return true;
		}
	}
}

license: mit


code:
using System;
using System.Collections.Generic;
using HarmonyLib;
using RimWorld;
using Verse;
using Verse.AI.Group;
using System.Reflection;

namespace rjw
{
	//ABF?? raid rape before leaving?
	[HarmonyPatch(typeof(LordJob_AssaultColony), "CreateGraph")]
	internal static class Patches_AssaultColonyForRape
	{
		[HarmonyPostfix]
		public static void Postfix(StateGraph __result)
		{
			//--Log.Message("[ABF]AssaultColonyForRape::CreateGraph");
			if (__result == null) return;
			//--ModLog.Message("AssaultColonyForRape::CreateGraph");
			foreach (var trans in __result.transitions)
			{
				if (HasDesignatedTransition(trans))
				{
					foreach (Trigger t in trans.triggers)
					{
						if (t.filters == null)
						{
							t.filters = new List<TriggerFilter>() { new Trigger_SexSatisfy(0.3f) };
						}
						else
						{
							t.filters.Add(new Trigger_SexSatisfy(0.3f));
						}
					}
					//--Log.Message("[ABF]AssaultColonyForRape::CreateGraph Adding SexSatisfyTrigger to " + trans.ToString());
				}
			}
		}

		private static bool HasDesignatedTransition(Transition t)
		{
			if (t.target == null) return false;
			if (t.target.GetType() == typeof(LordToil_KidnapCover)) return true;

			foreach (Trigger ta in t.triggers)
			{
				if (ta.GetType() == typeof(Trigger_FractionColonyDamageTaken)) return true;
			}
			return false;
		}
	}

	/*
	[HarmonyPatch(typeof(JobGiver_Manhunter), "TryGiveJob")]
	static class Patches_ABF_MunHunt
	{
		public static void Postfix(Job __result, ref Pawn pawn)
		{
			//--ModLog.Message("Patches_ABF_MunHunt::Postfix called");
			if (__result == null) return;

			if (__result.def == JobDefOf.Wait || __result.def == JobDefOf.Goto) __result = null;
		}
	}
	*/

	[HarmonyPatch(typeof(SkillRecord), "CalculateTotallyDisabled")]
	internal static class Patches_SkillRecordDebug
	{
		[HarmonyPrefix]
		public static bool Prefix(SkillRecord __instance, ref bool __result)
		{
			var field = __instance.GetType().GetField("pawn", BindingFlags.GetField | BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Instance);
			Pawn pawn = (field.GetValue(__instance) as Pawn);
			if (__instance.def == null)
			{
				ModLog.Message("no def!");
				__result = false;
				return false;
			}
			return true;
		}
	}
}


code:
using System.Collections.Generic;
using Verse;
using HarmonyLib;

namespace rjw
{
	//adds new gizmo for sex
	[HarmonyPatch(typeof(Pawn), "GetGizmos")]
	class Patch_AddSexGizmo
	{
		[HarmonyPriority(99),HarmonyPostfix]
		static IEnumerable<Gizmo> AddSexGizmo(IEnumerable<Gizmo> __result, Pawn __instance)
		{

			foreach (Gizmo entry in __result)
			{
				yield return entry;
			}

			if (ModsConfig.RoyaltyActive)
				if (__instance?.jobs?.curDriver is JobDriver_Sex)
				{
					Gizmo SexGizmo = new SexGizmo(__instance);
					yield return SexGizmo;
				}
		}
	}
}


code:
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using RimWorld;
using Verse;
using UnityEngine;
using Multiplayer.API;

namespace rjw
{
	///
	/// Harmony patch to toggle the RJW designation box showing
	///
	[HarmonyPatch(typeof(PlaySettings), "DoPlaySettingsGlobalControls")]
	[StaticConstructorOnStartup]
	public static class RJW_corner_toggle
	{
		static readonly Texture2D icon = ContentFinder<Texture2D>.Get("UI/Commands/ComfortPrisoner_off");

		[HarmonyPostfix]
		public static void adding_RJW_toggle(WidgetRow row, bool worldView)
		{
			if (worldView) return;
			row.ToggleableIcon(ref RJWSettings.show_RJW_designation_box, icon, "RJW_designation_box_desc".Translate());
		}
	}

	///
	///Compact button group containing rjw designations on pawn
	///
	[HarmonyPatch(typeof(Pawn), "GetGizmos")]
	[StaticConstructorOnStartup]
	static class Rjw_buttons
	{
		[HarmonyPostfix]
		static void this_is_postfix(ref IEnumerable<Gizmo> __result, ref Pawn __instance)
		{
			if (!RJWSettings.show_RJW_designation_box) return;
			if (!(__instance.Faction == Faction.OfPlayer || __instance.IsPrisonerOfColony)) return;
			//Log.Message("[rjw]Harmony patch submit_button is called");
			var pawn = __instance;
			var gizmos = __result.ToList();
			gizmos.Add(new RJWdesignations(pawn));
			__result = gizmos.AsEnumerable();
		}
	}

AnimalTab
Extensions
        public static bool Pregnant( this Pawn pawn )
        {
            // get hediff
            var _hediff = pawn.health.hediffSet.GetFirstHediffOfDef( HediffDefOf.Pregnant );

            // if pregnant, and pregnancy is far enough advanced to be visible
            if ( _hediff?.Visible ?? false )
                return true;

            // not (visibly) pregnant.
            return false;
        }	///
	///Submit gizmo
	///
	[HarmonyPatch(typeof(Pawn), "GetGizmos")]
	[StaticConstructorOnStartup]
	static class submit_button
	{
		[HarmonyPostfix]
		static void this_is_postfix(ref IEnumerable<Gizmo> __result, ref Pawn __instance)
		{
			//Log.Message("[rjw]Harmony patch submit_button is called");
			var pawn = __instance;
			var gizmos = __result.ToList();
			var enabled = RJWSettings.submit_button_enabled;

			if (enabled && pawn.IsColonistPlayerControlled && pawn.Drafted)
				if (pawn.CanChangeDesignationColonist())
					if (!(pawn.kindDef.race.defName.Contains("Droid") && !AndroidsCompatibility.IsAndroid(pawn)))
					{
						gizmos.Add(new Command_Action
						{
							defaultLabel = "CommandSubmit".Translate(),
							icon = submit_icon,
							defaultDesc = "CommandSubmitDesc".Translate(),
							action = delegate
							{
								LayDownAndAccept(pawn);
							},
							hotKey = KeyBindingDefOf.Misc3
						});
					}
			__result = gizmos.AsEnumerable();
		}

		static Texture2D submit_icon = ContentFinder<Texture2D>.Get("UI/Commands/Submit", true);
		static HediffDef submit_hediff = HediffDef.Named("Hediff_Submitting");

		[SyncMethod]
		static void LayDownAndAccept(Pawn pawn)
		{
			//Log.Message("Submit button is pressed for " + pawn);
			pawn.health.AddHediff(submit_hediff);
		}
	}
}


code:
using System.Reflection;
using Harmony;
using RimWorld;
using Verse;
using System;

namespace rjw
{
	/// <summary>
	/// Conditional patching class that only does patching if CnP is active
	/// </summary>
	public class patch_CnPBnC
	{
		private readonly static Type Hediff_Baby = AccessTools.TypeByName("Hediff_Baby");
		Notify_TraitChanged()
			//CnP (or BnC) try to address the joy need of a child, prisoners don't have that.
								//Considering how you can arrest children without rjw, it is more of a bug of that mod than ours.
		[HarmonyPatch(typeof(HediffGiver_Birthday), "GrowUpTo")]
		static class jfpk
		{
			[HarmonyPostfix]
			static void postfix(ref Pawn_NeedsTracker __instance)
			{
				Pawn_NeedsTracker tr = __instance;
				FieldInfo fieldInfo = AccessTools.Field(typeof(Pawn_NeedsTracker), "pawn");
				Pawn pawn = fieldInfo.GetValue(__instance) as Pawn;
				if (xxx.is_human(pawn) && pawn.ageTracker.CurLifeStageIndex < AgeStage.Teenager)
				{
					if (tr.TryGetNeed(NeedDefOf.Joy) == null)
					{
						MethodInfo method = AccessTools.Method(typeof(Pawn_NeedsTracker), "AddNeed");
						method.Invoke(tr, new object[] { NeedDefOf.Joy });
					}
				}
			}
		}
	}
}


code:
using HarmonyLib;
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using Verse;
using Verse.AI;

namespace rjw
{
	/// <summary>
	/// count (rjw) bodypart with missing rjw part as missing to prevent damage
	/// </summary>
	[HarmonyPatch(typeof(HediffSet), "PartIsMissing")]
	internal static class PATCH_HediffSet_GetRandomNotMissingPart
	{
		[HarmonyPostfix]
		private static void rjwPartIsMissing(ref bool __result, ref HediffSet __instance, BodyPartRecord part)
		{
			if (__result == true)
				return;

			var pawn = __instance.pawn;

			if (__instance.pawn != null)
			{
				if (part.def == xxx.genitalsDef && pawn.GetGenitalsList().NullOrEmpty())
					__result = true;
				else if (part.def == xxx.breastsDef && pawn.GetBreastList().NullOrEmpty())
					__result = true;
				else if (part.def == xxx.anusDef && pawn.GetAnusList().NullOrEmpty())
					__result = true;
			}
		}
	}

	/// <summary>
	/// count (rjw) bodypart with missing rjw part as missing to prevent damage
	/// </summary>
	[HarmonyPatch(typeof(HediffSet), "GetNotMissingParts")]
	internal static class PATCH_HediffSet_GetRandomNotMissingPart
	{
		[HarmonyPostfix]
		private static IEnumerable<BodyPartRecord> rjwGetNotMissingParts(IEnumerable<BodyPartRecord> __result, Pawn pawn)
		{
			//IEnumerable<BodyPartRecord> t;
			foreach (var bpr in __result)
			{
				if (bpr.def == xxx.genitalsDef && pawn.GetGenitalsList().NullOrEmpty())
					continue;
				else if (bpr.def == xxx.breastsDef && pawn.GetBreastList().NullOrEmpty())
					continue;
				else if (bpr.def == xxx.anusDef && pawn.GetAnusList().NullOrEmpty())
					continue;

				yield return bpr;
			}
		}
	}

	/// <summary>
	/// count rjw bodypart with missing rjw part as missing to prevent damage
	/// </summary>
	[HarmonyPatch(typeof(DamageWorker.DamageResult), "AddPart")]
	internal static class PATCH_DamageWorker_AddPart
	{
		[HarmonyPrefix]
		private static bool Disable_damage(Thing hitThing, BodyPartRecord part)
		{
			Pawn pawn = hitThing as Pawn;

			if (pawn != null)
			{
				if (part.def == xxx.genitalsDef && pawn.GetGenitalsList().NullOrEmpty())
					return false;
				if (part.def == xxx.breastsDef && pawn.GetBreastList().NullOrEmpty())
					return false;
				if (part.def == xxx.anusDef && pawn.GetAnusList().NullOrEmpty())
					return false;
			}

			return true;
		}
	}
}


code:
using System;
using RimWorld;
using Verse;
using HarmonyLib;

namespace rjw
{
	///<summary>
	///Disable vanilla(?) traders from buying/selling natural rjw parts
	///</summary>
	[HarmonyPatch(typeof(StockGenerator_BuyExpensiveSimple), "HandlesThingDef")]
	[StaticConstructorOnStartup]
	static class PATCH_StockGenerator_BuyExpensiveSimple_HandlesThingDef
	{
		[HarmonyPostfix]
		static void remove_RJW_stuff_fromtraderBUY(ref bool __result, ThingDef thingDef)
		{
			if (thingDef == null)
				return;
			if (thingDef.tradeTags.NullOrEmpty())
				return;
			if (thingDef.tradeTags.Contains("RJW_NoBuy"))
				__result = false;
		}
	}
}


code:
using System;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using Verse;
using Verse.AI;

namespace rjw
{
	[HarmonyPatch(typeof(Pawn_ApparelTracker))]
	[HarmonyPatch("Wear")]
	internal static class PATCH_Pawn_ApparelTracker_Wear
	{
		// Prevents pawns from equipping a piece of apparel if it conflicts with some locked apparel that they're already wearing
		[HarmonyPrefix]
		private static bool prevent_wear_by_gear(Pawn_ApparelTracker __instance, ref Apparel newApparel)
		{
			var tra = __instance;
			// //--Log.Message ("Pawn_ApparelTracker.Wear called for " + newApparel.Label + " on " + tra.xxx.get_pawnname(pawn));
			foreach (var app in tra.WornApparel)
				if (app.has_lock() && (!ApparelUtility.CanWearTogether(newApparel.def, app.def, tra.pawn.RaceProps.body)))
				{
					if (PawnUtility.ShouldSendNotificationAbout(tra.pawn))
						Messages.Message(xxx.get_pawnname(tra.pawn) + " can't wear " + newApparel.def.label + " (blocked by " + app.def.label + ")", tra.pawn, MessageTypeDefOf.NegativeEvent);
					return false;
				}
			return true;
		}

		// Add the appropriate hediff when gear is worn
		[HarmonyPostfix]
		private static void on_wear(Pawn_ApparelTracker __instance, Apparel newApparel)
		{
			var tra = __instance;
			if ((newApparel.def is bondage_gear_def def) &&
				(newApparel.Wearer == tra.pawn))
			{ // Check that the apparel was actually worn
				def.soul.on_wear(tra.pawn, newApparel);
			}
		}
	}

	// Remove the hediff when the gear is removed
	[HarmonyPatch(typeof(Pawn_ApparelTracker))]
	[HarmonyPatch("Notify_ApparelRemoved")]
	internal static class PATCH_Pawn_ApparelTracker_Remove
	{
		[HarmonyPostfix]
		private static void on_remove(Pawn_ApparelTracker __instance, Apparel apparel)
		{
			if (apparel.def is bondage_gear_def def)
			{
				def.soul.on_remove(apparel, __instance.pawn);
			}
		}
	}

	// Patch the TryDrop method so that locked apparel cannot be dropped by JobDriver_RemoveApparel or by stripping
	// a corpse or downed pawn
	internal static class PATCH_Pawn_ApparelTracker_TryDrop
	{
		// Can't call MakeByRefType in an attribute, which is why this method is necessary.
		private static MethodInfo get_target()
		{
			return typeof(Pawn_ApparelTracker).GetMethod("TryDrop", new Type[] {
				typeof(Apparel),
				typeof(Apparel).MakeByRefType (),
				typeof(IntVec3),
				typeof(bool)
			});
		}

		// Can't just put [HarmonyTargetMethod] on get_target, which is why this method is necessary. BTW I don't
		// know why HarmonyTargetMethod wasn't working. I'm sure I had everything set up properly so it might be a
		// bug in Harmony itself, but I can't be bothered to look into it in detail.
		public static void apply(Harmony har)
		{
			var tar = get_target();
			var pat = typeof(PATCH_Pawn_ApparelTracker_TryDrop).GetMethod("prevent_locked_apparel_drop");
			har.Patch(tar, new HarmonyMethod(pat), null);
		}

		public static bool prevent_locked_apparel_drop(Pawn_ApparelTracker __instance, ref Apparel ap, ref bool __result)
		{
			if (!ap.has_lock())
				return true;
			else
			{
				__result = false;
				return false;
			}
		}
	}

	// Prevent locked apparel from being removed from a pawn who's out on a caravan
	// TODO: Allow the apparel to be removed if the key is in the caravan's inventory
	//[HarmonyPatch (typeof (WITab_Caravan_Gear))]
	//[HarmonyPatch ("TryRemoveFromCurrentWearer")]
	//static class PATCH_WITab_Caravan_Gear_TryRemoveFromCurrentWearer {
	//	[HarmonyPrefix]
	//	static bool prevent_locked_apparel_removal (WITab_Caravan_Gear __instance, Thing t, ref bool __result)
	//	{
	//		var app = t as Apparel;
	//		if ((app == null) || (! app.has_lock ()))
	//			return true;
	//		else {
	//			__result = false;
	//			return false;
	//		}
	//	}
	//}

	// Check for the special case where a player uses the caravan gear tab to equip a piece of lockable apparel on a pawn that
	// is wearing an identical piece of already locked apparel, and make sure that doesn't work or change anything. This is to
	// fix a bug where, even though the new apparel would fail to be equipped on the pawn, it would somehow copy the holostamp
	// info from the equipped apparel.
	[HarmonyPatch(typeof(WITab_Caravan_Gear))]
	[HarmonyPatch("TryEquipDraggedItem")]
	internal static class PATCH_WITab_Caravan_Gear_TryEquipDraggedItem
	{
		private static Thing get_dragged_item(WITab_Caravan_Gear tab)
		{
			return (Thing)typeof(WITab_Caravan_Gear).GetField("draggedItem", xxx.ins_public_or_no).GetValue(tab);
		}

		private static void set_dragged_item(WITab_Caravan_Gear tab, Thing t)
		{
			typeof(WITab_Caravan_Gear).GetField("draggedItem", xxx.ins_public_or_no).SetValue(tab, t);
		}

		[HarmonyPrefix]
		private static bool prevent_locked_apparel_conflict(WITab_Caravan_Gear __instance, ref Pawn p)
		{
			if (__instance == null) return true;
			if (get_dragged_item(__instance) is Apparel dragged_app && p.apparel != null && dragged_app.has_lock())
			{
				foreach (var equipped_app in p.apparel.WornApparel)
				{
					if (equipped_app.has_lock() && (!ApparelUtility.CanWearTogether(dragged_app.def, equipped_app.def, p.RaceProps.body)))
					{
						set_dragged_item(__instance, null);
						return false;
					}
				}
			}

			return true;
		}
	}
	/* GONE IN b19
	// Prevent locked apparel from being removed from a corpse
	// TODO: Find out when this method is actually called (probably doesn't matter but still)
	[HarmonyPatch(typeof(Dialog_FormCaravan))]
	[HarmonyPatch("RemoveFromCorpseIfPossible")]
	internal static class PATCH_Dialog_FormCaravan_RemoveFromCorpseIfPossible
	{
		[HarmonyPrefix]
		private static bool prevent_locked_apparel_removal(Dialog_FormCaravan __instance, Thing thing)
		{
			var app = thing as Apparel;
			return (app == null) || (!app.has_lock());
		}
	}
	*/
	// Patch a method in a pawn gear tab to give the pawn a special job driver if the player tells them to
	// drop locked apparel they have equipped
	// TODO: Search for the key and, if the pawn can access it, give them a new job that has them go to the key
	// and use it to unlock the apparel
	[HarmonyPatch(typeof(ITab_Pawn_Gear))]
	[HarmonyPatch("InterfaceDrop")]
	internal static class PATCH_ITab_Pawn_Gear_InterfaceDrop
	{
		private static Pawn SelPawnForGear(ITab_Pawn_Gear tab)
		{
			var pro = typeof(ITab_Pawn_Gear).GetProperty("SelPawnForGear", xxx.ins_public_or_no);
			return (Pawn)pro.GetValue(tab, null);
		}

		[HarmonyPrefix]
		private static bool drop_locked_apparel(ITab_Pawn_Gear __instance, Thing t)
		{
			var tab = __instance;
			var apparel = t as Apparel;
			if ((apparel == null) || (!apparel.has_lock()))
				return true;
			else
			{
				var p = SelPawnForGear(tab);
				if ((p.apparel != null) && (p.apparel.WornApparel.Contains(apparel)))
				{
					p.jobs.TryTakeOrderedJob(JobMaker.MakeJob(xxx.struggle_in_BondageGear, apparel));
					return false;
				}
				else
					return true;
			}
		}
	}

	// Patch the method that prisoners use to find apparel in their cell so that they don't try to wear
	// something that conflicts with locked apparel. The method used to prevent pawns from trying to
	// optimize away locked apparel won't work here because prisoners don't check GetSpecialApparelScoreOffset.
	[HarmonyPatch(typeof(JobGiver_PrisonerGetDressed))]
	[HarmonyPatch("FindGarmentCoveringPart")]
	internal static class PATCH_JobGiver_PrisonerGetDressed_FindGarmentCoveringPart
	{
		private static bool conflicts(Pawn_ApparelTracker tra, Apparel new_app)
		{
			foreach (var worn_app in tra.WornApparel)
				if (worn_app.has_lock() && (!ApparelUtility.CanWearTogether(worn_app.def, new_app.def, tra.pawn.RaceProps.body)))
					return true;

			return false;
		}

		[HarmonyPrefix]
		private static bool prevent_locked_apparel_conflict(JobGiver_PrisonerGetDressed __instance, Pawn pawn, BodyPartGroupDef bodyPartGroupDef, ref Apparel __result)
		{
			// If the prisoner is not wearing locked apparel then just run the regular method
			if (!pawn.is_wearing_locked_apparel())
				return true;

			// Otherwise, duplicate the logic in the regular method except with an additional check
			// to filter out apparel that conflicts with worn locked apparel.
			else
			{
				var room = pawn.GetRoom();
				if (room.IsPrisonCell)
					foreach (var c in room.Cells)
						foreach (var t in c.GetThingList(pawn.Map))
						{
							if ((t is Apparel app) &&
								app.def.apparel.bodyPartGroups.Contains(bodyPartGroupDef) &&
								pawn.CanReserve(app) &&
								ApparelUtility.HasPartsToWear(pawn, app.def) &&
								(!conflicts(pawn.apparel, app)))
							{
								__result = app;
								return false;
							}
						}
				__result = null;
				return false;
			}
		}
	}

	// Patch the method that prisoners use to find apparel in their cell so that they don't try to wear
	// something that conflicts with locked apparel. The method used to prevent pawns from trying to
	// optimize away locked apparel won't work here because prisoners don't check GetSpecialApparelScoreOffset.
	[HarmonyPatch(typeof(JobGiver_OptimizeApparel))]
	[HarmonyPatch("ApparelScoreRaw")]
	internal static class PATCH_JobGiver_OptimizeApparel_ApparelScoreRaw
	{
		[HarmonyPostfix]
		static void bondage_score_offset(Pawn pawn, Apparel ap, ref float __result, JobGiver_OptimizeApparel __instance)
		{
			if (ap.HasThingCategory(ThingCategoryDef.Named("Bondage")))
			{
				if (ap.Wearer == pawn)
					__result += 0f;
				else if(ap.AllComps.Any(x=> x.props is CompProperties_HoloCryptoStamped))
					__result -= 1e5f;
				else
					__result += 0f;

				//Log.Message("bondage_score_offset " + __result);

			}
		}
	}
}


code:
using System;
using System.Reflection;
using HarmonyLib;
using RimWorld;
using rjw.Modules.Interactions.Enums;
using rjw.Modules.Interactions.Objects;
using Verse;
using Verse.AI;
using static HarmonyLib.Code;

namespace rjw
{
	/// <summary>
	/// Patch:
	/// Core Loving, Mating
	/// Rational Romance LovinCasual
	/// CnP, remove pregnancy if rjw human preg enabled
	/// </summary>

	// Add a fail condition to JobDriver_Lovin that prevents pawns from lovin' if they aren't physically able/have genitals
	[HarmonyPatch(typeof(JobDriver_Lovin), "MakeNewToils")]
	internal static class PATCH_JobDriver_Lovin_MakeNewToils
	{
		[HarmonyPrefix]
		private static bool lovin_patch_n_override(JobDriver_Lovin __instance)
		{
			Pawn pawn = __instance.pawn;
			Pawn partner = null;
			Building_Bed Bed = null;
			var any_ins = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
			partner = (Pawn)(__instance.GetType().GetProperty("Partner", any_ins).GetValue(__instance, null));
			Bed = (Building_Bed)(__instance.GetType().GetProperty("Bed", any_ins).GetValue(__instance, null));

			__instance.FailOn(() => (!(xxx.can_fuck(pawn) || xxx.can_be_fucked(pawn))));
			__instance.FailOn(() => (!(xxx.can_fuck(partner) || xxx.can_be_fucked(partner))));

			if (RJWSettings.override_lovin)
			{
				pawn.jobs.EndCurrentJob(JobCondition.Incompletable);
				Job job = JobMaker.MakeJob(xxx.casual_sex, partner, Bed);
				pawn.jobs.jobQueue.EnqueueFirst(job);
			}

			return true;
		}
	}

	// Add a fail condition to JobDriver_Mate that prevents animals from lovin' if they aren't physically able/have genitals
	[HarmonyPatch(typeof(JobDriver_Mate), "MakeNewToils")]
	internal static class PATCH_JobDriver_Mate_MakeNewToils
	{
		[HarmonyPrefix]
		private static bool matin_patch_n_override(JobDriver_Mate __instance)
		{
			//only reproductive male/futa starts mating job
			Pawn pawn = __instance.pawn;
			Pawn partner = null;
			var any_ins = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
			partner = (Pawn)(__instance.GetType().GetProperty("Female", any_ins).GetValue(__instance, null));

			__instance.FailOn(() => (!(xxx.can_fuck(pawn) || xxx.can_be_fucked(pawn))));
			__instance.FailOn(() => (!(xxx.can_fuck(partner) || xxx.can_be_fucked(partner))));

			if (RJWSettings.override_matin)
			{
				//__instance.FailOn(() => (!RJWSettings.animal_on_animal_enabled));
				//if (!RJWSettings.animal_on_animal_enabled)
				//	return true;

				Job job;

				if (pawn.kindDef == partner.kindDef || pawn.RaceProps.animalType == partner.RaceProps.animalType)
					job = JobMaker.MakeJob(xxx.animalMate, partner);
				else if (RJWSettings.animal_on_animal_enabled)
					job = JobMaker.MakeJob(xxx.animalBreed, partner);
				else
					return true;

				pawn.jobs.EndCurrentJob(JobCondition.Incompletable);
				pawn.jobs.jobQueue.EnqueueFirst(job);
			}

			return true;
		}
	}

	//Patch for futa animals to initiate mating (vanialla - only male)
	[HarmonyPatch(typeof(JobGiver_Mate), "TryGiveJob")]
	internal static class PATCH_JobGiver_Mate_TryGiveJob
	{
		[HarmonyPostfix]
		public static void futa_animal_partner_search_patch(ref Job __result, Pawn pawn)
		{
			//ModLog.Message("patches_lovin::JobGiver_Mate fail, try rjw for " + xxx.get_pawnname(pawn));
			var parts = pawn.GetGenitalsList();
			if (!Genital_Helper.has_male_bits(pawn, parts) || !pawn.ageTracker.CurLifeStage.reproductive)
			{
				//ModLog.Message("patches_lovin::JobGiver_Mate " + xxx.get_pawnname(pawn) + ", has no penis " + (Genital_Helper.has_penis(pawn) || Genital_Helper.has_penis_infertile(pawn)));
				//ModLog.Message("patches_lovin::JobGiver_Mate " + xxx.get_pawnname(pawn) + ", not reproductive " + !pawn.ageTracker.CurLifeStage.reproductive);
				return;
			}
			Predicate<Thing> validator = delegate (Thing t)
			{
				Pawn pawn3 = t as Pawn;
				var valid = !pawn3.Downed
							&& pawn3 != pawn
							&& pawn3.CanCasuallyInteractNow()
							&& !pawn3.IsForbidden(pawn)
							&& !pawn3.HostileTo(pawn)
							&& PawnUtility.FertileMateTarget(pawn, pawn3)
							&& (RJWSettings.WildMode || // go wild, mate everyone
								(!RJWSettings.matin_crossbreed && pawn.def == pawn3.def) || // mate same species - vanilla behavior
								(RJWSettings.matin_crossbreed && pawn.RaceProps.animalType != AnimalType.None && pawn.RaceProps.animalType == pawn3.RaceProps.animalType)); // mate same animalType
				if (!valid && pawn3 != pawn)
				{
					//ModLog.Message("patches_lovin::JobGiver_Mate " + xxx.get_pawnname(pawn3) + ", not valid");
					//ModLog.Message("patches_lovin::JobGiver_Mate Downed " + pawn3.Downed);
					//ModLog.Message("patches_lovin::JobGiver_Mate CanCasuallyInteractNow " + pawn3.CanCasuallyInteractNow());
					//ModLog.Message("patches_lovin::JobGiver_Mate IsForbidden " + pawn3.IsForbidden(pawn));
					//ModLog.Message("patches_lovin::JobGiver_Mate FertileMateTarget " + PawnUtility.FertileMateTarget(pawn, pawn3));
				}
				return valid;
			};

			ThingRequest request = ThingRequest.ForGroup(ThingRequestGroup.Pawn);			// mate everyone, filtered by validator
			Pawn pawn2 = (Pawn)GenClosest.ClosestThingReachable(pawn.Position, pawn.Map, request, PathEndMode.Touch, TraverseParms.For(pawn), 30f, validator);
			if (pawn2 == null)
			{
				//ModLog.Message("patches_lovin::JobGiver_Mate " + xxx.get_pawnname(pawn) + ", no valid partner found");
				return;
			}
			//__result = JobMaker.MakeJob(xxx.animalBreed, pawn2);
			__result = JobMaker.MakeJob(JobDefOf.Mate, pawn2);
			//ModLog.Message("patches_lovin::JobGiver_Mate " + xxx.get_pawnname(pawn) + ", female " + xxx.get_pawnname(pawn2) + ", job " + __result);
		}
	}

	//check if female can be impregnated for animal mating (also check rjw pregnancies)
	[HarmonyPatch(typeof(PawnUtility), "FertileMateTarget")]
	internal static class PATCH_PawnUtility_FertileMateTarget
	{
		[HarmonyPrefix]
		public static bool Prefix(Pawn male, Pawn female, ref bool __state)
		{
			__state = female.IsPregnant();
			//Log.Message("Prefix FertileMateTarget is vanilla/rjw pregnant: " + __state);
			return true;
		}

		[HarmonyPostfix]
		public static bool Postfix(bool __result, ref bool __state)
		{
			if (__result)
			{
				//Log.Message("Postfix FertileMateTarget is fertile and not vanilla pregnant: " + __result);
				if (__state)
				{
					//Log.Message("Postfix FertileMateTarget is fertile and rjw pregnant: " + __state);
					__result = false;
				}
			}
			return __result;
		}
	}

	//Suboptions when starting rjw sex through workgiver
	//[HarmonyPatch(typeof(FloatMenuOption), "Chosen")]
	//internal static class PATCH_test
	//{
	//	[HarmonyPostfix]
	//	public static void Postfix(FloatMenuOption __instance)
	//	{
	//		try
	//		{
	//			if (Find.Selector.NumSelected == 1) //&& (Find.Selector.SingleSelectedThing as Pawn).IsDesignatedHero()
	//			{
	//				//TODO: check if rjw jobdriver,
	//				//Insert another menu or 2 that will modify initiator sex jobdriver to
	//				//use selected parts - oral/anal/vaginal/etc
	//				//use selectable sex action - give/receive?
	//				//use selectable sex action - fuck/fisting?
	//				Log.Message("---");
	//				ModLog.Message("FloatMenuOption::Chosen " + __instance);
	//				ModLog.Message("FloatMenuOption::Chosen " + __instance.Label);
	//				ModLog.Message("FloatMenuOption::Chosen " + __instance.action.Target);
	//				ModLog.Message("FloatMenuOption::Chosen initiator - " + Find.Selector.SingleSelectedThing);
	//				ModLog.Message("FloatMenuOption::Chosen target - " + __instance.revalidateClickTarget);
	//				ModLog.Message("FloatMenuOption::Chosen initiator - " + (Find.Selector.SingleSelectedThing as Pawn).CurJob);
	//				Log.Message("---");
	//			}
	//		}
	//		catch
	//		{ }
	//	}
	//}

	//JobDriver_DoLovinCasual from RomanceDiversified should have handled whether pawns can do casual lovin,
	//so I don't bothered to do a check here, unless some bugs occur due to this.
	//this prob needs a patch like above, but who cares

	// Call xxx.aftersex after pawns have finished lovin'
	// You might be thinking, "wouldn't it be easier to add this code as a finish condition to JobDriver_Lovin in the patch above?" I tried that
	// at first but it didn't work because the finish condition is always called regardless of how the job ends (i.e. if it's interrupted or not)
	// and there's no way to find out from within the finish condition how the job ended. I want to make sure not apply the effects of sex if the
	// job was interrupted somehow.
	[HarmonyPatch(typeof(JobDriver), "Cleanup")]
	internal static class PATCH_JobDriver_Loving_Cleanup
	{
		//RomanceDiversified lovin
		//not very good solution, some other mod can have same named jobdrivers, but w/e
		private readonly static Type JobDriverDoLovinCasual = AccessTools.TypeByName("JobDriver_DoLovinCasual");

		//Nightmare Incarnation
		//not very good solution, some other mod can have same named jobdrivers, but w/e
		private readonly static Type JobDriverNIManaSqueeze = AccessTools.TypeByName("JobDriver_NIManaSqueeze");

		//vanilla lovin
		private readonly static Type JobDriverLovin = typeof(JobDriver_Lovin);

		//vanilla mate
		private readonly static Type JobDriverMate = typeof(JobDriver_Mate);

		[HarmonyPrefix]
		private static bool on_cleanup_driver(JobDriver __instance, JobCondition condition)
		{
			if (__instance == null)
				return true;

			if (condition == JobCondition.Succeeded)
			{
				Pawn pawn = __instance.pawn;
				Pawn partner = null;

				//ModLog.Message("patches_lovin::on_cleanup_driver" + xxx.get_pawnname(pawn));

				var any_ins = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

				//[RF] Rational Romance [1.0] loving
				if (xxx.RomanceDiversifiedIsActive && __instance.GetType() == JobDriverDoLovinCasual)
				{
					// not sure RR can even cause pregnancies but w/e
					partner = (Pawn)(__instance.GetType().GetProperty("Partner", any_ins).GetValue(__instance, null));
					ModLog.Message("patches_lovin::on_cleanup_driver RomanceDiversified/RationalRomance:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
				}
				//Nightmare Incarnation
				else if (xxx.NightmareIncarnationIsActive && __instance.GetType() == JobDriverNIManaSqueeze)
				{
					partner = (Pawn)(__instance.GetType().GetProperty("Victim", any_ins).GetValue(__instance, null));
					ModLog.Message("patches_lovin::on_cleanup_driver Nightmare Incarnation:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
				}
				//Vanilla loving
				else if (__instance.GetType() == JobDriverLovin)
				{
					partner = (Pawn)(__instance.GetType().GetProperty("Partner", any_ins).GetValue(__instance, null));
					//CnP loving
					if (xxx.RimWorldChildrenIsActive && RJWPregnancySettings.humanlike_pregnancy_enabled && xxx.is_human(pawn) && xxx.is_human(partner))
					{
						ModLog.Message("patches_lovin:: RimWorldChildren/ChildrenAndPregnancy pregnancy:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
						PregnancyHelper.cleanup_CnP(pawn);
						PregnancyHelper.cleanup_CnP(partner);
					}
					else
						ModLog.Message("patches_lovin:: JobDriverLovin pregnancy:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
				}
				//Vanilla mating
				else if (__instance.GetType() == JobDriverMate)
				{
					partner = (Pawn)(__instance.GetType().GetProperty("Female", any_ins).GetValue(__instance, null));
					ModLog.Message("patches_lovin:: JobDriverMate pregnancy:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
				}
				else
					return true;

				// TODO: Doing TryUseCondom here is a bit weird... it should happen before.
				//var usedCondom = CondomUtility.TryUseCondom(pawn) || CondomUtility.TryUseCondom(partner);

				//vanilla will probably be fucked up for non humanlikes... but only humanlikes do loving, right? right?
				//if rjw pregnancy enabled, remove vanilla for:
				//human-human
				//animal-animal
				//bestiality
				//always remove when someone is insect or mech
				if (RJWPregnancySettings.humanlike_pregnancy_enabled && xxx.is_human(pawn) && xxx.is_human(partner)
					|| RJWPregnancySettings.animal_pregnancy_enabled && xxx.is_animal(pawn) && xxx.is_animal(partner)
					|| (RJWPregnancySettings.bestial_pregnancy_enabled && xxx.is_human(pawn) && xxx.is_animal(partner)
					|| RJWPregnancySettings.bestial_pregnancy_enabled && xxx.is_animal(pawn) && xxx.is_human(partner))
					|| xxx.is_insect(pawn) || xxx.is_insect(partner) || xxx.is_mechanoid(pawn) || xxx.is_mechanoid(partner)
					)
				{
					ModLog.Message("patches_lovin::on_cleanup_driver vanilla pregnancy:" + xxx.get_pawnname(pawn) + "+" + xxx.get_pawnname(partner));
					PregnancyHelper.cleanup_vanilla(pawn);
					PregnancyHelper.cleanup_vanilla(partner);
				}

				SexProps nonRJWsexI = SexUtility.SelectSextype(pawn, partner, false, false);
				var interaction = Modules.Interactions.Helpers.InteractionHelper.GetWithExtension(nonRJWsexI.dictionaryKey);
				nonRJWsexI.isRevese = interaction.HasInteractionTag(InteractionTag.Reverse);
				nonRJWsexI.isCoreLovin = true;

				SexUtility.ProcessSex(nonRJWsexI); //TODO: fix me someday
				SexUtility.SatisfyPersonal(nonRJWsexI);
				SexUtility.SatisfyPersonal(nonRJWsexI.GetForPartner());
			}
			return true;
		}
	}
}


code:
using HarmonyLib;
using RimWorld;
using Verse;
using Verse.AI;

namespace rjw
{
	/// <summary>
	/// disable meditation effects for nymphs (i.e meditation on throne)
	/// </summary>
	[HarmonyPatch(typeof(JobDriver_Meditate), "MeditationTick")]
	internal static class PATCH_JobDriver_Meditate_MeditationTick
	{
		[HarmonyPrefix]
		private static bool Disable_For_Nymph(JobDriver_Meditate __instance)
		{
			Pawn pawn = __instance.pawn;

			if (xxx.is_nympho(pawn))
			{
				//ModLog.Message("JobGiver_Meditate::MeditationTick for nymph " + xxx.get_pawnname(pawn) + " __instance " + __instance);
				CompProperties_MeditationFocus t0 = __instance.Focus.Thing?.def?.comps?.Find(x => x is CompProperties_MeditationFocus) as CompProperties_MeditationFocus;
				if (t0 != null)
					if (t0.focusTypes.Contains(xxx.SexMeditationFocus))
						return true;

				return false;
			}

			//ModLog.Message("JobGiver_Meditate::MeditationTick pass");
			return true;
		}
	}

	[HarmonyPatch(typeof(JobGiver_Meditate), "TryGiveJob")]
	internal static class PATCH_JobGiver_Meditate_TryGiveJob
	{
		[HarmonyPostfix]
		public static void Disable_For_Nymph(ref Job __result, Pawn pawn)
		{
			if (__result != null)
				if (xxx.is_nympho(pawn))
				{
					//ModLog.Message("JobGiver_Meditate::TryGiveJob for nymph " + xxx.get_pawnname(pawn) + " job " + __result);
					CompProperties_MeditationFocus t1 = __result.targetA.Thing?.def.comps.Find(x => x is CompProperties_MeditationFocus) as CompProperties_MeditationFocus;
					CompProperties_MeditationFocus t2 = __result.targetB.Thing?.def.comps.Find(x => x is CompProperties_MeditationFocus) as CompProperties_MeditationFocus;
					CompProperties_MeditationFocus t3 = __result.targetC.Thing?.def.comps.Find(x => x is CompProperties_MeditationFocus) as CompProperties_MeditationFocus;
					//ModLog.Message("JobGiver_Meditate::TryGiveJob targetA " + t1);
					//ModLog.Message("JobGiver_Meditate::TryGiveJob targetB " + t2);
					//ModLog.Message("JobGiver_Meditate::TryGiveJob targetC " + t3);
					if (t1 != null)
						if (t1.focusTypes.Contains(xxx.SexMeditationFocus))
							return;
					if (t2 != null)
						if (t2.focusTypes.Contains(xxx.SexMeditationFocus))
							return;
					if (t3 != null)
						if (t3.focusTypes.Contains(xxx.SexMeditationFocus))
							return;

					//ModLog.Message("JobGiver_Meditate::Disable_For_Nymph no valid targets fail job");
					__result = null;
					//ModLog.Message("JobGiver_Meditate::Disable_For_Nymph " + xxx.get_pawnname(pawn) + " job " + __result);
				}
		}
	}
}


code:
namespace rjw
{
	/*
	[HarmonyPatch(typeof(Pawn_NeedsTracker))]
	[HarmonyPatch("ShouldHaveNeed")]
	static class patches_need
	{
		[HarmonyPostfix]
		static void on_postfix(Pawn_NeedsTracker __instance, NeedDef nd, ref bool __result){
			Pawn p=(Pawn)(typeof(Pawn_NeedsTracker).GetField("pawn", xxx.ins_public_or_no).GetValue(__instance));
			__result = __result && (nd.defName != "Sex" || (p!=null && p.Map!=null));
		}
	}
	*/
}


code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using HarmonyLib;
using Multiplayer.API;
using UnityEngine;
using Verse;
using RimWorld;
using rjw.Modules.Testing;

using Seeded = rjw.Modules.Rand.Seeded;

namespace rjw
{
	[HarmonyPatch(typeof(Hediff_Pregnant), "DoBirthSpawn")]
	internal static class PATCH_Hediff_Pregnant_DoBirthSpawn
	{
		/// <summary>
		/// This one overrides vanilla pregnancy hediff behavior.
		/// 0 - try to find suitable father for debug pregnancy
		/// 1st part if character pregnant and rjw pregnancies enabled - creates rjw pregnancy and instantly births it instead of vanilla
		/// 2nd part if character pregnant with rjw pregnancy - birth it
		/// 3rd part - debug - create rjw/vanila pregnancy and birth it
		/// </summary>
		/// <param name="mother"></param>
		/// <param name="father"></param>
		/// <returns></returns>
		[HarmonyPrefix]
		[SyncMethod]
		private static bool on_begin_DoBirthSpawn(ref Pawn mother, ref Pawn father)
		{
			//--Log.Message("patches_pregnancy::PATCH_Hediff_Pregnant::DoBirthSpawn() called");

			if (mother == null)
			{
				ModLog.Error("Hediff_Pregnant::DoBirthSpawn() - no mother defined -> exit");
				return false;
			}

			//CompEggLayer compEggLayer = mother.TryGetComp<CompEggLayer>();
			//if (compEggLayer != null)
			//{
			//	ProcessVanillaEggPregnancy(mother, father);
			//	return false;
			//}

			//vanilla debug?
			if (mother.gender == Gender.Male)
			{
				ModLog.Error("Hediff_Pregnant::DoBirthSpawn() - mother is male -> exit");
				return false;
			}

			// get a reference to the hediff we are applying
			//do birth for vanilla pregnancy Hediff
			//if using rjw pregnancies - add RJW pregnancy Hediff and birth it instead
			Hediff_Pregnant self = (Hediff_Pregnant)mother.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.Pregnant);
			if (self != null)
			{
				return ProcessVanillaPregnancy(self, mother, father);
			}

			// do birth for existing RJW pregnancies
			if (ProcessRJWPregnancy(mother, father))
			{
				return false;
			}

			return ProcessDebugPregnancy(mother, father);
		}

		private static bool ProcessVanillaEggPregnancy(Pawn mother, Pawn father)
		{
			CompEggLayer compEggLayer = mother.TryGetComp<CompEggLayer>();
			if (compEggLayer != null)
			{
				if (!compEggLayer.FullyFertilized)
				{
					if (father == null)
						compEggLayer.Fertilize(mother);
					else
						compEggLayer.Fertilize(father);

					compEggLayer.ProduceEgg();
				}
			}

			CompHatcher compHatcher = mother.TryGetComp<CompHatcher>();
			if (compHatcher != null)
			{
				compHatcher.Hatch();
			}

			ModLog.Message("patches_pregnancy::PATCH_Hediff_Pregnant::DoBirthSpawn():ProcessVanillaEggPregnancy birthing:" + xxx.get_pawnname(mother));
			return true;
		}

		private static bool ProcessVanillaPregnancy(Hediff_Pregnant pregnancy, Pawn mother, Pawn father)
		{
			void CreateAndBirth<T>() where T : Hediff_BasePregnancy
			{
				T hediff = Hediff_BasePregnancy.Create<T>(mother, father);
				hediff.GiveBirth();
				if (pregnancy != null)
					mother.health.RemoveHediff(pregnancy);
			}

			if (father == null)
			{
				father = Hediff_BasePregnancy.Trytogetfather(ref mother);
			}

			ModLog.Message("patches_pregnancy::PATCH_Hediff_Pregnant::DoBirthSpawn():Vanilla_pregnancy birthing:" + xxx.get_pawnname(mother));
			if (RJWPregnancySettings.animal_pregnancy_enabled && ((father == null || xxx.is_animal(father)) && xxx.is_animal(mother)))
			{
				//RJW Bestial pregnancy animal-animal
				ModLog.Message(" override as Bestial birthing(animal-animal): Father-" + xxx.get_pawnname(father) + " Mother-" + xxx.get_pawnname(mother));
				CreateAndBirth<Hediff_BestialPregnancy>();
				return false;
			}
			else if (RJWPregnancySettings.bestial_pregnancy_enabled && ((xxx.is_animal(father) && xxx.is_human(mother)) || (xxx.is_human(father) && xxx.is_animal(mother))))
			{
				//RJW Bestial pregnancy human-animal
				ModLog.Message(" override as Bestial birthing(human-animal): Father-" + xxx.get_pawnname(father) + " Mother-" + xxx.get_pawnname(mother));
				CreateAndBirth<Hediff_BestialPregnancy>();
				return false;
			}
			else if (RJWPregnancySettings.humanlike_pregnancy_enabled && (xxx.is_human(father) && xxx.is_human(mother)))
			{
				//RJW Humanlike pregnancy
				ModLog.Message(" override as Humanlike birthing: Father-" + xxx.get_pawnname(father) + " Mother-" + xxx.get_pawnname(mother));
				CreateAndBirth<Hediff_HumanlikePregnancy>();
				return false;
			}
			else
			{
				ModLog.Warning("Hediff_Pregnant::DoBirthSpawn() - checks failed, vanilla pregnancy birth");
				ModLog.Warning("Hediff_Pregnant::DoBirthSpawn(): Father-" + xxx.get_pawnname(father) + " Mother-" + xxx.get_pawnname(mother));
				//vanilla pregnancy code, no effects on rjw

				return true;
			}
		}

		private static bool ProcessRJWPregnancy(Pawn mother, Pawn father)
		{
			var p = PregnancyHelper.GetPregnancies(mother);
			if (p.NullOrEmpty())
			{
				return false;
			}

			var birth = false;
			foreach (var x in p)
			{
				if (x is Hediff_BasePregnancy)
				{
					var preg = x as Hediff_BasePregnancy;
					ModLog.Message($"patches_pregnancy::{preg.GetType().Name}::DoBirthSpawn() birthing:" + xxx.get_pawnname(mother));
					preg.GiveBirth();
					birth = true;
				}
			}

			return birth;
		}

		private static bool ProcessDebugPregnancy(Pawn mother, Pawn father)
		{
			void CreateAndBirth<T>() where T : Hediff_BasePregnancy
			{
				T hediff = Hediff_BasePregnancy.Create<T>(mother, father);
				hediff.GiveBirth();
			}
			//CreateAndBirth<Hediff_HumanlikePregnancy>();
			//CreateAndBirth<Hediff_BestialPregnancy>();
			//CreateAndBirth<Hediff_MechanoidPregnancy>();
			//return false;

			//debug, add RJW pregnancy and birth it
			ModLog.Message("patches_pregnancy::PATCH_Hediff_Pregnant::DoBirthSpawn():Debug_pregnancy birthing:" + xxx.get_pawnname(mother));
			if (father == null)
			{
				father = Hediff_BasePregnancy.Trytogetfather(ref mother);

				if (RJWPregnancySettings.bestial_pregnancy_enabled && ((xxx.is_animal(father) || xxx.is_animal(mother)))
					|| (xxx.is_animal(mother) && RJWPregnancySettings.animal_pregnancy_enabled))
				{
					//RJW Bestial pregnancy
					ModLog.Message(" override as Bestial birthing, mother: " + xxx.get_pawnname(mother));
					CreateAndBirth<Hediff_BestialPregnancy>();
				}
				else if (RJWPregnancySettings.humanlike_pregnancy_enabled && ((father == null || xxx.is_human(father)) && xxx.is_human(mother)))
				{
					//RJW Humanlike pregnancy
					ModLog.Message(" override as Humanlike birthing, mother: " + xxx.get_pawnname(mother));
					CreateAndBirth<Hediff_HumanlikePregnancy>();
				}
				else
				{
					ModLog.Warning("Hediff_Pregnant::DoBirthSpawn() - debug vanilla pregnancy birth");
					return true;
				}
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(Hediff_Pregnant), "Tick")]
	class PATCH_Hediff_Pregnant_Tick
	{
		[HarmonyPrefix]
		static bool abort_on_missing_genitals(Hediff_Pregnant __instance)
		{
			if (__instance.pawn.IsHashIntervalTick(1000))
			{
				if (!Genital_Helper.has_vagina(__instance.pawn))
				{
					__instance.pawn.health.RemoveHediff(__instance);
				}
			}
			return true;
		}
	}

	// Enables pregnancy approach for same-gender couples as long as they have the right genitals,
	// prevents the UI from bugging out if the first pawn is genderless, and ensures that the
	// "Pawns are sterile" report is not misapplied in case of mpreg.
	[HarmonyPatch(typeof(PregnancyUtility), nameof(PregnancyUtility.CanEverProduceChild))]
	class PregnancyUtility_CanEverProduceChild
	{
		static Type thisType = typeof(PregnancyUtility_CanEverProduceChild);

		static readonly MethodInfo SterileMethod =
			AccessTools.Method(typeof(Pawn), nameof(Pawn.Sterile));
		static readonly MethodInfo GetPregnancyHediffMethod =
			AccessTools.Method(typeof(PregnancyUtility), nameof(PregnancyUtility.GetPregnancyHediff));

		// TODO from Feb-2023: Uncomment the second version once `rjw-race-support` gets
		// its shit together and patches their gender check.
		static bool BypassGenderChecks => true;
		// static bool BypassGenderChecks =>
		// 	!ModsConfig.IsActive("erdelf.HumanoidAlienRaces") ||
		// 	!ModsConfig.IsActive("ASMR.RJW.RaceSupport");

		[HarmonyPrefix]
		static bool CheckPlumbing(Pawn first, Pawn second, ref AcceptanceReport __result)
		{
			if (first.Dead || second.Dead)
			{
				return true;
			}

			var plumbingReport = GetPlumbingReport(first, second);
			if (plumbingReport.Accepted)
			{
				return true;
			}

			__result = plumbingReport;
			return false;
		}

		[HarmonyTranspiler]
		static IEnumerable<CodeInstruction> SkipGenderCheckAndMakeSterilityCheckNotSexist(
			IEnumerable<CodeInstruction> instructionEnumberable, ILGenerator generator)
		{
			var instructions = instructionEnumberable.ToList();

			bool foundGenderCheck = false;
			bool foundSupposedLocalFemaleAssignment = false;
			bool foundFemaleSterilityCheck = false;
			bool foundMaleSterilityCheck = false;

			// Break this method up into blocks, either where a value is returned or where
			// we set a local variable.
			static bool findBlock(CodeInstruction il) => il.opcode == OpCodes.Ret || il.IsStloc();
			(var curIns, var nextIns) = instructions.SplitAfter(findBlock);

			while(curIns.Count > 0)
			{
				if (curIns.Any((il) => il.Is(OpCodes.Ldstr, "PawnsHaveSameGender")))
				{
					// Processing the same-gender check.

					// We want to bypass this check, unless the Alien Races mod is active.
					// RJW's compatibility mod can instead patch its `GenderReproductionCheck`
					// method to alter its behavior.
					if (!BypassGenderChecks)
					{
						foundGenderCheck = true;
						goto yieldOriginal;
					}

					// Due to a quirk in how the optimizer handles branches, we must insert our
					// bypass AFTER the conditional, otherwise the compiler just removes it.
					// Isn't it great when documentation doesn't mention stuff like this?
					(var beforeBr, var afterBr) = curIns.SplitAfter((il) => il.Branches(out _));

					// Verify that we found the branch.
					if (afterBr.Count is 0) goto yieldOriginal;

					foreach (var il in beforeBr) yield return il;
					if (beforeBr.LastOrDefault() is { } br && br.Branches(out var bypassLabel))
					{
						foundGenderCheck = true;

						// Adds `&& false` after the conditional.
						yield return new(OpCodes.Ldc_I4_0);
						yield return new(OpCodes.Brfalse_S, bypassLabel);
					}
					foreach (var il in afterBr) yield return il;
					goto setupNextLoop;
				}
				else if (curIns.Any((il) => il.IsStlocOf(1)))
				{
					// Processing the initialization of `pawn2` into local #1:
					// Pawn pawn2 = (first.gender == Gender.Female) ? first : second;

					// This needs to be changed to just select the other pawn, the one that is
					// not the assumed father.  It is possible that Alien Races has already
					// patched this, so we'll need to take that into consideration.

					// Locate the branch instruction.
					(var beforeBr, var afterBr) = curIns.SplitAfter((il) => il.Branches(out _));

					// Verify that we found the branch.
					if (afterBr.Count is 0) goto yieldOriginal;
					if (beforeBr.LastOrDefault() is not { } br) goto yieldOriginal;
					if (!br.Branches(out var label)) goto yieldOriginal;

					foundSupposedLocalFemaleAssignment = true;

					// Rewrite to:
					// Pawn pawn2 = (first != pawn) ? first : second;

					// Make sure the labels are preserved.
					yield return curIns[0].Replace(new CodeInstruction(OpCodes.Ldarg_0));
					yield return new(OpCodes.Ldloc_0);
					yield return new(OpCodes.Bne_Un_S, label);
					// The remaining instructions handle the selection of the pawn, so we
					// can spit those out without changes.
					foreach (var il in afterBr) yield return il;
					goto setupNextLoop;
				}
				else if (curIns.Any((il) => il.IsStlocOf(6)))
				{
					// Processing the initialization of `flag5` into local #6:
					// bool flag5 = pawn2.Sterile(false) && PregnancyUtility.GetPregnancyHediff(pawn2) == null;

					// This needs to be changed to call `PregnancyHelper.GetPregnancy`.

					// Look for the call `pawn2.Sterile(false)`.
					(var callToSterile, var remainder) = curIns.CutMatchingSequence(
						(il) => il.opcode == OpCodes.Ldloc_1,
						(il) => il.opcode == OpCodes.Ldc_I4_0,
						(il) => il.Calls(SterileMethod),
						(il) => il.opcode == OpCodes.Brfalse_S
					);

					// Verify we found this sequence and abort if not.
					if (callToSterile.Count == 0) goto yieldOriginal;

					// Look for the call `PregnancyUtility.GetPregnancyHediff(pawn2)`.
					(var callToPregnancy, remainder) = remainder.CutMatchingSequence(
						(il) => il.opcode == OpCodes.Ldloc_1,
						(il) => il.Calls(GetPregnancyHediffMethod)
					);

					// Verify we found this sequence and abort if not.
					if (callToPregnancy.Count == 0) goto yieldOriginal;

					foundFemaleSterilityCheck = true;

					// Rewrite this to call `PregnancyHelper.GetPregnancy` instead.
					// We're keeping the call to `Sterile`.
					foreach (var il in callToSterile) yield return il;
					// Setup and call.
					yield return new(OpCodes.Ldloc_1);
					yield return CodeInstruction.Call(typeof(PregnancyHelper), nameof(PregnancyHelper.GetPregnancy));
					// The remaining instructions just check for `null`, so should be good.
					foreach (var il in remainder) yield return il;
					goto setupNextLoop;
				}
				else if (curIns.Any((il) => il.IsStlocOf(7)))
				{
					// Processing the initialization of `flag6` into local #7:
					// bool flag6 = pawn.Sterile(false);

					// We need to add a call to `PregnancyHelper.GetPregnancy` just like for
					// the female, since this pawn may actually be a futa or something.

					// Look for the call `pawn.Sterile(false)`.
					(var callToSterile, var remainder) = curIns.CutMatchingSequence(
						(il) => il.opcode == OpCodes.Ldloc_0,
						(il) => il.opcode == OpCodes.Ldc_I4_0,
						(il) => il.Calls(SterileMethod)
					);

					// Verify we found this sequence and abort if not.
					if (callToSterile.Count == 0) goto yieldOriginal;

					// There should only be 1 instruction left, which sets the variable.
					if (remainder.Count != 1) goto yieldOriginal;

					foundMaleSterilityCheck = true;

					// We need to setup a label pointing to the instruction that will set
					// `false` if the call to `pawn.Sterile(false)` returns false.
					var labelToFalse = generator.DefineLabel();
					var IL_SetToFalse = new CodeInstruction(OpCodes.Ldc_I4_0);
					IL_SetToFalse.labels.Add(labelToFalse);

					// We also need a label on the instruction that sets the variable.
					var labelToSet = generator.DefineLabel();
					remainder[0].labels.Add(labelToSet);

					foreach (var il in callToSterile) yield return il;
					// If the return value was false, skip to `IL_SetToFalse`.
					yield return new(OpCodes.Brfalse_S, labelToFalse);
					// Now, write `PregnancyHelper.GetPregnancy(pawn) == null`.
					yield return new(OpCodes.Ldloc_0);
					yield return CodeInstruction.Call(typeof(PregnancyHelper), nameof(PregnancyHelper.GetPregnancy));
					yield return new(OpCodes.Ldnull);
					yield return new(OpCodes.Ceq);
					// If it was `true`, skip over the next instruction so that is set to the variable.
					yield return new(OpCodes.Br_S, labelToSet);
					// Otherwise, we'll set `false`.
					yield return IL_SetToFalse;
					// The remaining instruction just sets the variable to whatever was last pushed
					// to the stack.
					foreach (var il in remainder) yield return il;
					goto setupNextLoop;
				}

			yieldOriginal:
				foreach (var il in curIns)
					yield return il;

			setupNextLoop:
				(curIns, nextIns) = nextIns.SplitAfter(findBlock);
			}

			if (!foundGenderCheck)
				ModLog.Error("Failed to patch PregnancyUtility.CanEverProduceChild: Could not find gender check");
			if (!foundSupposedLocalFemaleAssignment)
				ModLog.Error("Error when patching PregnancyUtility.CanEverProduceChild: Could not find assignment to local variable `pawn2`");
			if (!foundFemaleSterilityCheck)
				ModLog.Error("Error when patching PregnancyUtility.CanEverProduceChild: Could not find sterility check on local variable `pawn2`");
			if (!foundMaleSterilityCheck)
				ModLog.Error("Error when patching PregnancyUtility.CanEverProduceChild: Could not find sterility check on local variable `pawn`");
		}

		static AcceptanceReport GetPlumbingReport(Pawn first, Pawn second)
		{
			bool firstHasPenis = Genital_Helper.has_penis_fertile(first);
			bool firstHasVagina = Genital_Helper.has_vagina(first);

			if (!firstHasPenis && !firstHasVagina)
			{
				return "PawnLacksFunctionalGenitals".Translate(first.Named("PAWN")).Resolve();
			}

			bool secondHasPenis = Genital_Helper.has_penis_fertile(second);
			bool secondHasVagina = Genital_Helper.has_vagina(second);

			if (!secondHasPenis && !secondHasVagina)
			{
				return "PawnLacksFunctionalGenitals".Translate(second.Named("PAWN")).Resolve();
			}
			if ((firstHasPenis && secondHasVagina) || (firstHasVagina && secondHasPenis))
			{
				return true;
			}
			if (firstHasPenis && !secondHasVagina)
			{
				return "PawnLacksVagina".Translate(second.Named("PAWN")).Resolve();
			}
			if (firstHasVagina && !secondHasPenis)
			{
				return "PawnLacksFunctionalPenis".Translate(second.Named("PAWN")).Resolve();
			}
			return true;
		}

		/// <summary>
		/// <para>Tests various pairings to make sure that that the patch is operating
		/// correctly.  The results of this test may be affected by other mods,
		/// so keep that in mind.</para>
		/// <para>This doesn't go into too much depth, mostly just checking colonists
		/// and a few animals.  It does not currently test integration with Alien
		/// Races or anything.  RJW's Alien Races compatibility mod should provide
		/// its own auto-test for that.</para>
		/// </summary>
		[DebugOutput("RJW Auto-Tests", onlyWhenPlaying = true)]
		public static void TestCanEverProduceChild()
		{
			var logger = Modules.Shared.Logs.LogManager.GetLogger("TestCanEverProduceChild");
			var sb = new StringBuilder();
			var passedColor = GenColor.FromHex("66CC00");
			var failedColor = GenColor.FromHex("FF3300");

			var maleColonistRequest = new PawnGenerationRequest(
				kind: PawnKindDefOf.Colonist,
				fixedGender: Gender.Male,
				excludeBiologicalAgeRange: new(0f, 18f)
			).RequestDefaults();

			var femaleColonistRequest = new PawnGenerationRequest(
				kind: PawnKindDefOf.Colonist,
				fixedGender: Gender.Female,
				allowPregnant: false,
				excludeBiologicalAgeRange: new(0f, 18f)
			).RequestDefaults();

			var maleThrumboRequest = new PawnGenerationRequest(
				kind: PawnKindDefOf.Thrumbo,
				fixedGender: Gender.Male,
				excludeBiologicalAgeRange: new(0f, 8f)
			).RequestDefaults();

			var femaleThrumboRequest = new PawnGenerationRequest(
				kind: PawnKindDefOf.Thrumbo,
				fixedGender: Gender.Female,
				allowPregnant: false,
				excludeBiologicalAgeRange: new(0f, 8f)
			).RequestDefaults();

			// Checks regarding basic sex-parts.

			Trial("Male Colonist + Female Colonist", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				TryToReport(male, female, true);
			});

			Trial("Male Colonist + Male Colonist", () =>
			{
				var male1 = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var male2 = TestHelper.GenerateSeededPawn(maleColonistRequest);
				TryToReport(male1, male2, false);
			});

			Trial("Female Colonist + Female Colonist", () =>
			{
				var female1 = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				var female2 = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				TryToReport(female1, female2, false);
			});

			Trial("Futa Colonist + Female Colonist", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				if (TestHelper.MakeIntoFuta(male))
					TryToReport(male, female, true);
				else
				{
					var text = "Failed to Create Futa".Colorize(failedColor);
					sb.AppendLineTagged($"  {text}");
				}
			});

			Trial("Male Colonist + Futa Colonist", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				if (TestHelper.MakeIntoFuta(female))
					TryToReport(male, female, true);
				else
				{
					var text = "Failed to Create Futa".Colorize(failedColor);
					sb.AppendLineTagged($"  {text}");
				}
			});

			Trial("Futa Colonist + Futa Colonist", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				if (TestHelper.MakeIntoFuta(male) && TestHelper.MakeIntoFuta(female))
					TryToReport(male, female, true);
				else
				{
					var text = "Failed to Create Futa".Colorize(failedColor);
					sb.AppendLineTagged($"  {text}");
				}
			});

			// Tests regarding pregnancy.

			Trial("Male Colonist + Pregnant Female Colonist (Vanilla)", () =>
			{
				if (!ModsConfig.BiotechActive)
				{
					sb.AppendLine("  Biotech Not Active");
					return;
				}

				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				if (VanillaHumanPregnancy(female, male) is { } hediff)
				{
					female.health.AddHediff(hediff);
					TryToReport(male, female, true);
				}
				else
				{
					var text = "Failed to Impregnate".Colorize(failedColor);
					sb.AppendLineTagged($"  {text}");
				}
			});

			Trial("Male Colonist + Pregnant Female Colonist (RJW)", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				PregnancyHelper.AddPregnancyHediff(female, male);
				TryToReport(male, female, true);
			});

			Trial("Pregnant Male Colonist + Female Colonist (Vanilla)", () =>
			{
				if (!ModsConfig.BiotechActive)
				{
					sb.AppendLine("  Biotech Not Active");
					return;
				}

				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				if (VanillaHumanPregnancy(male, female) is { } hediff)
				{
					male.health.AddHediff(hediff);
					TryToReport(male, female, true);
				}
				else
				{
					var text = "Failed to Impregnate".Colorize(failedColor);
					sb.AppendLineTagged($"  {text}");
				}
			});

			Trial("Pregnant Male Colonist + Female Colonist (RJW)", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				PregnancyHelper.AddPregnancyHediff(male, female);
				TryToReport(male, female, true);
			});

			// Tests regarding artificial genitalia and sterilization.

			Trial("Sterilized Male Colonist + Female Colonist", () =>
			{
				if (!ModsConfig.BiotechActive)
				{
					sb.AppendLine("  Biotech Not Active");
					return;
				}

				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				male.health.AddHediff(HediffDefOf.Sterilized);
				TryToReport(male, female, false);
			});

			Trial("Artificially Male Colonist + Female Colonist", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				if (TestHelper.GiveArtificialGenitals(male))
					TryToReport(male, female, false);
				else
				{
					var text = "Failed to Render Artifical".Colorize(failedColor);
					sb.AppendLineTagged($"  {text}");
				}
			});

			Trial("Male Colonist + Sterilized Female Colonist", () =>
			{
				if (!ModsConfig.BiotechActive)
				{
					sb.AppendLine("  Biotech Not Active");
					return;
				}

				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				female.health.AddHediff(HediffDefOf.Sterilized);
				TryToReport(male, female, false);
			});

			Trial("Male Colonist + Artificially Female Colonist", () =>
			{
				// The hydraulic vagina is still somehow fertile, btw.
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				if (TestHelper.GiveArtificialGenitals(female))
					TryToReport(male, female, true);
				else
				{
					var text = "Failed to Render Artifical".Colorize(failedColor);
					sb.AppendLineTagged($"  {text}");
				}
			});

			// Checks to verify the gender checks were disabled properly.

			Trial("Male Colonist + Cuntboy Colonist", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				female.gender = Gender.Male;
				TryToReport(male, female, true);
			});

			Trial("Dickgirl Colonist + Female Colonist", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				male.gender = Gender.Female;
				TryToReport(male, female, true);
			});

			// Tests versus animals.

			Trial("Male Thrumbo + Female Thrumbo", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleThrumboRequest);
				var female = TestHelper.GenerateSeededPawn(femaleThrumboRequest);
				TryToReport(male, female, true);
			});

			Trial("Male Thrumbo + Female Colonist", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleThrumboRequest);
				var female = TestHelper.GenerateSeededPawn(femaleColonistRequest);
				TryToReport(male, female, true);
			});

			Trial("Male Colonist + Female Thrumbo", () =>
			{
				var male = TestHelper.GenerateSeededPawn(maleColonistRequest);
				var female = TestHelper.GenerateSeededPawn(femaleThrumboRequest);
				TryToReport(male, female, true);
			});

			Find.WindowStack.Add(new Dialog_MessageBox(sb.ToString().Trim()));

			void Trial(string title, Action action)
			{
				try
				{
					sb.AppendLine(title);
					action();
				}
				catch (Exception ex)
				{
					var result = "Exception".Colorize(failedColor);
					sb.AppendLineTagged($"  {result} (see console logs)");
					logger.Error("Auto-test exception.", ex);
				}
				finally
				{
					sb.AppendLine();
				}
			}

			// Tries to give the `mother` a human pregnancy.
			Hediff_Pregnant VanillaHumanPregnancy(Pawn mother, Pawn father)
			{
				using var _seeded = Seeded.With(mother);
				var hediff = (Hediff_Pregnant)HediffMaker.MakeHediff(HediffDefOf.PregnantHuman, mother);
				hediff.Severity = 0.1f;
				var inheritedGeneSet = PregnancyUtility.GetInheritedGeneSet(father, mother, out var success);
				if (success)
				{
					hediff.SetParents(null, father, inheritedGeneSet);
					return hediff;
				}
				return null;
			}

			// Try the two pawns in both argument positions.
			void TryToReport(Pawn pawn1, Pawn pawn2, bool expectAccepted)
			{
				var text = expectAccepted ? "Accepted" : "Rejected";
				sb.AppendLine($"  Expecting: {text}");
				var result1 = PregnancyUtility.CanEverProduceChild(pawn1, pawn2);
				sb.AppendLine("  Given Order");
				sb.AppendLineTagged($"    Status: {ReportToStatus(result1, expectAccepted)}");
				sb.AppendLineTagged($"    Reason: {ReportToReason(result1)}");
				var result2 = PregnancyUtility.CanEverProduceChild(pawn2, pawn1);
				sb.AppendLine("  Reversed Order");
				sb.AppendLineTagged($"    Status: {ReportToStatus(result2, expectAccepted)}");
				sb.AppendLineTagged($"    Reason: {ReportToReason(result2)}");
			}

			string ReportToStatus(AcceptanceReport report, bool expectAccepted) =>
				(report.Accepted, expectAccepted) switch
				{
					(true, true) or (false, false) => "Passed".Colorize(passedColor),
					_ => "Failed".Colorize(failedColor)
				};

			string ReportToReason(AcceptanceReport report) =>
				report.Reason.NullOrEmpty() ? "(None)" : report.Reason;
		}
	}

	[HarmonyPatch(typeof(PregnancyUtility), "RandomLastName")]
	static class Patch_PregnancyUtility_RandomLastName
	{
		public static bool Prefix(ref Pawn geneticMother, ref Pawn birthingMother, ref Pawn father)
		{
			if (geneticMother != null)
				if (geneticMother.Name == null || !xxx.is_human(geneticMother))
				{
					geneticMother = null;
				}
			if (father != null)
				if (father.Name == null || !xxx.is_human(father))
				{
					father = null;
				}
			if (birthingMother != null)
				if (birthingMother.Name == null || !xxx.is_human(birthingMother))
				{
					birthingMother = null;
				}
			return true;
		}
	}

	// Fixes CompEggLayer and mating for humanlikes.
	// Note that this involves skipping over a check for the Biotech DLC, but as of build 1.4.3534 this doesn't unlock
	// any Biotech-only features or anything like that.
	[HarmonyPatch(typeof(Pawn), nameof(Pawn.Sterile))]
	class Pawn_Sterile
	{
		[HarmonyTranspiler]
		static IEnumerable<CodeInstruction> NotOwningBiotechWillNotMakeYouSterileButModdingProbablyWill(
			IEnumerable<CodeInstruction> instructions)
		{
			PropertyInfo biotechActive = AccessTools.DeclaredProperty(typeof(ModsConfig), nameof(ModsConfig.BiotechActive));
			bool foundBiotechCheck = false;

			foreach (var instruction in instructions)
			{
				// if (ModsConfig.BiotechActive) ...
				// => if (true) ...
				if (instruction.Calls(biotechActive.GetMethod))
				{
					yield return new CodeInstruction(OpCodes.Ldc_I4_1);
					foundBiotechCheck = true;
					continue;
				}
				yield return instruction;
			}

			if (!foundBiotechCheck)
			{
				ModLog.Error("Failed to patch Pawn.Sterile: Could not find `ModsConfig.BiotechActive`");
			}
		}
	}

	// Make the game use RJW's fertility capacity in vanilla pregnancy chance calculations
	[HarmonyPatch]
	class Various_GetStatValue
	{
		static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(PregnancyUtility), nameof(PregnancyUtility.CanEverProduceChild));
			yield return AccessTools.Method(typeof(PregnancyUtility), nameof(PregnancyUtility.PregnancyChanceForPawn));
			yield return AccessTools.Method(typeof(Pawn), nameof(Pawn.Sterile));
		}

		[HarmonyTranspiler]
		static IEnumerable<CodeInstruction> UseRjwFertilityInstead(IEnumerable<CodeInstruction> instructionEnumerable, MethodBase original)
		{
			bool foundFertilityStatDefLoad = false;
			FieldInfo statDefOfFertility = AccessTools.DeclaredField(typeof(StatDefOf), nameof(StatDefOf.Fertility));

			var instructions = instructionEnumerable.ToList();
			for (int i = 0; i < instructions.Count; i++)
			{
				// pawn.GetStatValue(StatDefOf.Fertility)
				// => pawn.health.capacities.GetLevel(xxx.reproduction)
				if (instructions[i].LoadsField(statDefOfFertility) && i + 3 < instructions.Count)
				{
					foundFertilityStatDefLoad = true;
					yield return CodeInstruction.LoadField(typeof(Pawn), nameof(Pawn.health)).WithLabels(instructions[i].ExtractLabels());
					yield return CodeInstruction.LoadField(typeof(Pawn_HealthTracker), nameof(Pawn_HealthTracker.capacities));
					yield return CodeInstruction.LoadField(typeof(xxx), nameof(xxx.reproduction));
					yield return CodeInstruction.Call(typeof(PawnCapacitiesHandler), nameof(PawnCapacitiesHandler.GetLevel));

					// Skip GetStatValue call
					i += 3;
					continue;
				}
				yield return instructions[i];
			}

			if (!foundFertilityStatDefLoad)
			{
				ModLog.Error($"Failed to patch {original.Name}: Could not find `pawn.GetStatValue(StatDefOf.Fertility)`");
			}
		}
	}

	// Mostly prevent pawns born from RJW pregnancies from having no name.
	[HarmonyPatch(typeof(PawnBioAndNameGenerator), nameof(PawnBioAndNameGenerator.GiveAppropriateBioAndNameTo))]
	class PawnBioAndNameGenerator_GiveAppropriateBioAndNameTo
	{
		[HarmonyPrefix]
		static void FixBabyNameIfNoBiotech(ref bool newborn)
		{
			newborn = newborn && RJWPregnancySettings.UseVanillaPregnancy;
		}
	}

	// Adjust the pregnancy approach tooltip to reflect the fact that it no longer affects the chance of pregnancy directly.
	[HarmonyPatch(typeof(PregnancyUtility), nameof(PregnancyUtility.GetDescription))]
	class PregnancyUtility_GetDescription
	{
		[HarmonyTranspiler]
		static IEnumerable<CodeInstruction> ModifyPregnancyApproachTooltip(IEnumerable<CodeInstruction> instructions)
		{
			foreach (var instruction in instructions)
			{
				if (instruction.LoadsConstant("PregnancyChance"))
				{
					yield return new CodeInstruction(OpCodes.Ldstr, "VaginalWeight");
				}
				else
				{
					yield return instruction;
				}
			}
		}
	}

	[HarmonyPatch(typeof(PawnColumnWorker_Pregnant), "GetIconFor")]
	public class PawnColumnWorker_Patch_Icon
	{
		public static void Postfix(Pawn pawn, ref Texture2D __result)
		{
			if (pawn.IsVisiblyPregnant()) __result = ContentFinder<Texture2D>.Get("UI/Icons/Animal/Pregnant", true);
		}
	}

	[HarmonyPatch(typeof(PawnColumnWorker_Pregnant), "GetTooltipText")]
	public class PawnColumnWorker_Patch_Tooltip
	{
		public static bool Prefix(Pawn pawn, ref string __result)
		{
			// Handles multi-pregnancy by getting the one nearest to birth.
			var pregHediff = PregnancyHelper.GetPregnancy(pawn);
			(var ticksCompleted, var ticksToBirth) = PregnancyHelper.GetProgressTicks(pregHediff);
			__result = "PregnantIconDesc".Translate(
				ticksCompleted.ToStringTicksToDays("F0"),
				ticksToBirth.ToStringTicksToDays("F0")
			);
			return false;
		}
	}

	[HarmonyPatch(typeof(TransferableUIUtility), "DoExtraIcons")]
	public class TransferableUIUtility_Patch_Icon
	{
		//private static readonly Texture2D PregnantIcon = ContentFinder<Texture2D>.Get("UI/Icons/Animal/Pregnant", true);
		public static void Postfix(Transferable trad, Rect rect, ref float curX, Texture2D ___PregnantIcon)
		{
			Pawn pawn = trad.AnyThing as Pawn;
			if (pawn?.health?.hediffSet != null && pawn.IsVisiblyPregnant())
			{
				Rect rect3 = new Rect(curX - 24f, (rect.height - 24f) / 2f, 24f, 24f);
				curX -= 24f;
				if (Mouse.IsOver(rect3))
				{
					TooltipHandler.TipRegion(rect3, PawnColumnWorker_Pregnant.GetTooltipText(pawn));
				}
				GUI.DrawTexture(rect3, ___PregnantIcon);
			}
		}
	}

	//[HarmonyPatch(typeof(AutoSlaughterManager))]
	//public class AutoSlaughterManager_AnimalsToSlaughter_rjw_preg
	//{
	//	public static void Postfix(AutoSlaughterManager __instance)
	//	{
	//		List<Pawn> __result = new List<Pawn>();
	//		var any_ins = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
	//		__result = (List<Pawn>)(__instance.GetType().GetField("AnimalsToSlaughter", any_ins).GetValue(__instance));
	//		//(__instance.GetType().GetField("AnimalsToSlaughter", any_ins).SetValue(__instance, newresult));

	//		//List<Pawn> __result = new List<Pawn>((List < Pawn > )typeof(AutoSlaughterManager).GetField("AnimalsToSlaughter", BindingFlags.Instance | BindingFlags.NonPublic));
	//		if (!__result.NullOrEmpty())
	//		{
	//			var newresult = __result;
	//			foreach (var pawn in __result)
	//			{
	//				if (pawn?.health?.hediffSet != null && pawn.IsPregnant(true))
	//				{
	//					if (__instance.configs.Any(x => x.allowSlaughterPregnant != true && x.animal == pawn.def))
	//					{
	//						newresult.Remove(pawn);
	//					}
	//				}

	//			}
	//			__result = newresult;
	//		}

	//		//return __result;
	//	}
	//}
}


code:
using System.Linq;
using Verse;

namespace rjw
{
	/// <summary>
	/// Patch all races into rjw parts recipes
	/// </summary>

	[StaticConstructorOnStartup]
	public static class HarmonyPatches
	{
		static HarmonyPatches()
		{
			//summons carpet bombing

			//inject races into rjw recipes
			foreach (RecipeDef x in	DefDatabase<RecipeDef>.AllDefsListForReading.Where(x => x.IsSurgery && (x.targetsBodyPart || !x.appliedOnFixedBodyParts.NullOrEmpty())))
			{
				if (x.appliedOnFixedBodyParts.Contains(xxx.genitalsDef)
					|| x.appliedOnFixedBodyParts.Contains(xxx.breastsDef)
					|| x.appliedOnFixedBodyParts.Contains(xxx.anusDef)
					|| x.modContentPack?.PackageId == "rim.job.world"
					|| x.modContentPack?.PackageId == "Safe.Job.World" //*sigh*
					//|| x.modContentPack?.PackageId == "Abraxas.RJW.RaceSupport" // for udders?
					)

					foreach (ThingDef thingDef in DefDatabase<ThingDef>.AllDefs.Where(thingDef =>
							thingDef.race != null && (
							thingDef.race.Humanlike ||
							thingDef.race.Animal
							)))
					{
						//filter out something, probably?
						//if (thingDef.race. == "Human")
						//	continue;

						if (!x.recipeUsers.Contains(thingDef))
						{
							x.recipeUsers.Add(item: thingDef);
							//Log.Message("recipe: " + x.defName + ", thing: " + thingDef.defName);

						}
					}
			}
		}
	}
}


code:
using HarmonyLib;
using RimWorld;
using System;
using Verse;

namespace rjw
{
	///<summary>
	///RJW Designators checks/update
	///update designators only for selected pawn, once, instead of every tick(60 times per sec)
	///</summary>
	[HarmonyPatch(typeof(Selector), "Select")]
	[StaticConstructorOnStartup]
	static class PawnSelect
	{
		[HarmonyPrefix]
		private static bool Update_Designators_Permissions(Selector __instance, ref object obj)
		{
			if (obj is Pawn)
			{
				//ModLog.Message("Selector patch");
				Pawn pawn = (Pawn)obj;
				//ModLog.Message("pawn: " + xxx.get_pawnname(pawn));
				pawn.UpdatePermissions();
			}
			return true;
		}
	}

	//[HarmonyPatch(typeof(Dialog_InfoCard), "Setup")]
	////[HarmonyPatch(typeof(Dialog_InfoCard), "Dialog_InfoCard", new Type[] {typeof(Def)})]
	//[StaticConstructorOnStartup]
	//static class Button
	//{
	//	[HarmonyPostfix]
	//	public static bool Postfix()
	//	{
	//		ModLog.Message("InfoCardButton");
	//		return true;
	//	}
	//}
}