Decompiled source of HotbarReturn v1.0.0

HotbarReturn.dll

Decompiled 43 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace HotbarReturn;

[BepInPlugin("local.hotbarreturn", "Hotbar Return", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	private sealed class Reservation
	{
		public string DropToken;

		public string Prefab;

		public int Variant;

		public Sprite Icon;

		public ItemData GroundItem;
	}

	private sealed class DropAttempt
	{
		public DropAttempt Previous;

		public Inventory Inventory;

		public ItemData Item;

		public int Slot;

		public ItemDrop Spawn;
	}

	[HarmonyPatch(typeof(Humanoid), "DropItem", new Type[]
	{
		typeof(Inventory),
		typeof(ItemData),
		typeof(int)
	})]
	private static class PlayerDrop
	{
		private static void Prefix(Humanoid __instance, Inventory __0, ItemData __1, int __2, out DropAttempt __state)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer) && __1 != null && __2 >= __1.m_stack)
			{
				Inventory val = __0 ?? __instance.GetInventory();
				Vector2i gridPos = __1.m_gridPos;
				if (SelectInventory(val) && IsHotbar(val, gridPos) && object.ReferenceEquals(val.GetItemAt(gridPos.x, 0), __1))
				{
					__state = new DropAttempt
					{
						Inventory = val,
						Item = __1,
						Slot = gridPos.x,
						Previous = currentDrop
					};
					currentDrop = __state;
				}
			}
		}

		private static void Postfix(bool __result, DropAttempt __state)
		{
			if (!__result || __state == null || !Object.op_Implicit((Object)(object)__state.Spawn) || __state.Inventory.GetItemAt(__state.Slot, 0) != null)
			{
				return;
			}
			ZNetView component = ((Component)__state.Spawn).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component) && component.IsValid() && component.IsOwner())
			{
				string text = Guid.NewGuid().ToString("N");
				component.GetZDO().Set("local.hotbarreturn.drop", text);
				ItemData itemData = __state.Spawn.m_itemData;
				if (Reserved[__state.Slot] == null)
				{
					reservationCount++;
				}
				Reserved[__state.Slot] = new Reservation
				{
					DropToken = text,
					Prefab = Utils.GetPrefabName(((Component)__state.Spawn).gameObject),
					Variant = itemData.m_variant,
					Icon = itemData.GetIcon(),
					GroundItem = itemData
				};
				Save();
			}
		}

		private static void Finalizer(DropAttempt __state)
		{
			if (__state != null)
			{
				currentDrop = __state.Previous;
			}
		}
	}

	[HarmonyPatch(typeof(ItemDrop), "DropItem", new Type[]
	{
		typeof(ItemData),
		typeof(int),
		typeof(Vector3),
		typeof(Quaternion)
	})]
	private static class SpawnedDrop
	{
		private static void Postfix(ItemData __0, ItemDrop __result)
		{
			if (currentDrop != null && object.ReferenceEquals(currentDrop.Item, __0))
			{
				currentDrop.Spawn = __result;
			}
		}
	}

	[HarmonyPatch(typeof(ItemDrop), "Load")]
	private static class LoadedDrop
	{
		private static void Postfix(ItemDrop __instance, ZNetView ___m_nview)
		{
			if (!Object.op_Implicit((Object)(object)Player.m_localPlayer) || !SelectInventory(((Humanoid)Player.m_localPlayer).GetInventory()) || reservationCount == 0 || !Object.op_Implicit((Object)(object)___m_nview) || !___m_nview.IsValid())
			{
				return;
			}
			string text = ___m_nview.GetZDO().GetString("local.hotbarreturn.drop", string.Empty);
			if (text.Length == 0)
			{
				return;
			}
			for (int i = 0; i < 8; i++)
			{
				Reservation reservation = Reserved[i];
				if (reservation != null && !(reservation.DropToken != text))
				{
					reservation.GroundItem = __instance.m_itemData;
					break;
				}
			}
		}
	}

	[HarmonyPatch(typeof(Inventory), "FindEmptySlot")]
	private static class FindSpace
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> source)
		{
			return ReplaceCalls(source, ItemAt, AccessTools.Method(typeof(FindSpace), "IsOccupied", (Type[])null, (Type[])null), passItem: false, 2);
		}

		private static bool IsOccupied(Inventory inventory, int x, int y)
		{
			if (inventory.GetItemAt(x, y) == null)
			{
				if (y == 0 && x >= 0 && x < 8 && SelectInventory(inventory))
				{
					return Reserved[x] != null;
				}
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })]
	private static class AddPickup
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> source)
		{
			IEnumerable<CodeInstruction> source2 = ReplaceCalls(source, EmptySlot, AccessTools.Method(typeof(AddPickup), "GetPlacement", (Type[])null, (Type[])null), passItem: true, 2);
			return ReplaceCalls(source2, FreeStack, AccessTools.Method(typeof(AddPickup), "GetStack", (Type[])null, (Type[])null), passItem: true, 1);
		}

		private static Vector2i GetPlacement(Inventory inventory, bool topFirst, ItemData item)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!IsEmptyReturnSlot(inventory, item, out var slot))
			{
				return findEmptySlot(inventory, topFirst);
			}
			return new Vector2i(slot, 0);
		}

		private static ItemData GetStack(Inventory inventory, string name, int quality, float worldLevel, ItemData item)
		{
			if (!IsEmptyReturnSlot(inventory, item, out var _))
			{
				return findFreeStack(inventory, name, quality, worldLevel);
			}
			return null;
		}

		[HarmonyPriority(0)]
		private static void Postfix(Inventory __instance, ItemData __0, bool __result)
		{
			if (__result)
			{
				int num = ReturningSlot(__instance, __0);
				if (num >= 0 && object.ReferenceEquals(__instance.GetItemAt(num, 0), __0))
				{
					Clear(num);
				}
			}
		}
	}

	[HarmonyPatch(typeof(Inventory), "CanAddItem", new Type[]
	{
		typeof(ItemData),
		typeof(int)
	})]
	private static class Capacity
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> source)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(source);
			FieldInfo fieldInfo = AccessTools.Field(typeof(Inventory), "m_inventory");
			for (int i = 1; i < list.Count; i++)
			{
				if (CodeInstructionExtensions.LoadsField(list[i - 1], fieldInfo, false) && CodeInstructionExtensions.Calls(list[i], AccessTools.PropertyGetter(typeof(List<ItemData>), "Count")))
				{
					list.InsertRange(i + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4]
					{
						new CodeInstruction(OpCodes.Ldarg_0, (object)null),
						new CodeInstruction(OpCodes.Ldarg_1, (object)null),
						new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Plugin), "CountReservedSpace", (Type[])null, (Type[])null)),
						new CodeInstruction(OpCodes.Add, (object)null)
					});
					return list;
				}
			}
			throw new InvalidOperationException("Could not find the item count in Inventory.CanAddItem.");
		}
	}

	[HarmonyPatch(typeof(Inventory), "GetEmptySlots")]
	private static class EmptyCount
	{
		[HarmonyPriority(0)]
		[HarmonyAfter(new string[] { "randyknapp.mods.equipmentandquickslots" })]
		private static void Postfix(Inventory __instance, ref int __result)
		{
			int num = CountReservedSpace(__instance, null);
			if (num != 0)
			{
				__result = Math.Max(0, __result - num);
			}
		}
	}

	[HarmonyPatch(typeof(Inventory), "HaveEmptySlot")]
	private static class HaveSpace
	{
		[HarmonyPriority(0)]
		[HarmonyAfter(new string[] { "randyknapp.mods.equipmentandquickslots" })]
		private static void Postfix(Inventory __instance, ref bool __result)
		{
			if (__result && CountReservedSpace(__instance, null) != 0)
			{
				__result = __instance.GetEmptySlots() > 0;
			}
		}
	}

	[HarmonyPatch(typeof(InventoryGrid), "DropItem")]
	private static class ExplicitPlacement
	{
		private static void Postfix(Inventory ___m_inventory, Vector2i __3, bool __result)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if (__result && SelectInventory(___m_inventory) && IsHotbar(___m_inventory, __3) && ___m_inventory.GetItemAt(__3.x, 0) != null)
			{
				Clear(__3.x);
			}
		}
	}

	[HarmonyPatch(typeof(HotkeyBar), "UpdateIcons")]
	private static class DrawBar
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> source)
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Expected O, but got Unknown
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(source);
			MethodInfo methodInfo = AccessTools.PropertyGetter(BarElements.FieldType, "Count");
			for (int i = 2; i < list.Count - 2; i++)
			{
				if (CodeInstructionExtensions.LoadsField(list[i - 1], BarElements, false) && CodeInstructionExtensions.Calls(list[i], methodInfo) && !(list[i + 1].opcode != OpCodes.Ldloc_1) && (!(list[i + 2].opcode != OpCodes.Beq) || !(list[i + 2].opcode != OpCodes.Beq_S)))
				{
					list.InsertRange(i + 2, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4]
					{
						new CodeInstruction(OpCodes.Ldarg_0, (object)null),
						new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(DrawBar), "ExtendToReservedSlot", (Type[])null, (Type[])null)),
						new CodeInstruction(OpCodes.Dup, (object)null),
						new CodeInstruction(OpCodes.Stloc_1, (object)null)
					});
					return list;
				}
			}
			throw new InvalidOperationException("Could not find the slot count in HotkeyBar.UpdateIcons.");
		}

		private static bool IsNumberedBar(HotkeyBar bar)
		{
			return ((Object)bar).name == "HotKeyBar";
		}

		private static int ExtendToReservedSlot(int count, HotkeyBar bar)
		{
			if (!IsNumberedBar(bar) || !Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				return count;
			}
			Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory();
			if (!SelectInventory(inventory) || reservationCount == 0)
			{
				return count;
			}
			for (int num = Math.Min(8, inventory.GetWidth()) - 1; num >= count; num--)
			{
				if (Reserved[num] != null)
				{
					return num + 1;
				}
			}
			return count;
		}

		[HarmonyPriority(0)]
		private static void Postfix(HotkeyBar __instance, Player __0)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			if (!IsNumberedBar(__instance) || !Object.op_Implicit((Object)(object)__0) || (Object)(object)__0 != (Object)(object)Player.m_localPlayer || ((Character)__0).IsDead())
			{
				return;
			}
			Inventory inventory = ((Humanoid)__0).GetInventory();
			if (!SelectInventory(inventory))
			{
				return;
			}
			IList list = (IList)BarElements.GetValue(__instance);
			for (int i = 0; i < Math.Min(8, list.Count); i++)
			{
				Image val = (Image)ElementIcon.GetValue(list[i]);
				if (!Object.op_Implicit((Object)(object)val))
				{
					continue;
				}
				Transform val2 = ((Component)val).transform.parent.Find("HotbarReturnGhost");
				Reservation reservation = Reserved[i];
				Sprite val3 = ((reservation != null && inventory.GetItemAt(i, 0) == null) ? ResolveIcon(reservation) : null);
				if (!Object.op_Implicit((Object)(object)val3))
				{
					if (Object.op_Implicit((Object)(object)val2) && ((Component)val2).gameObject.activeSelf)
					{
						((Component)val2).gameObject.SetActive(false);
					}
					continue;
				}
				Image val4 = (Object.op_Implicit((Object)(object)val2) ? ((Component)val2).GetComponent<Image>() : CreateGhost(val));
				val4.sprite = val3;
				if (!((Component)val4).gameObject.activeSelf)
				{
					((Component)val4).gameObject.SetActive(true);
				}
			}
		}

		private static Sprite ResolveIcon(Reservation reservation)
		{
			if (Object.op_Implicit((Object)(object)reservation.Icon) || !Object.op_Implicit((Object)(object)ObjectDB.instance))
			{
				return reservation.Icon;
			}
			GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(reservation.Prefab);
			ItemDrop val = (Object.op_Implicit((Object)(object)itemPrefab) ? itemPrefab.GetComponent<ItemDrop>() : null);
			if (Object.op_Implicit((Object)(object)val) && val.m_itemData.m_shared.m_icons != null && reservation.Variant < val.m_itemData.m_shared.m_icons.Length)
			{
				reservation.Icon = val.m_itemData.m_shared.m_icons[reservation.Variant];
			}
			return reservation.Icon;
		}

		private static Image CreateGhost(Image original)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			RectTransform rectTransform = ((Graphic)original).rectTransform;
			GameObject val = new GameObject("HotbarReturnGhost", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			RectTransform val2 = (RectTransform)val.transform;
			((Transform)val2).SetParent(((Transform)rectTransform).parent, false);
			((Transform)val2).SetSiblingIndex(((Transform)rectTransform).GetSiblingIndex());
			val2.anchorMin = rectTransform.anchorMin;
			val2.anchorMax = rectTransform.anchorMax;
			val2.pivot = rectTransform.pivot;
			val2.sizeDelta = rectTransform.sizeDelta;
			val2.anchoredPosition3D = rectTransform.anchoredPosition3D;
			((Transform)val2).localRotation = ((Transform)rectTransform).localRotation;
			((Transform)val2).localScale = ((Transform)rectTransform).localScale;
			Image component = val.GetComponent<Image>();
			((Graphic)component).color = new Color(1f, 1f, 1f, 0.35f);
			component.preserveAspect = original.preserveAspect;
			((Graphic)component).raycastTarget = false;
			return component;
		}
	}

	private const string Id = "local.hotbarreturn";

	private const string QuickSlots = "randyknapp.mods.equipmentandquickslots";

	private const int Slots = 8;

	private const float GhostOpacity = 0.35f;

	private const string GhostName = "HotbarReturnGhost";

	private const string DropKey = "local.hotbarreturn.drop";

	private static readonly Reservation[] Reserved = new Reservation[8];

	private static readonly MethodInfo ItemAt = AccessTools.Method(typeof(Inventory), "GetItemAt", (Type[])null, (Type[])null);

	private static readonly MethodInfo EmptySlot = AccessTools.Method(typeof(Inventory), "FindEmptySlot", (Type[])null, (Type[])null);

	private static readonly MethodInfo FreeStack = AccessTools.Method(typeof(Inventory), "FindFreeStackItem", (Type[])null, (Type[])null);

	private static readonly FieldInfo BarElements = AccessTools.Field(typeof(HotkeyBar), "m_elements");

	private static readonly FieldInfo ElementIcon = AccessTools.Field(BarElements.FieldType.GetGenericArguments()[0], "m_icon");

	private static Func<Inventory, bool, Vector2i> findEmptySlot;

	private static Func<Inventory, string, int, float, ItemData> findFreeStack;

	private static ManualLogSource log;

	private static bool ready;

	private static int reservationCount;

	private static string activeFile;

	private static DropAttempt currentDrop;

	private static Inventory activeInventory;

	private static Player activePlayer;

	private void Awake()
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Expected O, but got Unknown
		log = ((BaseUnityPlugin)this).Logger;
		Harmony val = new Harmony("local.hotbarreturn");
		try
		{
			val.PatchAll(typeof(Plugin).Assembly);
			findEmptySlot = (Func<Inventory, bool, Vector2i>)EmptySlot.CreateDelegate(typeof(Func<Inventory, bool, Vector2i>));
			findFreeStack = (Func<Inventory, string, int, float, ItemData>)FreeStack.CreateDelegate(typeof(Func<Inventory, string, int, float, ItemData>));
			ready = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Hotbar Return is ready for numbered hotbar slots 1–8.");
		}
		catch (Exception ex)
		{
			val.UnpatchSelf();
			((BaseUnityPlugin)this).Logger.LogError((object)("Hotbar Return could not start. " + ex));
		}
	}

	private static bool IsLocal(Inventory inventory)
	{
		if (ready && Object.op_Implicit((Object)(object)Player.m_localPlayer))
		{
			return inventory == ((Humanoid)Player.m_localPlayer).GetInventory();
		}
		return false;
	}

	private static bool IsHotbar(Inventory inventory, Vector2i position)
	{
		if (position.y == 0 && position.x >= 0 && position.x < 8)
		{
			return position.x < inventory.GetWidth();
		}
		return false;
	}

	private static bool SelectInventory(Inventory inventory)
	{
		if (!IsLocal(inventory))
		{
			return false;
		}
		if (activeInventory == inventory && (Object)(object)activePlayer == (Object)(object)Player.m_localPlayer)
		{
			return true;
		}
		if (!Object.op_Implicit((Object)(object)Game.instance) || Game.instance.GetPlayerProfile() == null || !Object.op_Implicit((Object)(object)ZNet.instance) || ZNet.instance.GetWorld() == null)
		{
			return false;
		}
		long worldUID = ZNet.instance.GetWorldUID();
		long playerID = Game.instance.GetPlayerProfile().GetPlayerID();
		string text = Path.Combine(Paths.ConfigPath, "local.hotbarreturn", string.Format(CultureInfo.InvariantCulture, "{0}_{1}.txt", playerID, worldUID));
		activeInventory = inventory;
		activePlayer = Player.m_localPlayer;
		if (text == activeFile)
		{
			return true;
		}
		activeFile = text;
		Array.Clear(Reserved, 0, Reserved.Length);
		reservationCount = 0;
		try
		{
			if (File.Exists(text))
			{
				foreach (string item in File.ReadLines(text))
				{
					string[] array = item.Split('\t');
					if (array.Length == 4 && int.TryParse(array[0], out var result) && Guid.TryParseExact(array[1], "N", out var _) && int.TryParse(array[2], out var result3) && result >= 0 && result < 8 && result3 >= 0 && array[3].Length != 0 && Reserved[result] == null && inventory.GetItemAt(result, 0) == null)
					{
						Reserved[result] = new Reservation
						{
							DropToken = array[1],
							Variant = result3,
							Prefab = array[3]
						};
						reservationCount++;
					}
				}
			}
		}
		catch (Exception ex)
		{
			log.LogWarning((object)("Could not read saved hotbar reservations. " + ex.Message));
		}
		return true;
	}

	private static void Save()
	{
		try
		{
			Directory.CreateDirectory(Path.GetDirectoryName(activeFile));
			List<string> list = new List<string>();
			for (int i = 0; i < 8; i++)
			{
				Reservation reservation = Reserved[i];
				if (reservation != null)
				{
					list.Add(string.Format(CultureInfo.InvariantCulture, "{0}\t{1}\t{2}\t{3}", i, reservation.DropToken, reservation.Variant, reservation.Prefab));
				}
			}
			string text = activeFile + ".tmp";
			File.WriteAllLines(text, list.ToArray());
			if (File.Exists(activeFile))
			{
				File.Replace(text, activeFile, null);
			}
			else
			{
				File.Move(text, activeFile);
			}
		}
		catch (Exception ex)
		{
			log.LogWarning((object)("Could not save hotbar reservations. " + ex.Message));
		}
	}

	private static void Clear(int slot)
	{
		if (Reserved[slot] != null)
		{
			Reserved[slot] = null;
			reservationCount--;
			Save();
		}
	}

	private static int ReturningSlot(Inventory inventory, ItemData item)
	{
		if (item == null || !SelectInventory(inventory) || reservationCount == 0)
		{
			return -1;
		}
		for (int i = 0; i < Math.Min(8, inventory.GetWidth()); i++)
		{
			Reservation reservation = Reserved[i];
			if (reservation != null && object.ReferenceEquals(reservation.GroundItem, item))
			{
				return i;
			}
		}
		return -1;
	}

	private static bool IsEmptyReturnSlot(Inventory inventory, ItemData item, out int slot)
	{
		slot = ReturningSlot(inventory, item);
		if (slot >= 0)
		{
			return inventory.GetItemAt(slot, 0) == null;
		}
		return false;
	}

	private static int CountReservedSpace(Inventory inventory, ItemData except)
	{
		if (!SelectInventory(inventory) || reservationCount == 0)
		{
			return 0;
		}
		int num = 0;
		for (int i = 0; i < Math.Min(8, inventory.GetWidth()); i++)
		{
			Reservation reservation = Reserved[i];
			if (reservation != null && (except == null || !object.ReferenceEquals(reservation.GroundItem, except)) && inventory.GetItemAt(i, 0) == null)
			{
				num++;
			}
		}
		return num;
	}

	private static IEnumerable<CodeInstruction> ReplaceCalls(IEnumerable<CodeInstruction> source, MethodInfo original, MethodInfo replacement, bool passItem, int expected)
	{
		int matches = 0;
		foreach (CodeInstruction instruction in source)
		{
			if (!CodeInstructionExtensions.Calls(instruction, original))
			{
				yield return instruction;
				continue;
			}
			matches++;
			if (passItem)
			{
				CodeInstruction arg = new CodeInstruction(OpCodes.Ldarg_1, (object)null);
				arg.labels.AddRange(instruction.labels);
				instruction.labels.Clear();
				yield return arg;
			}
			instruction.opcode = OpCodes.Call;
			instruction.operand = replacement;
			yield return instruction;
		}
		if (matches != expected)
		{
			throw new InvalidOperationException("Unexpected call count for " + original.Name + ": " + matches);
		}
	}
}