Decompiled source of LynxModFixes v1.12.15

plugins/LynxModFixes.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Utils;
using UnityEngine;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace LynxModFixes;

[BepInPlugin("lynx.modfixes", "LynxModFixes", "1.12.15")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[SynchronizationMode(/*Could not decode attribute arguments.*/)]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "lynx.modfixes";

	public const string Version = "1.12.15";

	public const string TrueFlightGuid = "com.valheimcrewman.dynamicaimpoint";

	public const string KvistGuid = "com.ryan.greydwarfsorter";

	public const string PovGuid = "treextr.pathofvalheiman";

	public const string SmbGuid = "vapok.mods.shieldmebruh";

	public const string DrawersGuid = "com.rossdwest.itemdrawers";

	public const string GlidersGuid = "Yggdrah.ValheimGliders";

	public const string XPortalGuid = "vapok.mods.xportalnetworks";

	public const string SeneaLGuid = "seneaL.valheim.ui";

	public const string ForgeGuid = "wire.valheim.forgeofgoodtential";

	internal static ManualLogSource Log;

	internal static Harmony H;

	internal static Plugin Instance;

	internal static readonly Dictionary<MethodBase, int> Hits = new Dictionary<MethodBase, int>();

	private void Awake()
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		H = new Harmony("lynx.modfixes");
		Instance = this;
	}

	private void Start()
	{
		//IL_069c: Unknown result type (might be due to invalid IL or missing references)
		//IL_06a3: Expected O, but got Unknown
		//IL_0768: Unknown result type (might be due to invalid IL or missing references)
		//IL_076f: Expected O, but got Unknown
		//IL_0fc6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0ff4: Unknown result type (might be due to invalid IL or missing references)
		//IL_1022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0582: Unknown result type (might be due to invalid IL or missing references)
		//IL_0589: Expected O, but got Unknown
		//IL_05d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_05d7: Expected O, but got Unknown
		//IL_0e3c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0e43: Expected O, but got Unknown
		//IL_0e4e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0e58: Expected O, but got Unknown
		//IL_0e8a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0e90: Invalid comparison between Unknown and I4
		//IL_0ea1: Unknown result type (might be due to invalid IL or missing references)
		ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "RespectItemDrawers", true, "Kvist only puts an item in an ItemDrawers drawer assigned to that exact item; never into unassigned drawers or with non-stackables.");
		ConfigEntry<bool> val2 = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "HandPickedKilnsRespectCoalStock", true, "A hand-picked Kilns task stops once coal reaches the nest's coal stock setting.");
		ConfigEntry<bool> val3 = ((BaseUnityPlugin)this).Config.Bind<bool>("PathOfValheiman", "NoHuginOverlay", true, "Remove the blue screen overlay while Hugin's Flight is active.");
		ConfigEntry<bool> val4 = ((BaseUnityPlugin)this).Config.Bind<bool>("ShieldMeBruh", "OffhandWeapon", true, "Shift + middle-click marks a one-handed weapon as the off-hand item ShieldMeBruh re-equips.");
		KvistFixes.drawersFirst = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "DrawersFirst", true, "A drawer labelled for an item's category and assigned to that exact item is filled before any other chest of the category.").Value;
		KvistFixes.keepBonuses = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "KeepPovBonusesOutOfDrawers", true, "Kvist never puts meads, food or oils carrying PoV bonuses (brewing/cooking potency, aged mead) into an ItemDrawers drawer: a drawer keeps only the item type and count, so those bonuses would be lost. They go to a normal chest instead.").Value;
		Run("Kvist: drawers", val.Value, "com.ryan.greydwarfsorter", KvistFixes.ApplyDrawers);
		Run("Kvist: coal stock", val2.Value, "com.ryan.greydwarfsorter", KvistFixes.ApplyCoal);
		ConfigEntry<bool> val5 = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "SeedReserveCoversEverything", true, "Kvist's Seed reserve (K window number) also keeps that many of every food from being fed to animals, and keeps that many of anything he plants with from going into smelters, ovens, fermenters, drying racks or cooking. When feeding, he uses the food you have most of first.");
		Run("Kvist: reserves", val5.Value, "com.ryan.greydwarfsorter", KvistReserveFix.Apply);
		ConfigEntry<bool> val6 = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "RaidLoggedOnce", true, "Kvist writes 'Raid started' to the log every time the game re-confirms a raid (about 50 times a second for the whole raid). Log it once per raid instead.");
		Run("Kvist: raid log spam", val6.Value, "com.ryan.greydwarfsorter", KvistRaidLogFix.Apply);
		ConfigEntry<bool> val7 = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "NoWorldWideScans", true, "Every Kvist searched every object in the loaded world for snow piles every 10 s (and for doors when stuck). On a big base that search takes ~250 ms, so several Kvists froze the game every few seconds. Search only the game's networked objects instead, shared between all Kvists.");
		Run("Kvist: no world-wide scans", val7.Value, "com.ryan.greydwarfsorter", KvistScanFix.Apply);
		ConfigEntry<bool> val8 = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "FastResortCheck", true, "Every 10 s each Kvist checks all labelled chests for stacks to re-sort. For every part-stack it recounted that item in every nearby chest of the same label, item by item, so a base with many full chests froze for 300-500 ms per check. Each chest's contents are now counted once per check. Same result, same choices.");
		Run("Kvist: fast re-sort check", val8.Value, "com.ryan.greydwarfsorter", KvistResortFix.Apply);
		ConfigEntry<bool> val9 = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "FastPlantingSpots", true, "Whenever a farming Kvist picks his next planting spot, Kvist checked every free soil cell against every plant and crop loaded around the base, building each crop's name as a new string every time. On a big field that froze the game for 250-650 ms about every 12 s. Each spot is now checked only against the plants and crops near it, with the same distances. Same result, same spots.");
		Run("Kvist: fast planting spot check", val9.Value, "com.ryan.greydwarfsorter", KvistSpaceFix.Apply);
		ConfigEntry<bool> val10 = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "PathOfValheimanCategories", true, "Kvist sorts PoV items into their own categories (maps, Halls rooms, Runic Anvil stock = glyphs + alloys + azurite and divine azurite dust, Runic Chest = exactly the runes the chest holds, scrolls and other runes, essences and brands, skill gems, jewels and sigils), PoV ores and azurite into Ore & Coal, corrupted azurite dust into Metals & Parts, rune chisels into Tools. Added on top of categories.yaml; categories with the same id in the file win.");
		if (!val10.Value)
		{
			Log.LogInfo((object)"Kvist: PoV categories: disabled in config");
		}
		else if (!Chainloader.PluginInfos.ContainsKey("treextr.pathofvalheiman"))
		{
			Log.LogInfo((object)"Kvist: PoV categories: PoV not installed, skipped");
		}
		else
		{
			Run("Kvist: PoV categories", enabled: true, "com.ryan.greydwarfsorter", KvistPovCategories.Apply);
		}
		ConfigEntry<bool> val11 = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "FillRunicAnvilAndChest", true, "A Runic Anvil or Runic Chest labelled for Kvist gets its deliveries put into its PoV stock (what the anvil/chest window shows) instead of its plain inventory. Only items the anvil or chest accepts are delivered there.");
		if (!val11.Value)
		{
			Log.LogInfo((object)"Kvist: Runic Anvil/Chest stock: disabled in config");
		}
		else if (!Chainloader.PluginInfos.ContainsKey("treextr.pathofvalheiman"))
		{
			Log.LogInfo((object)"Kvist: Runic Anvil/Chest stock: PoV not installed, skipped");
		}
		else
		{
			Run("Kvist: Runic Anvil/Chest stock", enabled: true, "com.ryan.greydwarfsorter", KvistPovStores.Apply);
		}
		Run("PoV: Hugin overlay", val3.Value, "treextr.pathofvalheiman", HuginFix.Apply);
		Run("ShieldMeBruh: off-hand weapon", val4.Value, "vapok.mods.shieldmebruh", SmbFix.Apply);
		ConfigEntry<bool> val12 = ((BaseUnityPlugin)this).Config.Bind<bool>("ShieldMeBruh", "KeepOffhandDuringThrows", true, "A thrown weapon (PoV's Throw the Axe, spears) is briefly unequipped by the game; ShieldMeBruh takes that as sheathing and unequips your off-hand too. Skip that during throws so the off-hand weapon is never moved mid-throw.");
		Run("ShieldMeBruh: keep off-hand during throws", val12.Value, "vapok.mods.shieldmebruh", SmbThrowFix.Apply);
		ConfigEntry<bool> val13 = ((BaseUnityPlugin)this).Config.Bind<bool>("ShieldMeBruh", "MarkFollowsItem", true, "ShieldMeBruh remembers the off-hand item by its bag slot, so the mark falls off when another mod moves the item (PoV/SeneaL equipment rows, tool swaps). Keep the mark on the same item wherever it moves; middle-clicking it off still removes it.");
		Run("ShieldMeBruh: mark follows the item", val13.Value, "vapok.mods.shieldmebruh", SmbFollowFix.Apply);
		ConfigEntry<string> val14 = ((BaseUnityPlugin)this).Config.Bind<string>("ValheimGliders", "FrostResistantGliders", "Glider_BackPack_Ygg", "Gliders (prefab names, comma-separated) that get Frost: Resistant, which stops Freezing like the Wolf cape. Glider_BackPack_Ygg is the Wolf Crystal Glider Bag. Empty = off.");
		if (!Chainloader.PluginInfos.ContainsKey("Yggdrah.ValheimGliders"))
		{
			Log.LogInfo((object)"Gliders: wolf glider cold: mod not installed, skipped");
		}
		else if (string.IsNullOrWhiteSpace(val14.Value))
		{
			Log.LogInfo((object)"Gliders: wolf glider cold: disabled in config");
		}
		else
		{
			GliderFix.Setting = val14.Value.Trim();
			try
			{
				Harmony h = H;
				MethodInfo methodInfo = AccessTools.Method(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null);
				HarmonyMethod val15 = new HarmonyMethod(typeof(GliderFix), "Apply", (Type[])null);
				val15.priority = 0;
				val15 = val15;
				h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val15, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Harmony h2 = H;
				methodInfo = AccessTools.Method(typeof(Player), "OnSpawned", (Type[])null, (Type[])null);
				val15 = new HarmonyMethod(typeof(GliderFix), "Apply", (Type[])null);
				h2.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val15, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)"Gliders: wolf glider cold: hooked (items are changed once the game's item list loads)");
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Gliders: wolf glider cold: NOT applied (" + ex.Message + ")"));
			}
		}
		ConfigEntry<bool> val16 = ((BaseUnityPlugin)this).Config.Bind<bool>("Vanilla", "CartsRemovableWithHammer", true, "Carts can be dismantled with the hammer like a build piece (workbench nearby, cart must be empty), returning their materials.");
		if (!val16.Value)
		{
			Log.LogInfo((object)"Carts: hammer removal: disabled in config");
		}
		else
		{
			try
			{
				Harmony h3 = H;
				MethodInfo methodInfo = AccessTools.Method(typeof(Vagon), "Awake", (Type[])null, (Type[])null) ?? throw new Exception("Vagon.Awake missing");
				HarmonyMethod val15 = new HarmonyMethod(typeof(CartFix), "Removable", (Type[])null);
				h3.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val15, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)"Carts: hammer removal: applied");
			}
			catch (Exception ex2)
			{
				Log.LogWarning((object)("Carts: hammer removal: NOT applied (" + ex2.Message + ")"));
			}
		}
		ConfigEntry<bool> val17 = ((BaseUnityPlugin)this).Config.Bind<bool>("Vanilla", "EggsNeedNoRoof", true, "Eggs only need warmth to hatch, not a roof overhead.");
		if (!val17.Value)
		{
			Log.LogInfo((object)"Eggs: no roof needed: disabled in config");
		}
		else
		{
			try
			{
				Harmony h4 = H;
				MethodInfo methodInfo = AccessTools.Method(typeof(EggGrow), "Start", (Type[])null, (Type[])null) ?? throw new Exception("EggGrow.Start missing");
				HarmonyMethod val15 = new HarmonyMethod(typeof(EggFix), "NoRoof", (Type[])null);
				h4.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val15, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				Log.LogInfo((object)"Eggs: no roof needed: applied");
			}
			catch (Exception ex3)
			{
				Log.LogWarning((object)("Eggs: no roof needed: NOT applied (" + ex3.Message + ")"));
			}
		}
		ConfigEntry<bool> val18 = ((BaseUnityPlugin)this).Config.Bind<bool>("ItemDrawers", "IgnorePlacedItems", true, "Drawer auto-pickup leaves items that were placed as build pieces alone (e.g. ValheimCuisine's Keg Hammer food), instead of vacuuming them up as if they were dropped.");
		Run("ItemDrawers: ignore placed items", val18.Value, "com.rossdwest.itemdrawers", DrawerPickupFix.Apply);
		Run("PoV: lynx_removegraves command", enabled: true, "treextr.pathofvalheiman", GraveCommand.Apply);
		PickableCommand.Apply();
		SpikeProfiler.Apply();
		ConfigEntry<bool> val19 = ((BaseUnityPlugin)this).Config.Bind<bool>("PathOfValheiman", "PortalCrateWithStationlessPortals", true, "When a mod (e.g. BottleShips) removes the portals' build station, PoV's Portal crate still treats the workbench as their station: dismantled near a workbench = normal (e.g. the bottle back), away from one = packed crate with its tag.");
		Run("PoV: Portal crate for station-less portals", val19.Value, "treextr.pathofvalheiman", PortalCrateFix.Apply);
		ConfigEntry<bool> val20 = ((BaseUnityPlugin)this).Config.Bind<bool>("XPortalNetworks", "PortalCrateKeepsNetworkSettings", true, "A portal packed into PoV's Portal crate keeps its XPortalNetworks name, destination, colour, network owner and private flag when set back up, and portals that targeted it are relinked.");
		if (!val20.Value)
		{
			Log.LogInfo((object)"XPortalNetworks: Portal crate settings: disabled in config");
		}
		else if (!Chainloader.PluginInfos.ContainsKey("treextr.pathofvalheiman"))
		{
			Log.LogInfo((object)"XPortalNetworks: Portal crate settings: PoV not installed, skipped");
		}
		else
		{
			Run("XPortalNetworks: Portal crate settings", enabled: true, "vapok.mods.xportalnetworks", XPortalCrateFix.Apply);
		}
		ConfigEntry<bool> val21 = ((BaseUnityPlugin)this).Config.Bind<bool>("PathOfValheiman", "NoPunchAfterCratePlacement", true, "After setting up a portal or ship from a PoV crate, ignore attacks for half a second so the same click doesn't punch the new piece.");
		Run("PoV: no punch after crate placement", val21.Value, "treextr.pathofvalheiman", CratePunchFix.Apply);
		ConfigEntry<bool> val22 = ((BaseUnityPlugin)this).Config.Bind<bool>("Kvist", "PlantAnyBiomeWithAnySoil", true, "While the player whose game runs Kvist has PoV's Any Soil, Kvist plants crops and saplings outside their usual biome, and those plants are marked like hand-planted Any Soil plants.");
		if (!val22.Value)
		{
			Log.LogInfo((object)"Kvist: Any Soil planting: disabled in config");
		}
		else if (!Chainloader.PluginInfos.ContainsKey("treextr.pathofvalheiman"))
		{
			Log.LogInfo((object)"Kvist: Any Soil planting: PoV not installed, skipped");
		}
		else
		{
			Run("Kvist: Any Soil planting", enabled: true, "com.ryan.greydwarfsorter", AnySoilFix.Apply);
		}
		ConfigEntry<bool> val23 = ((BaseUnityPlugin)this).Config.Bind<bool>("PathOfValheiman", "TreasureMapPinsChest", true, "Reading a PoV treasure map also puts a pin on your map at its buried chest, instead of leaving you to match the scrap's coastline by eye.");
		Run("PoV: treasure map pins", val23.Value, "treextr.pathofvalheiman", TreasurePinFix.Apply);
		ConfigEntry<bool> val24 = ((BaseUnityPlugin)this).Config.Bind<bool>("SeneaLUI", "ShowPovCraftPanelWindows", true, "While a PoV window that lives in the crafting panel is open (Halls merchant shop, Book of the Halls, Runic Anvil), SeneaL UI steps its crafting view aside and shows that window, the same way it does for other mods' crafting tabs.");
		if (!val24.Value)
		{
			Log.LogInfo((object)"SeneaL UI: PoV crafting-panel windows: disabled in config");
		}
		else if (!Chainloader.PluginInfos.ContainsKey("treextr.pathofvalheiman"))
		{
			Log.LogInfo((object)"SeneaL UI: PoV crafting-panel windows: PoV not installed, skipped");
		}
		else
		{
			Run("SeneaL UI: PoV crafting-panel windows", enabled: true, "seneaL.valheim.ui", SeneaLPovWindowsFix.Apply);
		}
		ConfigEntry<bool> val25 = ((BaseUnityPlugin)this).Config.Bind<bool>("SeneaLUI", "ShowPovBeltLanternCell", true, "SeneaL UI draws PoV's Belt Lantern cell (Craft mastery: Belt Lantern) on the equipment doll next to the trinket cells, so a worn Dvergr lantern can be seen and taken off again. Without it the lantern disappears into a cell SeneaL never draws.");
		if (!val25.Value)
		{
			Log.LogInfo((object)"SeneaL UI: PoV belt lantern cell: disabled in config");
		}
		else if (!Chainloader.PluginInfos.ContainsKey("treextr.pathofvalheiman"))
		{
			Log.LogInfo((object)"SeneaL UI: PoV belt lantern cell: PoV not installed, skipped");
		}
		else
		{
			Run("SeneaL UI: PoV belt lantern cell", enabled: true, "seneaL.valheim.ui", SeneaLLanternFix.Apply);
		}
		ConfigEntry<bool> val26 = ((BaseUnityPlugin)this).Config.Bind<bool>("SeneaLUI", "PovCellsCheckItems", true, "Dropping an item on one of PoV's base equipment cells in SeneaL UI (Utility cell, belt, quiver…) asks PoV whether that cell takes the item, as SeneaL already does for PoV's extra cells. Without it a Megingjord can be dropped in the Utility cell, where PoV ignores it.");
		if (!val26.Value)
		{
			Log.LogInfo((object)"SeneaL UI: PoV cell item check: disabled in config");
		}
		else if (!Chainloader.PluginInfos.ContainsKey("treextr.pathofvalheiman"))
		{
			Log.LogInfo((object)"SeneaL UI: PoV cell item check: PoV not installed, skipped");
		}
		else
		{
			Run("SeneaL UI: PoV cell item check", enabled: true, "seneaL.valheim.ui", SeneaLCellCheckFix.Apply);
		}
		ConfigEntry<bool> val27 = ((BaseUnityPlugin)this).Config.Bind<bool>("SeneaLUI", "LockedSlotsSurviveRestart", true, "SeneaL UI saves your locked inventory slots with the character, but while PoV's equipment rows own the inventory it never reads them back at login, so every lock was gone after a restart. LMF reads them back once the character has loaded.");
		if (!val27.Value)
		{
			Log.LogInfo((object)"SeneaL UI: locked slots after restart: disabled in config");
		}
		else
		{
			Run("SeneaL UI: locked slots after restart", enabled: true, "seneaL.valheim.ui", SeneaLLocksFix.Apply);
		}
		ConfigEntry<bool> val28 = ((BaseUnityPlugin)this).Config.Bind<bool>("PathOfValheiman", "ModdedBeltsTakeBeltProperties", true, "Belts from other mods that PoV already wears in its Belt cell (e.g. Warfare's Ymir's Belt) also get PoV's 'belt' item tag, so runes and enchants can roll belt properties on them instead of saying 'No property fits this item'.");
		Run("PoV: modded belt properties", val28.Value, "treextr.pathofvalheiman", PovBeltTagFix.Apply);
		ConfigEntry<bool> val29 = ((BaseUnityPlugin)this).Config.Bind<bool>("PathOfValheiman", "MergeCookedFoodStacks", true, "The same food cooked with different PoV cooking bonuses (nourishment, duration) stacks anyway; the stack takes the count-weighted average of both. Fresh Kitchen food merges with non-fresh food only when the same cook made both, and the merged stack keeps Fresh Kitchen.");
		Run("PoV: merge cooked food stacks", val29.Value, "treextr.pathofvalheiman", FoodMergeFix.Apply);
		ConfigEntry<bool> val30 = ((BaseUnityPlugin)this).Config.Bind<bool>("PathOfValheiman", "DungeonVegvisirsMarkHalls", true, "Boss vegvisirs inside dungeons (the Queen's, in infested mines) also mark that biome's Halls of Oaths, like outdoor ones do. Without it the Oath of Mist can never be marked by a vegvisir.");
		Run("PoV: dungeon vegvisirs mark halls", val30.Value, "treextr.pathofvalheiman", DungeonVegvisirFix.Apply);
		ConfigEntry<bool> val31 = ((BaseUnityPlugin)this).Config.Bind<bool>("TrueFlightCrosshair", "ShowForPovThrownWeapons", true, "TrueFlight Crosshair shows its aim marker while you hold a weapon PoV lets you throw (Throw the Axe, knife throws), not only during the throw.");
		if (!val31.Value)
		{
			Log.LogInfo((object)"TrueFlight: PoV thrown weapons: disabled in config");
		}
		else if (!Chainloader.PluginInfos.ContainsKey("treextr.pathofvalheiman"))
		{
			Log.LogInfo((object)"TrueFlight: PoV thrown weapons: PoV not installed, skipped");
		}
		else
		{
			Run("TrueFlight: PoV thrown weapons", enabled: true, "com.valheimcrewman.dynamicaimpoint", TrueFlightThrowFix.Apply);
		}
		BonusPointsFix.Entry = ((BaseUnityPlugin)this).Config.Bind<string>("PathOfValheiman", "BonusTreePoints", string.Empty, "Extra passive-tree points for named characters, e.g. 'Gunnar=15; Astrid=4'. Each character only gets their own number (matched by character name, any case). Works like PoV's Debug points but needs no admin rights. It is a running total: raise it to grant more; lowering it takes points back along with the outermost nodes they paid for, so only ever raise it.");
		ConfigFile config = ((BaseUnityPlugin)this).Config;
		string empty = string.Empty;
		object[] array = new object[1];
		ConfigurationManagerAttributes val32 = new ConfigurationManagerAttributes();
		val32.IsAdminOnly = true;
		array[0] = val32;
		BonusPointsFix.ServerEntry = config.Bind<string>("PathOfValheiman", "ServerBonusTreePoints", empty, new ConfigDescription("Same format as BonusTreePoints, but set in the SERVER's LMF config: Jotunn sends it to every player, and changes reach players straight away (edit the server's config file and save, or change it in-game with the Configuration Manager as an admin). Each character gets the higher of this and their own BonusTreePoints. Same rule: only ever raise a number; lowering it takes points back along with the outermost nodes they paid for. Has no effect if the server doesn't run LMF.", (AcceptableValueBase)null, array));
		Run("PoV: bonus tree points", enabled: true, "treextr.pathofvalheiman", BonusPointsFix.Apply);
		if ((int)SystemInfo.graphicsDeviceType == 4)
		{
			try
			{
				new ConfigFileWatcher(((BaseUnityPlugin)this).Config, 1000L);
				Log.LogInfo((object)"Server: LMF config is watched; saving it sends ServerBonusTreePoints to players");
			}
			catch (Exception ex4)
			{
				Log.LogWarning((object)("Server: LMF config watcher NOT started (" + ex4.Message + ")"));
			}
		}
		Run("PoV: lynx_povlevels command", enabled: true, "treextr.pathofvalheiman", PovLevelsCommand.Apply);
		ConfigEntry<bool> val33 = ((BaseUnityPlugin)this).Config.Bind<bool>("PathOfValheiman", "RenameTamedAnimals", true, "Tamed animals can be renamed again with the vanilla Shift+E (crouching Shift+E stays PoV's pick-up). PoV blocks renaming entirely; companions made with the Leader's horn keep PoV's own naming.");
		Run("PoV: rename tamed animals", val33.Value, "treextr.pathofvalheiman", RenameFix.Apply);
		ConfigEntry<bool> val34 = ((BaseUnityPlugin)this).Config.Bind<bool>("PathOfValheiman", "FermentedFoodKeepsCook", true, "Food that comes out of a fermenter (Valheim Cuisine's Food Fermenter) keeps the cook's name and PoV cooking bonuses (potency, duration, Fresh Kitchen) from the ingredient that went in. PoV only carries brewer credit through fermenters for meads and potions.");
		Run("PoV: fermented food keeps cook", val34.Value, "treextr.pathofvalheiman", FermentFoodFix.Apply);
		GemBoardWindow.Key = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("SeneaLUI", "SkillBoardKey", new KeyboardShortcut((KeyCode)107, Array.Empty<KeyCode>()), "SeneaL UI replaces PoV's equipment window, so PoV's Skills tab (the skill-gem board) never shows. With the inventory open, this key opens PoV's own skill board in a window of its own.");
		GemBoardWindow.PosCfg = ((BaseUnityPlugin)this).Config.Bind<Vector2>("SeneaLUI", "SkillBoardPosition", new Vector2(-1f, -1f), "Where the skill board window sits (saved when you drag it by its title area). -1 = default spot.");
		GemBoardWindow.SizeCfg = ((BaseUnityPlugin)this).Config.Bind<Vector2>("SeneaLUI", "SkillBoardSize", new Vector2(660f, 620f), "Size of the skill board window (saved when you drag its bottom-right corner).");
		if (Chainloader.PluginInfos.ContainsKey("treextr.pathofvalheiman") && Chainloader.PluginInfos.ContainsKey("seneaL.valheim.ui"))
		{
			Run("SeneaL UI: PoV skill board window", enabled: true, "treextr.pathofvalheiman", GemBoardWindow.Apply);
		}
		ConfigEntry<bool> val35 = ((BaseUnityPlugin)this).Config.Bind<bool>("Vanilla", "NoBirthsThroughWalls", true, "A newborn animal appears a short way in front of its mother; if a wall, fence or rock is in between, it is born at the mother's spot instead, so offspring stay inside their pen.");
		if (!val35.Value)
		{
			Log.LogInfo((object)"Vanilla: births through walls: disabled in config");
		}
		else
		{
			try
			{
				Log.LogInfo((object)("Vanilla: births through walls: " + BirthFix.Apply()));
			}
			catch (Exception ex5)
			{
				Log.LogWarning((object)("Vanilla: births through walls: NOT applied (" + ex5.Message + ")"));
			}
		}
		ConfigEntry<bool> val36 = ((BaseUnityPlugin)this).Config.Bind<bool>("WiresForge", "KeepItemDataOnFailure", true, "When forging an item at Wire's Forge of Goodtential fails (it keeps or loses quality), the game hands back a fresh copy of the item, and PoV only carries affixes, sockets and brand over to an item that went UP in quality, so the item came back bare. LMF remembers the item's saved data before every upgrade and puts back whatever the returned item is missing. Never overwrites anything.");
		Run("WiresForge: keep affixes on failed forging", val36.Value, "wire.valheim.forgeofgoodtential", ForgeKeepDataFix.Apply);
	}

	private static void Run(string name, bool enabled, string guid, Func<Assembly, string> apply)
	{
		if (!enabled)
		{
			Log.LogInfo((object)(name + ": disabled in config"));
			return;
		}
		if (!Chainloader.PluginInfos.TryGetValue(guid, out var value) || (Object)(object)value.Instance == (Object)null)
		{
			Log.LogInfo((object)(name + ": mod not installed, skipped"));
			return;
		}
		try
		{
			Log.LogInfo((object)(name + ": " + apply(((object)value.Instance).GetType().Assembly)));
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)(name + ": NOT applied (" + ex.Message + ")"));
		}
	}

	internal static int LocalIndex(CodeInstruction ci)
	{
		OpCode opcode = ci.opcode;
		if (opcode == OpCodes.Ldloc_0 || opcode == OpCodes.Stloc_0)
		{
			return 0;
		}
		if (opcode == OpCodes.Ldloc_1 || opcode == OpCodes.Stloc_1)
		{
			return 1;
		}
		if (opcode == OpCodes.Ldloc_2 || opcode == OpCodes.Stloc_2)
		{
			return 2;
		}
		if (opcode == OpCodes.Ldloc_3 || opcode == OpCodes.Stloc_3)
		{
			return 3;
		}
		if (opcode == OpCodes.Ldloc || opcode == OpCodes.Ldloc_S || opcode == OpCodes.Stloc || opcode == OpCodes.Stloc_S)
		{
			object obj = ci.operand as LocalBuilder;
			LocalBuilder localBuilder = default(LocalBuilder);
			if (obj != null)
			{
				localBuilder = (LocalBuilder)obj;
				obj = localBuilder;
			}
			if (obj != null)
			{
				return localBuilder.LocalIndex;
			}
			object operand = ci.operand;
			object obj2 = ((operand is int) ? operand : null);
			int result = default(int);
			if (obj2 != null)
			{
				result = (int)operand;
			}
			if (obj2 != null)
			{
				return result;
			}
			operand = ci.operand;
			object obj3 = ((operand is byte) ? operand : null);
			byte result2 = default(byte);
			if (obj3 != null)
			{
				result2 = (byte)operand;
			}
			if (obj3 != null)
			{
				return result2;
			}
		}
		return -1;
	}

	internal static bool IsLd(CodeInstruction ci)
	{
		return ci.opcode == OpCodes.Ldloc_0 || ci.opcode == OpCodes.Ldloc_1 || ci.opcode == OpCodes.Ldloc_2 || ci.opcode == OpCodes.Ldloc_3 || ci.opcode == OpCodes.Ldloc || ci.opcode == OpCodes.Ldloc_S;
	}

	internal static bool IsSt(CodeInstruction ci)
	{
		return ci.opcode == OpCodes.Stloc_0 || ci.opcode == OpCodes.Stloc_1 || ci.opcode == OpCodes.Stloc_2 || ci.opcode == OpCodes.Stloc_3 || ci.opcode == OpCodes.Stloc || ci.opcode == OpCodes.Stloc_S;
	}

	internal static CodeInstruction LoadFromStore(CodeInstruction st)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Expected O, but got Unknown
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Expected O, but got Unknown
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected O, but got Unknown
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Expected O, but got Unknown
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Expected O, but got Unknown
		if (!(st.opcode == OpCodes.Stloc_0))
		{
			if (!(st.opcode == OpCodes.Stloc_1))
			{
				if (!(st.opcode == OpCodes.Stloc_2))
				{
					if (!(st.opcode == OpCodes.Stloc_3))
					{
						return new CodeInstruction(OpCodes.Ldloc, st.operand);
					}
					return new CodeInstruction(OpCodes.Ldloc_3, (object)null);
				}
				return new CodeInstruction(OpCodes.Ldloc_2, (object)null);
			}
			return new CodeInstruction(OpCodes.Ldloc_1, (object)null);
		}
		return new CodeInstruction(OpCodes.Ldloc_0, (object)null);
	}

	internal static bool Calls(CodeInstruction ci, string name)
	{
		int result;
		if (ci.opcode == OpCodes.Call || ci.opcode == OpCodes.Callvirt)
		{
			object obj = ci.operand as MethodBase;
			MethodBase methodBase = default(MethodBase);
			if (obj != null)
			{
				methodBase = (MethodBase)obj;
				obj = methodBase;
			}
			if (obj != null)
			{
				result = ((methodBase.Name == name) ? 1 : 0);
				goto IL_004e;
			}
		}
		result = 0;
		goto IL_004e;
		IL_004e:
		return (byte)result != 0;
	}

	internal static bool LoadsInt(CodeInstruction ci, int v)
	{
		if (v == 0 && ci.opcode == OpCodes.Ldc_I4_0)
		{
			return true;
		}
		if (v == 3 && ci.opcode == OpCodes.Ldc_I4_3)
		{
			return true;
		}
		if (v == 5 && ci.opcode == OpCodes.Ldc_I4_5)
		{
			return true;
		}
		if (ci.opcode == OpCodes.Ldc_I4_S && Convert.ToInt32(ci.operand) == v)
		{
			return true;
		}
		if (ci.opcode == OpCodes.Ldc_I4 && Convert.ToInt32(ci.operand) == v)
		{
			return true;
		}
		return false;
	}

	internal static bool LdFld(CodeInstruction ci, string name)
	{
		int result;
		if (ci.opcode == OpCodes.Ldfld)
		{
			object obj = ci.operand as FieldInfo;
			FieldInfo fieldInfo = default(FieldInfo);
			if (obj != null)
			{
				fieldInfo = (FieldInfo)obj;
				obj = fieldInfo;
			}
			if (obj != null)
			{
				result = ((fieldInfo.Name == name) ? 1 : 0);
				goto IL_0039;
			}
		}
		result = 0;
		goto IL_0039;
		IL_0039:
		return (byte)result != 0;
	}

	internal static void Patch(MethodBase target, string transpiler, Type owner, int expectAtLeast, ref int total)
	{
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Expected O, but got Unknown
		if (target == null)
		{
			throw new Exception("target method missing");
		}
		Hits[target] = 0;
		Harmony h = H;
		HarmonyMethod val = new HarmonyMethod(owner.GetMethod(transpiler, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
		h.Patch(target, (HarmonyMethod)null, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null);
		int num = Hits[target];
		if (num < expectAtLeast)
		{
			H.Unpatch(target, (HarmonyPatchType)3, "lynx.modfixes");
			throw new Exception(target.DeclaringType.Name + "." + target.Name + " changed (matched " + num + ")");
		}
		total += num;
	}
}
public static class KvistFixes
{
	internal static bool keepBonuses = true;

	internal static bool drawersFirst = true;

	private static Func<Vector3, float, List<Container>> labelled;

	private static Func<Container, bool> blacklisted;

	private static Func<Container, string> labelOf;

	private static FieldInfo catId;

	private static Func<ItemData, string> prefabName;

	private static Func<Inventory, ItemData, int> spaceFor;

	private static MethodInfo hasRoom;

	private static FieldInfo closureItem;

	private static readonly string[] BonusKeys = new string[6] { "pt.food", "pt.brew", "pt.oil", "pt.aged", "pt.age.", "pt.meadjarl" };

	public static string ApplyDrawers(Assembly kv)
	{
		//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fb: Expected O, but got Unknown
		//IL_03f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_0401: Expected O, but got Unknown
		Type type = kv.GetType("GreydwarfSorter.Chests.ChestIndex", throwOnError: true);
		prefabName = (Func<ItemData, string>)Delegate.CreateDelegate(typeof(Func<ItemData, string>), AccessTools.Method(kv.GetType("GreydwarfSorter.Categories.ItemClassifier", throwOnError: true), "PrefabName", new Type[1] { typeof(ItemData) }, (Type[])null));
		spaceFor = (Func<Inventory, ItemData, int>)Delegate.CreateDelegate(typeof(Func<Inventory, ItemData, int>), AccessTools.Method(kv.GetType("GreydwarfSorter.Chests.ContainerAccess", throwOnError: true), "SpaceFor", new Type[2]
		{
			typeof(Inventory),
			typeof(ItemData)
		}, (Type[])null));
		hasRoom = AccessTools.Method(type, "HasRoom", new Type[2]
		{
			typeof(Container),
			typeof(ItemData)
		}, (Type[])null) ?? throw new Exception("HasRoom missing");
		Type type2 = AccessTools.Inner(type, "<>c__DisplayClass19_0") ?? throw new Exception("FindTarget closure missing");
		Type type3 = AccessTools.Inner(type, "<>c") ?? throw new Exception("FindTarget lambdas missing");
		closureItem = AccessTools.Field(type2, "item") ?? throw new Exception("closure item missing");
		MethodInfo methodInfo = AccessTools.Method(type2, "<FindTarget>b__1", (Type[])null, (Type[])null);
		MethodInfo methodInfo2 = AccessTools.Method(type3, "<FindTarget>b__19_2", (Type[])null, (Type[])null);
		MethodInfo methodInfo3 = AccessTools.Method(type3, "<FindTarget>b__19_4", (Type[])null, (Type[])null);
		MethodInfo methodInfo4 = AccessTools.Method(kv.GetType("GreydwarfSorter.Worker.SorterAI", throwOnError: true), "RoutedTarget", (Type[])null, (Type[])null);
		int total = 0;
		if (CountEmpty(methodInfo) != 1 || CountEmpty(methodInfo2) != 1 || CountEmpty(methodInfo3) != 1)
		{
			throw new Exception("FindTarget empty-chest checks changed");
		}
		if (CountRouted(methodInfo4) != 1)
		{
			throw new Exception("RoutedTarget changed");
		}
		Plugin.H.Patch((MethodBase)hasRoom, new HarmonyMethod(typeof(KvistFixes), "HasRoomPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		if (drawersFirst)
		{
			MethodInfo methodInfo5 = AccessTools.Method(type, "FindTarget", (Type[])null, (Type[])null) ?? throw new Exception("FindTarget missing");
			ParameterInfo[] parameters = methodInfo5.GetParameters();
			if (parameters.Length != 6 || parameters[1].ParameterType != typeof(ItemData) || parameters[2].ParameterType != typeof(Vector3) || parameters[3].ParameterType != typeof(float) || parameters[4].ParameterType != typeof(Vector3))
			{
				throw new Exception("FindTarget signature changed");
			}
			labelled = (Func<Vector3, float, List<Container>>)Delegate.CreateDelegate(typeof(Func<Vector3, float, List<Container>>), AccessTools.Method(type, "Labelled", new Type[2]
			{
				typeof(Vector3),
				typeof(float)
			}, (Type[])null) ?? throw new Exception("Labelled missing"));
			blacklisted = (Func<Container, bool>)Delegate.CreateDelegate(typeof(Func<Container, bool>), AccessTools.Method(type, "IsBlacklisted", new Type[1] { typeof(Container) }, (Type[])null) ?? throw new Exception("IsBlacklisted missing"));
			labelOf = (Func<Container, string>)Delegate.CreateDelegate(typeof(Func<Container, string>), AccessTools.Method(kv.GetType("GreydwarfSorter.Chests.ChestLabel", throwOnError: true), "Get", new Type[1] { typeof(Container) }, (Type[])null) ?? throw new Exception("ChestLabel.Get missing"));
			catId = AccessTools.Field(kv.GetType("GreydwarfSorter.Categories.Category", throwOnError: true), "Id") ?? throw new Exception("Category.Id missing");
			Plugin.H.Patch((MethodBase)methodInfo5, new HarmonyMethod(typeof(KvistFixes), "DrawerFirst", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
		Plugin.Patch(methodInfo, "EmptyWithItem", typeof(KvistFixes), 1, ref total);
		Plugin.Patch(methodInfo2, "EmptyNoItem", typeof(KvistFixes), 1, ref total);
		Plugin.Patch(methodInfo3, "EmptyNoItem", typeof(KvistFixes), 1, ref total);
		Plugin.Patch(methodInfo4, "RoutedUsesHasRoom", typeof(KvistFixes), 1, ref total);
		return "applied (" + (total + 1) + " sites)";
	}

	public static string ApplyCoal(Assembly kv)
	{
		MethodInfo target = AccessTools.Method(kv.GetType("GreydwarfSorter.Worker.SorterAI", throwOnError: true), "OfferSmelting", (Type[])null, (Type[])null) ?? throw new Exception("OfferSmelting missing");
		int total = 0;
		Plugin.Patch(target, "KilnsRespectStock", typeof(KvistFixes), 2, ref total);
		return "applied (" + total + " sites)";
	}

	public static bool HasPovBonus(ItemData item)
	{
		Dictionary<string, string> dictionary = item?.m_customData;
		if (dictionary == null || dictionary.Count == 0)
		{
			return false;
		}
		foreach (string key in dictionary.Keys)
		{
			string[] bonusKeys = BonusKeys;
			foreach (string value in bonusKeys)
			{
				if (key.StartsWith(value, StringComparison.Ordinal))
				{
					return true;
				}
			}
		}
		return false;
	}

	public static int DrawerVerdict(Container c, ItemData item)
	{
		if (!Object.op_Implicit((Object)(object)c) || ((object)c).GetType().Name != "DrawerComponent")
		{
			return 0;
		}
		if (item != null && item.m_shared.m_maxStackSize <= 1)
		{
			return 2;
		}
		if (item != null && keepBonuses && HasPovBonus(item))
		{
			return 2;
		}
		ZNetView component = ((Component)c).GetComponent<ZNetView>();
		if (!Object.op_Implicit((Object)(object)component) || !component.IsValid())
		{
			return 2;
		}
		string text = component.GetZDO().GetString("Prefab", string.Empty);
		if (string.IsNullOrEmpty(text) || item == null)
		{
			return 2;
		}
		return (text == prefabName(item)) ? 1 : 2;
	}

	public static bool EmptyFor(Container c, ItemData item)
	{
		switch (DrawerVerdict(c, item))
		{
		case 0:
			return c.GetInventory().NrOfItems() == 0;
		default:
			if (item != null)
			{
				return spaceFor(c.GetInventory(), item) > 0;
			}
			goto case 2;
		case 2:
			return false;
		}
	}

	private static bool DrawerFirst(object __0, ItemData __1, Vector3 __2, float __3, Vector3 __4, ref Container __result)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			string text = ((__0 != null) ? (catId.GetValue(__0) as string) : null);
			if (text == null || text == "incoming_loot" || __1 == null)
			{
				return true;
			}
			Container val = null;
			float num = float.MaxValue;
			foreach (Container item in labelled(__2, __3))
			{
				if (Object.op_Implicit((Object)(object)item) && !blacklisted(item) && !(labelOf(item) != text) && DrawerVerdict(item, __1) == 1 && (bool)hasRoom.Invoke(null, new object[2] { item, __1 }))
				{
					float num2 = Vector3.Distance(__4, ((Component)item).transform.position);
					if (num2 < num)
					{
						num = num2;
						val = item;
					}
				}
			}
			if (!Object.op_Implicit((Object)(object)val))
			{
				return true;
			}
			__result = val;
			return false;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Kvist: drawers first: " + ex.Message));
			return true;
		}
	}

	private static bool HasRoomPrefix(Container __0, ItemData __1, ref bool __result)
	{
		if (DrawerVerdict(__0, __1) == 2)
		{
			__result = false;
			return false;
		}
		return true;
	}

	private static int FindEmptyCheck(List<CodeInstruction> c)
	{
		for (int i = 0; i + 3 < c.Count; i++)
		{
			if (Plugin.Calls(c[i], "GetInventory") && Plugin.Calls(c[i + 1], "NrOfItems") && Plugin.LoadsInt(c[i + 2], 0) && c[i + 3].opcode == OpCodes.Ceq)
			{
				return i;
			}
		}
		return -1;
	}

	private static int CountEmpty(MethodBase m)
	{
		return (!(m == null) && FindEmptyCheck(PatchProcessor.GetOriginalInstructions(m, (ILGenerator)null)) >= 0) ? 1 : 0;
	}

	private static IEnumerable<CodeInstruction> EmptyWithItem(IEnumerable<CodeInstruction> ins, MethodBase original)
	{
		return ReplaceEmpty(ins, original, withItem: true);
	}

	private static IEnumerable<CodeInstruction> EmptyNoItem(IEnumerable<CodeInstruction> ins, MethodBase original)
	{
		return ReplaceEmpty(ins, original, withItem: false);
	}

	private static IEnumerable<CodeInstruction> ReplaceEmpty(IEnumerable<CodeInstruction> ins, MethodBase original, bool withItem)
	{
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Expected O, but got Unknown
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Expected O, but got Unknown
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Expected O, but got Unknown
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Expected O, but got Unknown
		List<CodeInstruction> list = ins.ToList();
		int num = FindEmptyCheck(list);
		if (num < 0)
		{
			return list;
		}
		List<CodeInstruction> list2 = new List<CodeInstruction>();
		if (withItem)
		{
			list2.Add(new CodeInstruction(OpCodes.Ldarg_0, (object)null));
			list2.Add(new CodeInstruction(OpCodes.Ldfld, (object)closureItem));
		}
		else
		{
			list2.Add(new CodeInstruction(OpCodes.Ldnull, (object)null));
		}
		list2.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(KvistFixes), "EmptyFor", (Type[])null, (Type[])null)));
		list2[0].labels.AddRange(list[num].labels);
		list.RemoveRange(num, 4);
		list.InsertRange(num, list2);
		Plugin.Hits[original]++;
		return list;
	}

	private static int FindRouted(List<CodeInstruction> c)
	{
		for (int i = 0; i + 4 < c.Count; i++)
		{
			if (Plugin.Calls(c[i], "GetInventory") && c[i + 1].opcode == OpCodes.Ldarg_1 && Plugin.Calls(c[i + 2], "SpaceFor") && Plugin.LoadsInt(c[i + 3], 0) && (c[i + 4].opcode == OpCodes.Ble || c[i + 4].opcode == OpCodes.Ble_S))
			{
				return i;
			}
		}
		return -1;
	}

	private static int CountRouted(MethodBase m)
	{
		return (!(m == null) && FindRouted(PatchProcessor.GetOriginalInstructions(m, (ILGenerator)null)) >= 0) ? 1 : 0;
	}

	private static IEnumerable<CodeInstruction> RoutedUsesHasRoom(IEnumerable<CodeInstruction> ins, MethodBase original)
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Expected O, but got Unknown
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Expected O, but got Unknown
		List<CodeInstruction> list = ins.ToList();
		int num = FindRouted(list);
		if (num < 0)
		{
			return list;
		}
		object operand = list[num + 4].operand;
		List<CodeInstruction> list2 = new List<CodeInstruction>();
		list2.Add(new CodeInstruction(OpCodes.Ldarg_1, (object)null));
		list2.Add(new CodeInstruction(OpCodes.Call, (object)hasRoom));
		list2.Add(new CodeInstruction(OpCodes.Brfalse, operand));
		List<CodeInstruction> list3 = list2;
		list3[0].labels.AddRange(list[num].labels);
		list.RemoveRange(num, 5);
		list.InsertRange(num, list3);
		Plugin.Hits[original]++;
		return list;
	}

	private static IEnumerable<CodeInstruction> KilnsRespectStock(IEnumerable<CodeInstruction> ins, MethodBase original)
	{
		//IL_0164: Unknown result type (might be due to invalid IL or missing references)
		//IL_016a: Expected O, but got Unknown
		List<CodeInstruction> list = ins.ToList();
		int num = list.FindIndex((CodeInstruction x) => Plugin.Calls(x, "ChosenByHand"));
		int s = list.FindIndex((CodeInstruction x) => Plugin.Calls(x, "CoalShort"));
		if (num < 0 || s < 0 || !Plugin.IsSt(list[num + 1]) || !Plugin.IsSt(list[s + 1]))
		{
			return list;
		}
		int num2 = Plugin.LocalIndex(list[num + 1]);
		CodeInstruction st = list[s + 1];
		List<int> list2 = new List<int>();
		for (int num3 = 0; num3 < list.Count; num3++)
		{
			if (Plugin.IsLd(list[num3]) && Plugin.LocalIndex(list[num3]) == num2)
			{
				list2.Add(num3);
			}
		}
		if (list2.Count != 2 || list2.Any((int u) => u < s + 1))
		{
			return list;
		}
		for (int num4 = list2.Count - 1; num4 >= 0; num4--)
		{
			list.InsertRange(list2[num4] + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
			{
				Plugin.LoadFromStore(st),
				new CodeInstruction(OpCodes.And, (object)null)
			});
			Plugin.Hits[original]++;
		}
		return list;
	}
}
public static class PortalCrateFix
{
	private static CraftingStation workbench;

	public static string Apply(Assembly pov)
	{
		MethodBase methodBase = pov.GetType("PassiveTree.ShipCrate", throwOnError: true).GetMethod("Decide", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? AccessTools.Method(pov.GetType("PassiveTree.ShipCrate+Remove", throwOnError: true), "Prefix", (Type[])null, (Type[])null) ?? throw new Exception("ShipCrate.Decide / Remove.Prefix missing");
		int total = 0;
		Plugin.Patch(methodBase, "Transpile", typeof(PortalCrateFix), 1, ref total);
		return "applied (" + methodBase.DeclaringType.Name + "." + methodBase.Name + ")";
	}

	public static CraftingStation StationFor(Piece p)
	{
		if (!Object.op_Implicit((Object)(object)p))
		{
			return null;
		}
		if (Object.op_Implicit((Object)(object)p.m_craftingStation))
		{
			return p.m_craftingStation;
		}
		if (!Object.op_Implicit((Object)(object)((Component)p).GetComponentInChildren<TeleportWorld>()))
		{
			return null;
		}
		if (!Object.op_Implicit((Object)(object)workbench) && Object.op_Implicit((Object)(object)ZNetScene.instance))
		{
			GameObject prefab = ZNetScene.instance.GetPrefab("piece_workbench");
			if (Object.op_Implicit((Object)(object)prefab))
			{
				workbench = prefab.GetComponent<CraftingStation>();
			}
		}
		return workbench;
	}

	private static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> ins, MethodBase original)
	{
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Expected O, but got Unknown
		List<CodeInstruction> list = ins.ToList();
		int num = list.FindIndex(delegate(CodeInstruction x)
		{
			int result;
			if (x.opcode == OpCodes.Ldfld)
			{
				object obj = x.operand as FieldInfo;
				FieldInfo fieldInfo = default(FieldInfo);
				if (obj != null)
				{
					fieldInfo = (FieldInfo)obj;
					obj = fieldInfo;
				}
				if (obj != null && fieldInfo.Name == "m_craftingStation")
				{
					result = ((fieldInfo.DeclaringType == typeof(Piece)) ? 1 : 0);
					goto IL_0057;
				}
			}
			result = 0;
			goto IL_0057;
			IL_0057:
			return (byte)result != 0;
		});
		if (num < 0)
		{
			return list;
		}
		list[num] = CodeInstructionExtensions.WithLabels(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(PortalCrateFix), "StationFor", (Type[])null, (Type[])null)), (IEnumerable<Label>)list[num].labels);
		Plugin.Hits[original]++;
		return list;
	}
}
public static class XPortalCrateFix
{
	private const string K = "lynx.xp.";

	private static Type kpT;

	private static Func<object> mgr;

	private static MethodInfo getById;

	private static MethodInfo withTarget;

	private static MethodInfo addOrUpdate;

	private static MethodInfo updateZdo;

	private static MethodInfo onDestroyed;

	private static readonly string[] Props = new string[5] { "Name", "Colour", "NetworkOwnerPlayerId", "NetworkOwnerDisplayName", "IsPrivate" };

	private static Dictionary<string, string> packing;

	private static readonly Dictionary<ZDOID, Dictionary<string, string>> pending = new Dictionary<ZDOID, Dictionary<string, string>>();

	private static readonly Dictionary<ZDOID, float> expires = new Dictionary<ZDOID, float>();

	private const float Window = 30f;

	public static string Apply(Assembly xp)
	{
		//IL_0294: Unknown result type (might be due to invalid IL or missing references)
		//IL_029b: Expected O, but got Unknown
		//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02aa: Expected O, but got Unknown
		//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b9: Expected O, but got Unknown
		//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0309: Expected O, but got Unknown
		//IL_0363: Unknown result type (might be due to invalid IL or missing references)
		//IL_0371: Expected O, but got Unknown
		//IL_0380: Unknown result type (might be due to invalid IL or missing references)
		//IL_0387: Expected O, but got Unknown
		//IL_03a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_03aa: Expected O, but got Unknown
		//IL_03d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e6: Expected O, but got Unknown
		Assembly assembly = ((object)Chainloader.PluginInfos["treextr.pathofvalheiman"].Instance).GetType().Assembly;
		Type type = assembly.GetType("PassiveTree.ShipCrate", throwOnError: true);
		Type type2 = xp.GetType("XPortalNetworks.XPortalNetworks", throwOnError: true);
		Type type3 = xp.GetType("XPortalNetworks.KnownPortalsManager", throwOnError: true);
		kpT = xp.GetType("XPortalNetworks.KnownPortal", throwOnError: true);
		MethodInfo inst = AccessTools.PropertyGetter(type3, "Instance") ?? throw new Exception("KnownPortalsManager.Instance missing");
		mgr = () => inst.Invoke(null, null);
		getById = AccessTools.Method(type3, "GetKnownPortalById", new Type[1] { typeof(ZDOID) }, (Type[])null) ?? throw new Exception("GetKnownPortalById missing");
		withTarget = AccessTools.Method(type3, "GetPortalsWithTarget", new Type[1] { typeof(ZDOID) }, (Type[])null) ?? throw new Exception("GetPortalsWithTarget missing");
		addOrUpdate = AccessTools.Method(xp.GetType("XPortalNetworks.RPC.SendToServer", throwOnError: true), "AddOrUpdateRequest", (Type[])null, (Type[])null) ?? throw new Exception("AddOrUpdateRequest missing");
		updateZdo = AccessTools.Method(xp.GetType("XPortalNetworks.ZdoTools", throwOnError: true), "UpdateFromKnownPortal", (Type[])null, (Type[])null) ?? throw new Exception("UpdateFromKnownPortal missing");
		onDestroyed = AccessTools.Method(type2, "OnPortalDestroyed", new Type[1] { typeof(ZDOID) }, (Type[])null) ?? throw new Exception("OnPortalDestroyed missing");
		foreach (string item in Props.Concat(new string[1] { "Target" }))
		{
			if (AccessTools.Property(kpT, item) == null)
			{
				throw new Exception("KnownPortal." + item + " missing");
			}
		}
		MethodInfo methodInfo = AccessTools.Method(type, "PackPortal", (Type[])null, (Type[])null) ?? throw new Exception("PackPortal missing");
		MethodInfo methodInfo2 = AccessTools.Method(type, "Unpack", (Type[])null, (Type[])null) ?? throw new Exception("Unpack missing");
		MethodInfo methodInfo3 = AccessTools.Method(type2, "OnPortalPlaced", (Type[])null, (Type[])null) ?? throw new Exception("OnPortalPlaced missing");
		Harmony h = Plugin.H;
		Type typeFromHandle = typeof(XPortalCrateFix);
		MethodInfo methodInfo4 = methodInfo;
		HarmonyMethod val = new HarmonyMethod(typeFromHandle, "PackPre", (Type[])null);
		HarmonyMethod val2 = new HarmonyMethod(typeFromHandle, "PackPost", (Type[])null);
		HarmonyMethod val3 = new HarmonyMethod(typeFromHandle, "PackFin", (Type[])null);
		h.Patch((MethodBase)methodInfo4, val, val2, (HarmonyMethod)null, val3, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(Inventory), "AddItem", new Type[1] { typeof(ItemData) }, (Type[])null), new HarmonyMethod(typeFromHandle, "Tag", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(ItemDrop), "DropItem", new Type[4]
		{
			typeof(ItemData),
			typeof(int),
			typeof(Vector3),
			typeof(Quaternion)
		}, (Type[])null), new HarmonyMethod(typeFromHandle, "Tag", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		methodInfo4 = methodInfo2;
		val3 = new HarmonyMethod(typeFromHandle, "UnpackPost", (Type[])null);
		h.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		methodInfo4 = methodInfo3;
		val3 = new HarmonyMethod(typeFromHandle, "PlacedPost", (Type[])null);
		h.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)AccessTools.Method(typeof(TextInput), "RequestText", (Type[])null, (Type[])null), new HarmonyMethod(typeFromHandle, "ReleaseOnEdit", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		return "applied";
	}

	private static object Known(ZDOID id)
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		object obj = mgr();
		return (obj != null) ? getById.Invoke(obj, new object[1] { id }) : null;
	}

	private static object Get(object kp, string p)
	{
		return AccessTools.Property(kpT, p).GetValue(kp, null);
	}

	private static void Set(object kp, string p, object v)
	{
		AccessTools.Property(kpT, p).SetValue(kp, v, null);
	}

	private static ZDOID IdOf(Component c)
	{
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		ZNetView val = ((!Object.op_Implicit((Object)(object)c)) ? null : c.GetComponent<ZNetView>());
		return (!Object.op_Implicit((Object)(object)val) || !val.IsValid()) ? ZDOID.None : val.GetZDO().m_uid;
	}

	private static void PackPre(Piece __1, out ZDOID __state)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		__state = IdOf((Component)(object)__1);
		packing = null;
		try
		{
			object obj = ((!((ZDOID)(ref __state)).IsNone()) ? Known(__state) : null);
			if (obj == null)
			{
				Plugin.Log.LogInfo((object)"XPortal crate: packed portal has no XPortalNetworks record");
				return;
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			string[] props = Props;
			foreach (string text in props)
			{
				dictionary["lynx.xp." + text] = Convert.ToString(Get(obj, text) ?? string.Empty, CultureInfo.InvariantCulture);
			}
			ZDOID val = (ZDOID)Get(obj, "Target");
			dictionary["lynx.xp.Target"] = ((ZDOID)(ref val)).UserID.ToString(CultureInfo.InvariantCulture) + ":" + ((ZDOID)(ref val)).ID.ToString(CultureInfo.InvariantCulture);
			dictionary["lynx.xp.OldId"] = ((ZDOID)(ref __state)).UserID.ToString(CultureInfo.InvariantCulture) + ":" + ((ZDOID)(ref __state)).ID.ToString(CultureInfo.InvariantCulture);
			packing = dictionary;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("XPortal crate: could not read portal record (" + ex.Message + ")"));
		}
	}

	private static void Tag(ItemData __0)
	{
		if (packing == null || __0 == null || __0.m_customData == null || !__0.m_customData.ContainsKey("pt.pack.ship"))
		{
			return;
		}
		foreach (KeyValuePair<string, string> item in packing)
		{
			__0.m_customData[item.Key] = item.Value;
		}
		Plugin.Log.LogInfo((object)("XPortal crate: saved settings of '" + packing["lynx.xp.Name"] + "' into the crate"));
	}

	private static void PackPost(bool __result, ZDOID __state)
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		if (!__result || ((ZDOID)(ref __state)).IsNone())
		{
			return;
		}
		try
		{
			onDestroyed.Invoke(null, new object[1] { __state });
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("XPortal crate: could not unregister packed portal (" + ex.Message + ")"));
		}
	}

	private static void PackFin()
	{
		packing = null;
	}

	private static void UnpackPost(Piece __0, ItemData __1)
	{
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_012b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		if (__1?.m_customData == null)
		{
			return;
		}
		Dictionary<string, string> dictionary = __1.m_customData.Where((KeyValuePair<string, string> kv) => kv.Key.StartsWith("lynx.xp.")).ToDictionary((KeyValuePair<string, string> kv) => kv.Key, (KeyValuePair<string, string> kv) => kv.Value);
		if (!dictionary.ContainsKey("lynx.xp.Name") && __1.m_customData.TryGetValue("pt.pack.tag", out var value) && !string.IsNullOrEmpty(value))
		{
			dictionary["lynx.xp.Name"] = value;
		}
		if (dictionary.ContainsKey("lynx.xp.Name"))
		{
			ZDOID val = IdOf((Component)(object)__0);
			if (!((ZDOID)(ref val)).IsNone())
			{
				pending[val] = dictionary;
				expires[val] = Time.time + 30f;
				Plugin.Log.LogInfo((object)("XPortal crate: setting up '" + dictionary["lynx.xp.Name"] + "'"));
				((MonoBehaviour)Plugin.Instance).StartCoroutine(Watch(val, ((Component)__0).transform.position));
			}
		}
	}

	private static void PlacedPost(ZDOID __0)
	{
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		foreach (ZDOID item in (from e in expires
			where e.Value < Time.time
			select e.Key).ToList())
		{
			expires.Remove(item);
			pending.Remove(item);
		}
		if (pending.ContainsKey(__0))
		{
			Restore(__0);
		}
	}

	private static ZDOID ParseId(string s)
	{
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		string[] array = (s ?? string.Empty).Split(':');
		if (array.Length == 2 && long.TryParse(array[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && uint.TryParse(array[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2))
		{
			return new ZDOID(result, result2);
		}
		return ZDOID.None;
	}

	private static IEnumerator Watch(ZDOID id, Vector3 pos)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		float start = Time.time;
		bool created = false;
		bool restored = false;
		int stable = 0;
		while (Time.time - start < 30f && pending.ContainsKey(id))
		{
			yield return (object)new WaitForSeconds(0.5f);
			object kp = null;
			try
			{
				kp = Known(id);
			}
			catch
			{
			}
			if (kp == null && !created && Time.time - start > 2f)
			{
				try
				{
					object obj2 = Activator.CreateInstance(kpT, id, pos);
					AccessTools.Method(mgr().GetType(), "AddOrUpdate", (Type[])null, (Type[])null).Invoke(mgr(), new object[1] { obj2 });
					created = true;
					Plugin.Log.LogInfo((object)"XPortal crate: registered the new portal with XPortalNetworks");
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("XPortal crate: could not register portal (" + (ex.InnerException ?? ex).Message + ")"));
				}
			}
			else
			{
				if (kp == null)
				{
					continue;
				}
				if (Drifted(id, kp))
				{
					Restore(id);
					restored = true;
					stable = 0;
				}
				else if (restored)
				{
					int num;
					stable = (num = stable + 1);
					if (num >= 6)
					{
						break;
					}
				}
			}
		}
		pending.Remove(id);
		expires.Remove(id);
	}

	private static void ReleaseOnEdit(TextReceiver __0)
	{
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		if (pending.Count == 0)
		{
			return;
		}
		object obj = ((__0 is Component) ? __0 : null);
		Component val = default(Component);
		if (obj != null)
		{
			val = (Component)obj;
			obj = val;
		}
		if (obj != null)
		{
			ZDOID key = IdOf((Component)(object)((!Object.op_Implicit((Object)(object)val.GetComponentInParent<ZNetView>())) ? null : val.GetComponentInParent<ZNetView>()));
			if (!((ZDOID)(ref key)).IsNone() && pending.Remove(key))
			{
				expires.Remove(key);
				Plugin.Log.LogInfo((object)"XPortal crate: portal is being edited; stopped restoring its saved settings");
			}
		}
	}

	private static bool Drifted(ZDOID id, object kp)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		if (!pending.TryGetValue(id, out var value))
		{
			return false;
		}
		string text = Convert.ToString(Get(kp, "Name") ?? string.Empty);
		if (text != ((!value.TryGetValue("lynx.xp.Name", out var value2)) ? string.Empty : value2))
		{
			return true;
		}
		if (value.TryGetValue("lynx.xp.IsPrivate", out var value3) && Convert.ToString(Get(kp, "IsPrivate")) != value3)
		{
			return true;
		}
		if (value.TryGetValue("lynx.xp.NetworkOwnerPlayerId", out var value4) && Convert.ToString(Get(kp, "NetworkOwnerPlayerId"), CultureInfo.InvariantCulture) != value4)
		{
			return true;
		}
		ZDO val = ((ZDOMan.instance == null) ? null : ZDOMan.instance.GetZDO(id));
		if (val != null && val.GetString("tag", string.Empty) != text)
		{
			return true;
		}
		return false;
	}

	private static void Restore(ZDOID id)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_0230: Unknown result type (might be due to invalid IL or missing references)
		if (!pending.TryGetValue(id, out var d))
		{
			return;
		}
		try
		{
			object obj = Known(id);
			if (obj == null)
			{
				Plugin.Log.LogWarning((object)"XPortal crate: placed portal not registered yet; settings not restored");
				return;
			}
			string value3;
			Func<string, string> func = (string key) => (!d.TryGetValue("lynx.xp." + key, out value3)) ? null : value3;
			Set(obj, "Name", func("Name"));
			if (func("Colour") != null)
			{
				Set(obj, "Colour", func("Colour"));
			}
			if (func("NetworkOwnerDisplayName") != null)
			{
				Set(obj, "NetworkOwnerDisplayName", func("NetworkOwnerDisplayName"));
			}
			if (long.TryParse(func("NetworkOwnerPlayerId"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
			{
				Set(obj, "NetworkOwnerPlayerId", result);
			}
			if (bool.TryParse(func("IsPrivate"), out var result2))
			{
				Set(obj, "IsPrivate", result2);
			}
			string value;
			ZDOID val = ParseId((!d.TryGetValue("lynx.xp.Target", out value)) ? null : value);
			if (!((ZDOID)(ref val)).IsNone() && Known(val) != null)
			{
				Set(obj, "Target", val);
			}
			updateZdo.Invoke(null, new object[2] { false, obj });
			addOrUpdate.Invoke(null, new object[1] { obj });
			int num = 0;
			string value2;
			ZDOID val2 = ParseId((!d.TryGetValue("lynx.xp.OldId", out value2)) ? null : value2);
			if (!((ZDOID)(ref val2)).IsNone() && !d.ContainsKey("lynx.xp.Relinked"))
			{
				object obj2 = withTarget.Invoke(mgr(), new object[1] { val2 }) as IList;
				IList list = default(IList);
				if (obj2 != null)
				{
					list = (IList)obj2;
					obj2 = list;
				}
				if (obj2 != null)
				{
					foreach (object item in list.Cast<object>().ToList())
					{
						Set(item, "Target", id);
						updateZdo.Invoke(null, new object[2] { false, item });
						addOrUpdate.Invoke(null, new object[1] { item });
						num++;
					}
				}
			}
			d["lynx.xp.Relinked"] = "1";
			Plugin.Log.LogInfo((object)("XPortal crate: restored '" + d["lynx.xp.Name"] + "'" + ((num <= 0) ? string.Empty : $", relinked {num} portal(s)")));
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("XPortal crate: could not restore settings (" + (ex.InnerException ?? ex).Message + ")"));
		}
	}
}
public static class CratePunchFix
{
	private static float blockUntil;

	public static string Apply(Assembly pov)
	{
		//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Expected O, but got Unknown
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		Type typeFromHandle = typeof(CratePunchFix);
		int num = 0;
		string[] array = new string[2] { "PassiveTree.ShipCrate", "PassiveTree.ShipyardCrate" };
		foreach (string name in array)
		{
			Type type = pov.GetType(name, throwOnError: false);
			MethodInfo methodInfo = ((!(type == null)) ? AccessTools.Method(type, "Unpack", (Type[])null, (Type[])null) : null);
			if (!(methodInfo == null))
			{
				Harmony h = Plugin.H;
				MethodInfo methodInfo2 = methodInfo;
				HarmonyMethod val = new HarmonyMethod(typeFromHandle, "Placed", (Type[])null);
				h.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				num++;
			}
		}
		if (num == 0)
		{
			throw new Exception("crate unpack methods missing");
		}
		Plugin.H.Patch((MethodBase)AccessTools.Method(typeof(Humanoid), "StartAttack", new Type[2]
		{
			typeof(Character),
			typeof(bool)
		}, (Type[])null), new HarmonyMethod(typeFromHandle, "NoAttack", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		return "applied";
	}

	private static void Placed()
	{
		blockUntil = Time.time + 0.5f;
	}

	private static bool NoAttack(Humanoid __instance, ref bool __result)
	{
		if (Time.time < blockUntil && (Object)(object)__instance == (Object)(object)Player.m_localPlayer)
		{
			__result = false;
			return false;
		}
		return true;
	}
}
public static class AnySoilFix
{
	private static Func<bool> has;

	private static FieldInfo biomeField;

	public static bool Active()
	{
		try
		{
			return has != null && has();
		}
		catch
		{
			return false;
		}
	}

	public static string Apply(Assembly kv)
	{
		Assembly assembly = ((object)Chainloader.PluginInfos["treextr.pathofvalheiman"].Instance).GetType().Assembly;
		Type type = assembly.GetType("PassiveTree.AnyBiomePlanting", throwOnError: true);
		MethodInfo method = AccessTools.PropertyGetter(type, "Has") ?? throw new Exception("AnyBiomePlanting.Has missing");
		has = (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), method);
		biomeField = AccessTools.Field(kv.GetType("GreydwarfSorter.Farming.Sapling", throwOnError: true), "Biome") ?? throw new Exception("Sapling.Biome missing");
		MethodInfo target = AccessTools.Method(kv.GetType("GreydwarfSorter.Farming.FarmIndex", throwOnError: true), "WhyNot", (Type[])null, (Type[])null);
		MethodInfo target2 = AccessTools.Method(kv.GetType("GreydwarfSorter.Farming.TreeIndex", throwOnError: true), "CanPlant", (Type[])null, (Type[])null);
		Type type2 = kv.GetType("GreydwarfSorter.Worker.SorterAI", throwOnError: true);
		MethodInfo target3 = AccessTools.Method(type2, "PlantOne", (Type[])null, (Type[])null);
		MethodInfo target4 = AccessTools.Method(type2, "PlaceSapling", (Type[])null, (Type[])null);
		int total = 0;
		Plugin.Patch(target, "IgnoreBiome", typeof(AnySoilFix), 2, ref total);
		Plugin.Patch(target2, "IgnoreBiome", typeof(AnySoilFix), 2, ref total);
		Plugin.Patch(target3, "MarkPlanted", typeof(AnySoilFix), 1, ref total);
		Plugin.Patch(target4, "MarkPlanted", typeof(AnySoilFix), 1, ref total);
		return "applied (" + total + " sites)";
	}

	public static Biome Filter(Biome b)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		return (Biome)((!Active()) ? ((int)b) : 0);
	}

	private static IEnumerable<CodeInstruction> IgnoreBiome(IEnumerable<CodeInstruction> ins, MethodBase original)
	{
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Expected O, but got Unknown
		List<CodeInstruction> list = ins.ToList();
		MethodInfo methodInfo = AccessTools.Method(typeof(AnySoilFix), "Filter", (Type[])null, (Type[])null);
		FieldInfo fieldInfo = default(FieldInfo);
		for (int num = list.Count - 1; num >= 0; num--)
		{
			if (list[num].opcode == OpCodes.Ldfld)
			{
				object obj = list[num].operand as FieldInfo;
				if (obj != null)
				{
					fieldInfo = (FieldInfo)obj;
					obj = fieldInfo;
				}
				if (obj != null && fieldInfo == biomeField)
				{
					list.Insert(num + 1, new CodeInstruction(OpCodes.Call, (object)methodInfo));
					Plugin.Hits[original]++;
				}
			}
		}
		return list;
	}

	public static void Mark(Piece p)
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)p) || !Active())
		{
			return;
		}
		Plant component = ((Component)p).GetComponent<Plant>();
		if (Object.op_Implicit((Object)(object)component))
		{
			component.m_biome = (Biome)(-1);
			ZNetView component2 = ((Component)p).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component2) && component2.IsValid())
			{
				component2.GetZDO().Set("pt_anybiome", true);
			}
		}
	}

	private static IEnumerable<CodeInstruction> MarkPlanted(IEnumerable<CodeInstruction> ins, MethodBase original)
	{
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cb: Expected O, but got Unknown
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Expected O, but got Unknown
		List<CodeInstruction> list = ins.ToList();
		MethodInfo methodInfo = AccessTools.Method(typeof(AnySoilFix), "Mark", (Type[])null, (Type[])null);
		FieldInfo fieldInfo = default(FieldInfo);
		for (int i = 2; i < list.Count; i++)
		{
			if (list[i].opcode == OpCodes.Stfld)
			{
				object obj = list[i].operand as FieldInfo;
				if (obj != null)
				{
					fieldInfo = (FieldInfo)obj;
					obj = fieldInfo;
				}
				if (obj != null && fieldInfo.Name == "m_creator" && fieldInfo.DeclaringType == typeof(Piece) && Plugin.IsLd(list[i - 2]))
				{
					list.InsertRange(i + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
					{
						new CodeInstruction(list[i - 2].opcode, list[i - 2].operand),
						new CodeInstruction(OpCodes.Call, (object)methodInfo)
					});
					Plugin.Hits[original]++;
					break;
				}
			}
		}
		return list;
	}
}
public static class GraveCommand
{
	private static Type graveType;

	private static bool registered;

	public static string Apply(Assembly pov)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Expected O, but got Unknown
		graveType = pov.GetType("PassiveTree.Resurrection+Grave", throwOnError: true);
		Harmony h = Plugin.H;
		MethodInfo methodInfo = AccessTools.Method(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null);
		HarmonyMethod val = new HarmonyMethod(typeof(GraveCommand), "Register", (Type[])null);
		h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		Register();
		return "applied";
	}

	private static void Register()
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Expected O, but got Unknown
		if (!registered)
		{
			registered = true;
			new ConsoleCommand("lynx_removegraves", "[radius=10] [all] - delete your PoV companion gravestones near you ('all' = everyone's, admins only)", new ConsoleEvent(Run), false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}
	}

	private static void Run(ConsoleEventArgs args)
	{
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Unknown result type (might be due to invalid IL or missing references)
		Player localPlayer = Player.m_localPlayer;
		if (!Object.op_Implicit((Object)(object)localPlayer))
		{
			args.Context.AddString("No player.");
			return;
		}
		float num = 10f;
		bool flag = false;
		for (int i = 1; i < args.Args.Length; i++)
		{
			float result;
			if (args.Args[i].Equals("all", StringComparison.OrdinalIgnoreCase))
			{
				if (!Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.LocalPlayerIsAdminOrHost())
				{
					args.Context.AddString("'all' is for server admins (adminlist.txt) or the host. Without it, only your own companions' graves are removed.");
					return;
				}
				flag = true;
			}
			else if (float.TryParse(args.Args[i], NumberStyles.Float, CultureInfo.InvariantCulture, out result))
			{
				num = Mathf.Clamp(result, 1f, 200f);
			}
		}
		long playerID = localPlayer.GetPlayerID();
		int num2 = 0;
		int num3 = 0;
		Object[] array = Object.FindObjectsOfType(graveType);
		foreach (Object val in array)
		{
			Component val2 = (Component)(object)((val is Component) ? val : null);
			if (!Object.op_Implicit((Object)(object)val2) || Vector3.Distance(val2.transform.position, ((Component)localPlayer).transform.position) > num)
			{
				continue;
			}
			ZNetView component = val2.GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component) && component.IsValid())
			{
				long num4 = component.GetZDO().GetLong("pt.grave.owner", 0L);
				if (!flag && num4 != playerID)
				{
					num3++;
					continue;
				}
				component.ClaimOwnership();
				ZNetScene.instance.Destroy(val2.gameObject);
				num2++;
			}
		}
		args.Context.AddString($"Removed {num2} companion grave(s) within {num:0} m" + ((num3 <= 0) ? string.Empty : $"; left {num3} belonging to other players (add 'all' to include them)") + ".");
	}
}
public static class PickableCommand
{
	private static bool registered;

	public static void Apply()
	{
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Expected O, but got Unknown
		Harmony h = Plugin.H;
		MethodInfo methodInfo = AccessTools.Method(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null);
		HarmonyMethod val = new HarmonyMethod(typeof(PickableCommand), "Register", (Type[])null);
		h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		Register();
		Plugin.Log.LogInfo((object)"lynx_removepickables command: applied");
	}

	private static void Register()
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Expected O, but got Unknown
		if (!registered)
		{
			registered = true;
			new ConsoleCommand("lynx_removepickables", "<name> [radius=20] - delete pickables (e.g. crab, raspberry) near you whose name contains <name>; they are gone, not just picked", new ConsoleEvent(Run), false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}
	}

	private static void Run(ConsoleEventArgs args)
	{
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		Player localPlayer = Player.m_localPlayer;
		if (!Object.op_Implicit((Object)(object)localPlayer))
		{
			args.Context.AddString("No player.");
			return;
		}
		if (args.Args.Length < 2)
		{
			args.Context.AddString("Usage: lynx_removepickables <name> [radius=20]   e.g. lynx_removepickables crab 30");
			return;
		}
		string text = args.Args[1].ToLowerInvariant();
		float num = 20f;
		if (args.Args.Length > 2 && float.TryParse(args.Args[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
		{
			num = Mathf.Clamp(result, 1f, 100f);
		}
		int num2 = 0;
		Pickable[] array = Object.FindObjectsOfType<Pickable>();
		foreach (Pickable val in array)
		{
			if (!Object.op_Implicit((Object)(object)val) || Vector3.Distance(((Component)val).transform.position, ((Component)localPlayer).transform.position) > num)
			{
				continue;
			}
			string text2 = ((Object)((Component)val).gameObject).name.Replace("(Clone)", string.Empty).ToLowerInvariant();
			string text3 = (((!Object.op_Implicit((Object)(object)val.m_itemPrefab)) ? string.Empty : ((Object)val.m_itemPrefab).name) + " " + (val.GetHoverName() ?? string.Empty)).ToLowerInvariant();
			if (text2.Contains(text) || text3.Contains(text))
			{
				ZNetView component = ((Component)val).GetComponent<ZNetView>();
				if (Object.op_Implicit((Object)(object)component) && component.IsValid())
				{
					component.ClaimOwnership();
					ZNetScene.instance.Destroy(((Component)val).gameObject);
					num2++;
				}
			}
		}
		args.Context.AddString($"Removed {num2} pickable(s) matching '{text}' within {num:0} m.");
	}
}
public static class DrawerPickupFix
{
	public static string Apply(Assembly drawers)
	{
		MethodInfo target = AccessTools.Method(drawers.GetType("ItemDrawers.Game.DrawerManager", throwOnError: true), "RunAutoPickup", (Type[])null, (Type[])null) ?? throw new Exception("DrawerManager.RunAutoPickup missing");
		int total = 0;
		Plugin.Patch(target, "Transpile", typeof(DrawerPickupFix), 1, ref total);
		return "applied";
	}

	private static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> ins, MethodBase original)
	{
		//IL_0160: Unknown result type (might be due to invalid IL or missing references)
		//IL_0166: Expected O, but got Unknown
		//IL_016e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Expected O, but got Unknown
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_0188: Expected O, but got Unknown
		List<CodeInstruction> list = ins.ToList();
		MethodInfo objB = AccessTools.Method(typeof(List<ItemDrop>), "get_Item", (Type[])null, (Type[])null);
		MethodInfo methodInfo = AccessTools.Method(typeof(ItemDrop), "IsPiece", (Type[])null, (Type[])null);
		MethodInfo methodInfo2 = default(MethodInfo);
		for (int i = 0; i + 5 < list.Count; i++)
		{
			if (!(list[i].opcode == OpCodes.Callvirt) || !object.Equals(list[i].operand, objB))
			{
				continue;
			}
			int num = Plugin.LocalIndex(list[i + 1]);
			if (num < 0 || Plugin.LocalIndex(list[i + 2]) != num || list[i + 3].opcode != OpCodes.Ldnull)
			{
				continue;
			}
			object obj = list[i + 4].operand as MethodInfo;
			if (obj != null)
			{
				methodInfo2 = (MethodInfo)obj;
				obj = methodInfo2;
			}
			if (obj != null && methodInfo2.Name == "op_Equality")
			{
				CodeInstruction val = list[i + 5];
				if (!(val.opcode != OpCodes.Brtrue) || !(val.opcode != OpCodes.Brtrue_S))
				{
					list.InsertRange(i + 6, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3]
					{
						new CodeInstruction(list[i + 2].opcode, list[i + 2].operand),
						new CodeInstruction(OpCodes.Callvirt, (object)methodInfo),
						new CodeInstruction(OpCodes.Brtrue, val.operand)
					});
					Plugin.Hits[original]++;
					break;
				}
			}
		}
		return list;
	}
}
public static class EggFix
{
	public static void NoRoof(EggGrow __instance)
	{
		__instance.m_requireUnderRoof = false;
	}
}
public static class CartFix
{
	public static void Removable(Vagon __instance)
	{
		Piece val = ((Component)__instance).GetComponent<Piece>() ?? ((Component)__instance).GetComponentInParent<Piece>();
		if (Object.op_Implicit((Object)(object)val))
		{
			val.m_canBeRemoved = true;
		}
	}
}
public static class GliderFix
{
	internal static string Setting = "Glider_BackPack_Ygg";

	private static readonly HashSet<string> logged = new HashSet<string>();

	private static bool Wanted(string prefab)
	{
		return Setting.Split(',').Any((string s) => s.Trim().Equals(prefab, StringComparison.OrdinalIgnoreCase));
	}

	public static void Apply()
	{
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Invalid comparison between Unknown and I4
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Invalid comparison between Unknown and I4
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Invalid comparison between Unknown and I4
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		ObjectDB instance = ObjectDB.instance;
		if (!Object.op_Implicit((Object)(object)instance) || instance.m_items == null)
		{
			return;
		}
		foreach (GameObject item in instance.m_items)
		{
			if (!Object.op_Implicit((Object)(object)item) || !Wanted(((Object)item).name))
			{
				continue;
			}
			ItemDrop component = item.GetComponent<ItemDrop>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				continue;
			}
			List<DamageModPair> list = component.m_itemData.m_shared.m_damageModifiers ?? (component.m_itemData.m_shared.m_damageModifiers = new List<DamageModPair>());
			int num = list.FindIndex((DamageModPair p) => (int)p.m_type == 64);
			if (num >= 0)
			{
				DamageModifier modifier = list[num].m_modifier;
				if ((int)modifier == 1 || (int)modifier == 5 || (int)modifier == 3)
				{
					continue;
				}
				list[num] = new DamageModPair
				{
					m_type = (DamageType)64,
					m_modifier = (DamageModifier)1
				};
			}
			else
			{
				list.Add(new DamageModPair
				{
					m_type = (DamageType)64,
					m_modifier = (DamageModifier)1
				});
			}
			if (logged.Add(((Object)item).name))
			{
				Plugin.Log.LogInfo((object)("Gliders: " + ((Object)item).name + " is now Frost: Resistant"));
			}
		}
	}
}
public static class KvistPovCategories
{
	private static readonly string[][] Cats = new string[8][]
	{
		new string[5] { "pov_maps", "Maps (PoV)", "PoV_TreasureMap_*", "PT_HallMap*", "PT_DungeonMap" },
		new string[4] { "pov_hall_rooms", "Oath Hall Rooms", "PT_HallRoom_*", "PT_HallRoomU_*" },
		new string[6] { "pov_runic_anvil", "Runic Anvil Stock", "PT_Glyph*", "PT_Alloy*", "PT_AzuriteDust", "PT_DivineAzuriteDust" },
		new string[4] { "pov_essences", "Essences & Brands", "PT_Essence*", "PT_Brand*" },
		new string[4] { "pov_gems", "Skill Gems", "PT_Gem_*", "PT_GemUncut*" },
		new string[4] { "pov_jewels", "Jewels & Sigils", "PT_Jewel_*", "PT_Sigil*" },
		null,
		new string[7] { "pov_scrolls", "Scrolls & Other Runes", "PT_EnchantScroll*", "PT_RuneOf*", "PT_GreatRuneOf*", "PT_RuneOpenGate", "PT_SpentRuneFragment" }
	};

	private static readonly string[] ChestFallback = new string[20]
	{
		"PT_RuneOfCorruption", "PT_RuneOfBloodChallenge", "PT_RuneOfCrimsonSeal", "PT_RuneOfInsight", "PT_GreatRuneOfAwakening", "PT_GreatRuneOfReturn", "PT_RuneOfJarl", "PT_GreatRuneOfOblivion", "PT_GreatRuneOfFate", "PT_GreatRuneOfFirstEssence",
		"PT_RunicPunch", "PT_CorruptedPunch", "PT_DivinePunch", "PT_RuneOfGuise", "PT_RuneOfSpark", "PT_RuneOfWeaving", "PT_RuneOfChange", "PT_RuneOfRenewedTrade", "PT_RuneOfAscent", "PT_BlankRunestone"
	};

	private static string[] chest;

	private static readonly string[][] Extra = new string[4][]
	{
		new string[6] { "ore_coal", "PT_Ore*", "PT_Azurite", "PT_DivineAzurite", "PT_CorruptedAzurite", "PT_AzuriteChunks" },
		new string[2] { "metals_parts", "PT_CorruptedAzuriteDust" },
		new string[2] { "tools", "PT_*Chisel" },
		new string[4] { "valuables_boss", "PT_FirstWardenVisage", "PT_CorruptedWardenVisage", "PT_HallsKey*" }
	};

	private static ConstructorInfo ctor;

	private static FieldInfo fId;

	private static FieldInfo fItems;

	public static string Apply(Assembly kv)
	{
		//IL_025e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0265: Expected O, but got Unknown
		Type type = kv.GetType("GreydwarfSorter.Categories.Category", throwOnError: true);
		ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[3]
		{
			typeof(string),
			typeof(string),
			typeof(string)
		}, null) ?? throw new Exception("Category(id, name, area) missing");
		fId = type.GetField("Id", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new Exception("Category.Id missing");
		fItems = type.GetField("Items", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? throw new Exception("Category.Items missing");
		if (fItems.FieldType != typeof(List<string>))
		{
			throw new Exception("Category.Items changed");
		}
		List<string> list = new List<string>();
		try
		{
			Assembly assembly = ((object)Chainloader.PluginInfos["treextr.pathofvalheiman"].Instance).GetType().Assembly;
			IEnumerable enumerable = assembly.GetType("PassiveTree.RuneChest", throwOnError: true).GetMethod("Slots", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).Invoke(null, null) as IEnumerable;
			FieldInfo field = assembly.GetType("PassiveTree.Runes+Kind", throwOnError: true).GetField("Id");
			string text = default(string);
			foreach (object item in enumerable)
			{
				object obj = field.GetValue(item) as string;
				if (obj != null)
				{
					text = (string)obj;
					obj = text;
				}
				if (obj != null && text.Length > 0)
				{
					list.Add(text);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Kvist: PoV categories: Runic Chest list unavailable (" + ex.Message + "), using the 6.0.8 list"));
		}
		string[] first = new string[2] { "pov_runic_chest", "Runic Chest" };
		object second;
		if (list.Count > 0)
		{
			IEnumerable<string> enumerable2 = list;
			second = enumerable2;
		}
		else
		{
			second = ChestFallback;
		}
		chest = first.Concat((IEnumerable<string>)second).ToArray();
		MethodInfo methodInfo = AccessTools.Method(kv.GetType("GreydwarfSorter.Categories.CategoryYaml", throwOnError: true), "Parse", new Type[1] { typeof(string) }, (Type[])null) ?? throw new Exception("CategoryYaml.Parse missing");
		Harmony h = Plugin.H;
		MethodInfo methodInfo2 = methodInfo;
		HarmonyMethod val = new HarmonyMethod(typeof(KvistPovCategories), "Add", (Type[])null);
		h.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		MethodInfo methodInfo3 = AccessTools.Method(kv.GetType("GreydwarfSorter.Categories.CategoryRegistry", throwOnError: true), "Load", (Type[])null, (Type[])null);
		if (methodInfo3 != null)
		{
			methodInfo3.Invoke(null, null);
		}
		return "applied";
	}

	public static void Add(object __result)
	{
		try
		{
			if (!(__result is IList list))
			{
				return;
			}
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			foreach (object item in list)
			{
				if (fId.GetValue(item) is string key && !dictionary.ContainsKey(key))
				{
					dictionary[key] = item;
				}
			}
			int num = 0;
			for (int i = 0; i < list.Count; i++)
			{
				if (fId.GetValue(list[i]) as string == "valuables_boss")
				{
					num = i + 1;
					break;
				}
			}
			string[][] cats = Cats;
			foreach (string[] array in cats)
			{
				string[] array2 = array ?? chest;
				if (array2 != null && !dictionary.ContainsKey(array2[0]))
				{
					object obj = ctor.Invoke(new object[3]
					{
						array2[0],
						array2[1],
						"PoV"
					});
					((List<string>)fItems.GetValue(obj)).AddRange(array2.Skip(2));
					list.Insert(num++, obj);
				}
			}
			string[][] extra = Extra;
			foreach (string[] array3 in extra)
			{
				if (!dictionary.TryGetValue(array3[0], out var value))
				{
					continue;
				}
				List<string> list2 = (List<string>)fItems.GetValue(value);
				foreach (string item2 in array3.Skip(1))
				{
					if (!list2.Contains(item2))
					{
						list2.Add(item2);
					}
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Kvist: PoV categories: " + ex.Message));
		}
	}
}
public static class KvistPovStores
{
	private enum Kind
	{
		None,
		Anvil,
		Chest
	}

	private static readonly ConditionalWeakTable<Inventory, Container> map = new ConditionalWeakTable<Inventory, Container>();

	private static MethodInfo aIs;

	private static MethodInfo aStockable;

	private static MethodInfo aRaw;

	private static MethodInfo aCopy;

	private static MethodInfo aCommit;

	private static MethodInfo aDamaged;

	private static FieldInfo aBusy;

	private static Type aStore;

	private static MethodInfo rIs;

	private static MethodInfo rCurrency;

	private static MethodInfo rSame;

	private static MethodInfo rPack;

	private static MethodInfo rCopy;

	private static MethodInfo rCommit;

	private static MethodInfo rDamaged;

	private static FieldInfo rBusy;

	private static FieldInfo bCount;

	private static FieldInfo bSample;

	private static FieldInfo bPacked;

	private static Type rStore;

	private static Type rBal;

	private static readonly FieldInfo fInUse = AccessTools.Field(typeof(Container), "m_inUse");

	public static string Apply(Assembly kv)
	{
		return ApplyWith(kv, ((object)Chainloader.PluginInfos["treextr.pathofvalheiman"].Instance).GetType().Assembly);
	}

	internal static string ApplyWith(Assembly kv, Assembly pov)
	{
		//IL_0504: Unknown result type (might be due to invalid IL or missing references)
		//IL_050b: Expected O, but got Unknown
		//IL_0532: Unknown result type (might be due to invalid IL or missing references)
		//IL_0539: Expected O, but got Unknown
		//IL_0560: Unknown result type (might be due to invalid IL or missing references)
		//IL_0567: Expected O, but got Unknown
		//IL_0590: Unknown result type (might be due to invalid IL or missing references)
		//IL_0597: Expected O, but got Unknown
		Type type = pov.GetType("PassiveTree.RunicCraft.Anvil", throwOnError: true);
		aStore = pov.GetType("PassiveTree.RunicCraft.Anvil+Store", throwOnError: true);
		aIs = Req(type.GetMethod("Is", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Container) }, null), "Anvil.Is");
		aStockable = Req(pov.GetType("PassiveTree.RunicCraft.Defs", throwOnError: true).GetMethod("Stockable", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(string) }, null), "Defs.Stockable");
		aBusy = Req(aStore.GetField("Busy", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), "Anvil.Store.Busy");
		aDamaged = Req(aStore.GetProperty("Damaged", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetGetMethod(nonPublic: true), "Anvil.Store.Damaged");
		aRaw = Req(aStore.GetProperty("Raw", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetGetMethod(nonPublic: true), "Anvil.Store.Raw");
		aCopy = Req(aStore.GetMethod("Copy", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null), "Anvil.Store.Copy");
		aCommit = Req(aStore.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo m) => m.Name == "Commit" && m.GetParameters().Length == 2), "Anvil.Store.Commit");
		if (aCopy.ReturnType != typeof(Dictionary<string, long>))
		{
			throw new Exception("Anvil stock format changed");
		}
		Type type2 = pov.GetType("PassiveTree.RuneChest", throwOnError: true);
		rStore = pov.GetType("PassiveTree.RuneChest+Store", throwOnError: true);
		rBal = pov.GetType("PassiveTree.RuneChest+Balance", throwOnError: true);
		rIs = Req(type2.GetMethod("Is", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(Container) }, null), "RuneChest.Is");
		rCurrency = Req(type2.GetMethod("Currency", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(ItemData) }, null), "RuneChest.Currency");
		rSame = Req(type2.GetMethod("SameTemplate", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2]
		{
			typeof(ItemData),
			typeof(ItemData)
		}, null), "RuneChest.SameTemplate");
		rPack = Req(type2.GetMethod("Pack", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(ItemData) }, null), "RuneChest.Pack");
		rBusy = Req(rStore.GetField("Busy", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), "RuneChest.Store.Busy");
		rDamaged = Req(rStore.GetProperty("Damaged", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetGetMethod(nonPublic: true), "RuneChest.Store.Damaged");
		rCopy = Req(rStore.GetMethod("Copy", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null), "RuneChest.Store.Copy");
		rCommit = Req(rStore.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo m) => m.Name == "Commit" && m.GetParameters().Length == 3), "RuneChest.Store.Commit");
		bCount = Req(rBal.GetField("Count", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), "Balance.Count");
		bSample = Req(rBal.GetField("Sample", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), "Balance.Sample");
		bPacked = Req(rBal.GetField("Packed", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), "Balance.Packed");
		if (bCount.FieldType != typeof(BigInteger))
		{
			throw new Exception("Runic Chest balance format changed");
		}
		Type type3 = kv.GetType("GreydwarfSorter.Chests.ChestIndex", throwOnError: true);
		Type type4 = kv.GetType("GreydwarfSorter.Chests.ContainerAccess", throwOnError: true);
		MethodInfo methodInfo = Req(AccessTools.Method(type3, "HasRoom", new Type[2]
		{
			typeof(Container),
			typeof(ItemData)
		}, (Type[])null), "ChestIndex.HasRoom");
		MethodInfo methodInfo2 = Req(AccessTools.Method(type4, "SpaceFor", new Type[2]
		{
			typeof(Inventory),
			typeof(ItemData)
		}, (Type[])null), "ContainerAccess.SpaceFor");
		MethodInfo methodInfo3 = Req(AccessTools.Method(type4, "Move", new Type[5]
		{
			typeof(Inventory),
			typeof(Inventory),
			typeof(ItemData),
			typeof(Vector3),
			typeof(int)
		}, (Type[])null), "ContainerAccess.Move");
		MethodInfo methodInfo4 = Req(AccessTools.Method(type4, "Open", new Type[1] { typeof(Container) }, (Type[])null), "ContainerAccess.Open");
		Type typeFromHandle = typeof(KvistPovStores);
		Harmony h = Plugin.H;
		HarmonyMethod val = new HarmonyMethod(typeFromHandle, "HasRoom", (Type[])null);
		val.priority = 800;
		h.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		Harmony h2 = Plugin.H;
		val = new HarmonyMethod(typeFromHandle, "SpaceFor", (Type[])null);
		val.priority = 800;
		h2.Patch((MethodBase)methodInfo2, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		Harmony h3 = Plugin.H;
		val = new HarmonyMethod(typeFromHandle, "Move", (Type[])null);
		val.priority = 800;
		h3.Patch((MethodBase)methodInfo3, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		Harmony h4 = Plugin.H;
		MethodInfo methodInfo5 = methodInfo4;
		val = new HarmonyMethod(typeFromHandle, "Opened", (Type[])null);
		h4.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		return "applied";
	}

	private static T Req<T>(T v, string what) where T : class
	{
		if (v == null)
		{
			throw new Exception(what + " missing");
		}
		return v;
	}

	private static Kind KindOf(Container c)
	{
		if (!Object.op_Implicit((Object)(object)c))
		{
			return Kind.None;
		}
		try
		{
			if ((bool)aIs.Invoke(null, new object[1] { c }))
			{
				return Kind.Anvil;
			}
			if ((bool)rIs.Invoke(null, new object[1] { c }))
			{
				return Kind.Chest;
			}
		}
		catch
		{
		}
		return Kind.None;
	}

	private static Kind Remember(Container c)
	{
		Kind kind = KindOf(c);
		if (kind != Kind.None)
		{
			Inventory inventory = c.GetInventory();
			if (inventory != null)
			{
				map.Remove(inventory);
				map.Add(inventory, c);
			}
		}
		return kind;
	}

	private static string Name(ItemData it)
	{
		return (!Object.op_Implicit((Object)(object)it?.m_dropPrefab)) ? null : ((Object)it.m_dropPrefab).name;
	}

	private static bool Accepts(Kind k, ItemData it)
	{
		if (it == null || it.m_shared.m_questItem)
		{
			return false;
		}
		string text = Name(it);
		if (text == null)
		{
			return false;
		}
		return k switch
		{
			Kind.Anvil => (bool)aStockable.Invoke(null, new object[1] { text }), 
			Kind.Chest => (bool)rCurrency.Invoke(null, new object[1] { it }), 
			_ => false, 
		};
	}

	private static bool Free(Kind k, Container c)
	{
		Component component = ((Component)c).GetComponent((k != Kind.Anvil) ? rStore : aStore);
		if (!Object.op_Implicit((Object)(object)component))
		{
			return false;
		}
		bool flag = (bool)((k != Kind.Anvil) ? rBusy : aBusy).GetValue(component);
		bool flag2 = (bool)((k != Kind.Anvil) ? rDamaged : aDamaged).Invoke(component, null);
		return !flag && !flag2;
	}

	public static void Opened(Container __0)
	{
		try
		{
			Remember(__0);
		}
		catch
		{
		}
	}

	public static bool HasRoom(Container __0, ItemData __1, ref bool __result)
	{
		try
		{
			Kind kind = Remember(__0);
			if (kind == Kind.None)
			{
				return true;
			}
			__result = Accepts(kind, __1) && Free(kind, __0);
			return false;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Kvist: Runic Anvil/Chest stock: " + ex.Message));
			return true;
		}
	}

	public static bool SpaceFor(Inventory __0, ItemData __1, ref int __result)
	{
		if (__0 == null || !map.TryGetValue(__0, out var value) || !Object.op_Implicit((Object)(object)value))
		{
			return true;
		}
		try
		{
			Kind kind = KindOf(value);
			if (kind == Kind.None)
			{
				return true;
			}
			__result = ((Accepts(kind, __1) && Free(kind, value)) ? __1.m_stack : 0);
			return false;
		}
		catch
		{
			__result = 0;
			return false;
		}
	}

	public static bool Move(Inventory __0, Inventory __1, ItemData __2, int __4, ref int __result)
	{
		if (__1 == null || !map.TryGetValue(__1, out var value) || !Object.op_Implicit((Object)(object)value))
		{
			return true;
		}
		Kind kind = KindOf(value);
		if (kind == Kind.None)
		{
			return true;
		}
		__result = 0;
		try
		{
			if (__0 == null || __2 == null || !__0.ContainsItem(__2) || !Accepts(kind, __2) || !value.IsOwner())
			{
				return false;
			}
			int num = Math.Min(__2.m_stack, _