Decompiled source of ModpackUpdate v0.8.5

FrozenDevv-ModPack-1.1.0/BepInEx/core/0Harmony.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using HarmonyLib.Internal.Patching;
using HarmonyLib.Internal.RuntimeFixes;
using HarmonyLib.Internal.Util;
using HarmonyLib.Public.Patching;
using HarmonyLib.Tools;
using JetBrains.Annotations;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.Utils;
using MonoMod.Utils.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("HarmonyTests")]
[assembly: InternalsVisibleTo("MonoMod.Utils.Cil.ILGeneratorProxy")]
[assembly: Guid("69aee16a-b6e7-4642-8081-3928b32455df")]
[assembly: AssemblyCompany("BepInEx")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © BepInEx 2022")]
[assembly: AssemblyDescription("A library for patching, replacing and decorating .NET and Mono methods during runtime powered by MonoMod.")]
[assembly: AssemblyFileVersion("2.9.0.0")]
[assembly: AssemblyInformationalVersion("2.9.0")]
[assembly: AssemblyProduct("HarmonyX")]
[assembly: AssemblyTitle("0Harmony")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.9.0.0")]
[module: UnverifiableCode]
namespace System
{
	internal struct ValueTuple<T1, T2>
	{
		public T1 Item1;

		public T2 Item2;

		public ValueTuple(T1 first, T2 second)
		{
			Item1 = first;
			Item2 = second;
		}
	}
	internal struct ValueTuple<T1, T2, T3>
	{
		public T1 Item1;

		public T2 Item2;

		public T3 Item3;

		public ValueTuple(T1 first, T2 second, T3 third)
		{
			Item1 = first;
			Item2 = second;
			Item3 = third;
		}
	}
}
namespace JetBrains.Annotations
{
	[AttributeUsage(AttributeTargets.All)]
	internal sealed class UsedImplicitlyAttribute : Attribute
	{
		public ImplicitUseKindFlags UseKindFlags { get; }

		public ImplicitUseTargetFlags TargetFlags { get; }

		public UsedImplicitlyAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter | AttributeTargets.GenericParameter)]
	internal sealed class MeansImplicitUseAttribute : Attribute
	{
		[UsedImplicitly]
		public ImplicitUseKindFlags UseKindFlags { get; }

		[UsedImplicitly]
		public ImplicitUseTargetFlags TargetFlags { get; }

		public MeansImplicitUseAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[Flags]
	internal enum ImplicitUseKindFlags
	{
		Default = 7,
		Access = 1,
		Assign = 2,
		InstantiatedWithFixedConstructorSignature = 4,
		InstantiatedNoFixedConstructorSignature = 8
	}
	[Flags]
	internal enum ImplicitUseTargetFlags
	{
		Default = 1,
		Itself = 1,
		Members = 2,
		WithInheritors = 4,
		WithMembers = 3
	}
}
namespace HarmonyLib
{
	public class DelegateTypeFactory
	{
		private class DelegateEntry
		{
			public CallingConvention? callingConvention;

			public Type delegateType;
		}

		private static int counter;

		private static readonly Dictionary<MethodInfo, List<DelegateEntry>> TypeCache = new Dictionary<MethodInfo, List<DelegateEntry>>();

		private static readonly MethodBase CallingConvAttr = AccessTools.Constructor(typeof(UnmanagedFunctionPointerAttribute), new Type[1] { typeof(CallingConvention) });

		public static readonly DelegateTypeFactory instance = new DelegateTypeFactory();

		public Type CreateDelegateType(Type returnType, Type[] argTypes)
		{
			return CreateDelegateType(returnType, argTypes, null);
		}

		public Type CreateDelegateType(Type returnType, Type[] argTypes, CallingConvention? convention)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Expected O, but got Unknown
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			counter++;
			AssemblyDefinition val = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition($"HarmonyDTFAssembly{counter}", new Version(1, 0)), $"HarmonyDTFModule{counter}", (ModuleKind)0);
			ModuleDefinition module = val.MainModule;
			TypeDefinition val2 = new TypeDefinition("", $"HarmonyDTFType{counter}", (TypeAttributes)257)
			{
				BaseType = module.ImportReference(typeof(MulticastDelegate))
			};
			module.Types.Add(val2);
			if (convention.HasValue)
			{
				CustomAttribute val3 = new CustomAttribute(module.ImportReference(CallingConvAttr));
				val3.ConstructorArguments.Add(new CustomAttributeArgument(module.ImportReference(typeof(CallingConvention)), (object)convention.Value));
				val2.CustomAttributes.Add(val3);
			}
			MethodDefinition val4 = new MethodDefinition(".ctor", (MethodAttributes)4230, module.ImportReference(typeof(void)))
			{
				ImplAttributes = (MethodImplAttributes)3
			};
			Extensions.AddRange<ParameterDefinition>(((MethodReference)val4).Parameters, (IEnumerable<ParameterDefinition>)(object)new ParameterDefinition[2]
			{
				new ParameterDefinition(module.ImportReference(typeof(object))),
				new ParameterDefinition(module.ImportReference(typeof(IntPtr)))
			});
			val2.Methods.Add(val4);
			MethodDefinition val5 = new MethodDefinition("Invoke", (MethodAttributes)198, module.ImportReference(returnType))
			{
				ImplAttributes = (MethodImplAttributes)3
			};
			Extensions.AddRange<ParameterDefinition>(((MethodReference)val5).Parameters, ((IEnumerable<Type>)argTypes).Select((Func<Type, ParameterDefinition>)((Type t) => new ParameterDefinition(module.ImportReference(t)))));
			val2.Methods.Add(val5);
			return ReflectionHelper.Load(val.MainModule).GetType($"HarmonyDTFType{counter}");
		}

		public Type CreateDelegateType(MethodInfo method)
		{
			return CreateDelegateType(method, null);
		}

		public Type CreateDelegateType(MethodInfo method, CallingConvention? convention)
		{
			DelegateEntry delegateEntry;
			if (TypeCache.TryGetValue(method, out var value) && (delegateEntry = value.FirstOrDefault((DelegateEntry e) => e.callingConvention == convention)) != null)
			{
				return delegateEntry.delegateType;
			}
			if (value == null)
			{
				value = (TypeCache[method] = new List<DelegateEntry>());
			}
			delegateEntry = new DelegateEntry
			{
				delegateType = CreateDelegateType(method.ReturnType, method.GetParameters().Types().ToArray(), convention),
				callingConvention = convention
			};
			value.Add(delegateEntry);
			return delegateEntry.delegateType;
		}
	}
	[Obsolete("Use AccessTools.FieldRefAccess<T, S> for fields and AccessTools.MethodDelegate<Func<T, S>> for property getters")]
	public delegate S GetterHandler<in T, out S>(T source);
	[Obsolete("Use AccessTools.FieldRefAccess<T, S> for fields and AccessTools.MethodDelegate<Action<T, S>> for property setters")]
	public delegate void SetterHandler<in T, in S>(T source, S value);
	public delegate T InstantiationHandler<out T>();
	public static class FastAccess
	{
		public static InstantiationHandler<T> CreateInstantiationHandler<T>()
		{
			//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)
			ConstructorInfo constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
			if ((object)constructor == null)
			{
				throw new ApplicationException($"The type {typeof(T)} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).");
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition("InstantiateObject_" + typeof(T).Name, typeof(T), (Type[])null);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Newobj, constructor);
			iLGenerator.Emit(OpCodes.Ret);
			return (InstantiationHandler<T>)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(InstantiationHandler<T>));
		}

		[Obsolete("Use AccessTools.MethodDelegate<Func<T, S>>(PropertyInfo.GetGetMethod(true))")]
		public static GetterHandler<T, S> CreateGetterHandler<T, S>(PropertyInfo propertyInfo)
		{
			MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true);
			DynamicMethodDefinition obj = CreateGetDynamicMethod<T, S>(propertyInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Call, getMethod);
			iLGenerator.Emit(OpCodes.Ret);
			return (GetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(GetterHandler<T, S>));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")]
		public static GetterHandler<T, S> CreateGetterHandler<T, S>(FieldInfo fieldInfo)
		{
			DynamicMethodDefinition obj = CreateGetDynamicMethod<T, S>(fieldInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldfld, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return (GetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(GetterHandler<T, S>));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(name) for fields and AccessTools.MethodDelegate<Func<T, S>>(AccessTools.PropertyGetter(typeof(T), name)) for properties")]
		public static GetterHandler<T, S> CreateFieldGetter<T, S>(params string[] names)
		{
			foreach (string name in names)
			{
				FieldInfo field = typeof(T).GetField(name, AccessTools.all);
				if ((object)field != null)
				{
					return CreateGetterHandler<T, S>(field);
				}
				PropertyInfo property = typeof(T).GetProperty(name, AccessTools.all);
				if ((object)property != null)
				{
					return CreateGetterHandler<T, S>(property);
				}
			}
			return null;
		}

		[Obsolete("Use AccessTools.MethodDelegate<Action<T, S>>(PropertyInfo.GetSetMethod(true))")]
		public static SetterHandler<T, S> CreateSetterHandler<T, S>(PropertyInfo propertyInfo)
		{
			MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
			DynamicMethodDefinition obj = CreateSetDynamicMethod<T, S>(propertyInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Call, setMethod);
			iLGenerator.Emit(OpCodes.Ret);
			return (SetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(SetterHandler<T, S>));
		}

		[Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")]
		public static SetterHandler<T, S> CreateSetterHandler<T, S>(FieldInfo fieldInfo)
		{
			DynamicMethodDefinition obj = CreateSetDynamicMethod<T, S>(fieldInfo.DeclaringType);
			ILGenerator iLGenerator = obj.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Stfld, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return (SetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(SetterHandler<T, S>));
		}

		private static DynamicMethodDefinition CreateGetDynamicMethod<T, S>(Type type)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			return new DynamicMethodDefinition("DynamicGet_" + type.Name, typeof(S), new Type[1] { typeof(T) });
		}

		private static DynamicMethodDefinition CreateSetDynamicMethod<T, S>(Type type)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			return new DynamicMethodDefinition("DynamicSet_" + type.Name, typeof(void), new Type[2]
			{
				typeof(T),
				typeof(S)
			});
		}
	}
	public delegate object FastInvokeHandler(object target, params object[] parameters);
	public static class MethodInvoker
	{
		public static FastInvokeHandler GetHandler(MethodInfo methodInfo, bool directBoxValueAccess = false)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			DynamicMethodDefinition val = new DynamicMethodDefinition("FastInvoke_" + methodInfo.Name + "_" + (directBoxValueAccess ? "direct" : "indirect"), typeof(object), new Type[2]
			{
				typeof(object),
				typeof(object[])
			});
			ILGenerator iLGenerator = val.GetILGenerator();
			if (!methodInfo.IsStatic)
			{
				Emit(iLGenerator, OpCodes.Ldarg_0);
				EmitUnboxIfNeeded(iLGenerator, methodInfo.DeclaringType);
			}
			bool flag = true;
			ParameterInfo[] parameters = methodInfo.GetParameters();
			for (int i = 0; i < parameters.Length; i++)
			{
				Type type = parameters[i].ParameterType;
				bool isByRef = type.IsByRef;
				if (isByRef)
				{
					type = type.GetElementType();
				}
				bool isValueType = type.IsValueType;
				if (isByRef && isValueType && !directBoxValueAccess)
				{
					Emit(iLGenerator, OpCodes.Ldarg_1);
					EmitFastInt(iLGenerator, i);
				}
				Emit(iLGenerator, OpCodes.Ldarg_1);
				EmitFastInt(iLGenerator, i);
				if (isByRef && !isValueType)
				{
					Emit(iLGenerator, OpCodes.Ldelema, typeof(object));
					continue;
				}
				Emit(iLGenerator, OpCodes.Ldelem_Ref);
				if (!isValueType)
				{
					continue;
				}
				if (!isByRef || !directBoxValueAccess)
				{
					Emit(iLGenerator, OpCodes.Unbox_Any, type);
					if (isByRef)
					{
						Emit(iLGenerator, OpCodes.Box, type);
						Emit(iLGenerator, OpCodes.Dup);
						if (flag)
						{
							flag = false;
							iLGenerator.DeclareLocal(typeof(object), pinned: false);
						}
						Emit(iLGenerator, OpCodes.Stloc_0);
						Emit(iLGenerator, OpCodes.Stelem_Ref);
						Emit(iLGenerator, OpCodes.Ldloc_0);
						Emit(iLGenerator, OpCodes.Unbox, type);
					}
				}
				else
				{
					Emit(iLGenerator, OpCodes.Unbox, type);
				}
			}
			if (methodInfo.IsStatic)
			{
				EmitCall(iLGenerator, OpCodes.Call, methodInfo);
			}
			else
			{
				EmitCall(iLGenerator, OpCodes.Callvirt, methodInfo);
			}
			if ((object)methodInfo.ReturnType == typeof(void))
			{
				Emit(iLGenerator, OpCodes.Ldnull);
			}
			else
			{
				EmitBoxIfNeeded(iLGenerator, methodInfo.ReturnType);
			}
			Emit(iLGenerator, OpCodes.Ret);
			return (FastInvokeHandler)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(FastInvokeHandler));
		}

		internal static void Emit(ILGenerator il, OpCode opcode)
		{
			il.Emit(opcode);
		}

		internal static void Emit(ILGenerator il, OpCode opcode, Type type)
		{
			il.Emit(opcode, type);
		}

		internal static void EmitCall(ILGenerator il, OpCode opcode, MethodInfo methodInfo)
		{
			il.EmitCall(opcode, methodInfo, null);
		}

		private static void EmitUnboxIfNeeded(ILGenerator il, Type type)
		{
			if (type.IsValueType)
			{
				Emit(il, OpCodes.Unbox_Any, type);
			}
		}

		private static void EmitBoxIfNeeded(ILGenerator il, Type type)
		{
			if (type.IsValueType)
			{
				Emit(il, OpCodes.Box, type);
			}
		}

		internal static void EmitFastInt(ILGenerator il, int value)
		{
			switch (value)
			{
			case -1:
				il.Emit(OpCodes.Ldc_I4_M1);
				return;
			case 0:
				il.Emit(OpCodes.Ldc_I4_0);
				return;
			case 1:
				il.Emit(OpCodes.Ldc_I4_1);
				return;
			case 2:
				il.Emit(OpCodes.Ldc_I4_2);
				return;
			case 3:
				il.Emit(OpCodes.Ldc_I4_3);
				return;
			case 4:
				il.Emit(OpCodes.Ldc_I4_4);
				return;
			case 5:
				il.Emit(OpCodes.Ldc_I4_5);
				return;
			case 6:
				il.Emit(OpCodes.Ldc_I4_6);
				return;
			case 7:
				il.Emit(OpCodes.Ldc_I4_7);
				return;
			case 8:
				il.Emit(OpCodes.Ldc_I4_8);
				return;
			}
			if (value > -129 && value < 128)
			{
				il.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
			}
			else
			{
				il.Emit(OpCodes.Ldc_I4, value);
			}
		}
	}
	internal class AccessCache
	{
		internal enum MemberType
		{
			Any,
			Static,
			Instance
		}

		private const BindingFlags BasicFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty;

		private static readonly Dictionary<MemberType, BindingFlags> declaredOnlyBindingFlags = new Dictionary<MemberType, BindingFlags>
		{
			{
				MemberType.Any,
				BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty
			},
			{
				MemberType.Instance,
				BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty
			},
			{
				MemberType.Static,
				BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty
			}
		};

		private readonly Dictionary<Type, Dictionary<string, FieldInfo>> declaredFields = new Dictionary<Type, Dictionary<string, FieldInfo>>();

		private readonly Dictionary<Type, Dictionary<string, PropertyInfo>> declaredProperties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();

		private readonly Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>> declaredMethods = new Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>>();

		private readonly Dictionary<Type, Dictionary<string, FieldInfo>> inheritedFields = new Dictionary<Type, Dictionary<string, FieldInfo>>();

		private readonly Dictionary<Type, Dictionary<string, PropertyInfo>> inheritedProperties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();

		private readonly Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>> inheritedMethods = new Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>>();

		private static T Get<T>(Dictionary<Type, Dictionary<string, T>> dict, Type type, string name, Func<T> fetcher)
		{
			lock (dict)
			{
				if (!dict.TryGetValue(type, out var value))
				{
					value = (dict[type] = new Dictionary<string, T>());
				}
				if (!value.TryGetValue(name, out var value2))
				{
					value2 = (value[name] = fetcher());
				}
				return value2;
			}
		}

		private static T Get<T>(Dictionary<Type, Dictionary<string, Dictionary<int, T>>> dict, Type type, string name, Type[] arguments, Func<T> fetcher)
		{
			lock (dict)
			{
				if (!dict.TryGetValue(type, out var value))
				{
					value = (dict[type] = new Dictionary<string, Dictionary<int, T>>());
				}
				if (!value.TryGetValue(name, out var value2))
				{
					value2 = (value[name] = new Dictionary<int, T>());
				}
				int key = AccessTools.CombinedHashCode(arguments);
				if (!value2.TryGetValue(key, out var value3))
				{
					value3 = (value2[key] = fetcher());
				}
				return value3;
			}
		}

		internal FieldInfo GetFieldInfo(Type type, string name, MemberType memberType = MemberType.Any, bool declaredOnly = false)
		{
			FieldInfo fieldInfo = Get(declaredFields, type, name, () => type.GetField(name, declaredOnlyBindingFlags[memberType]));
			if ((object)fieldInfo == null && !declaredOnly)
			{
				fieldInfo = Get(inheritedFields, type, name, () => AccessTools.FindIncludingBaseTypes(type, (Type t) => t.GetField(name, AccessTools.all)));
			}
			return fieldInfo;
		}

		internal PropertyInfo GetPropertyInfo(Type type, string name, MemberType memberType = MemberType.Any, bool declaredOnly = false)
		{
			PropertyInfo propertyInfo = Get(declaredProperties, type, name, () => type.GetProperty(name, declaredOnlyBindingFlags[memberType]));
			if ((object)propertyInfo == null && !declaredOnly)
			{
				propertyInfo = Get(inheritedProperties, type, name, () => AccessTools.FindIncludingBaseTypes(type, (Type t) => t.GetProperty(name, AccessTools.all)));
			}
			return propertyInfo;
		}

		internal MethodBase GetMethodInfo(Type type, string name, Type[] arguments, MemberType memberType = MemberType.Any, bool declaredOnly = false)
		{
			MethodBase methodBase = Get(declaredMethods, type, name, arguments, () => type.GetMethod(name, declaredOnlyBindingFlags[memberType], null, arguments, null));
			if ((object)methodBase == null && !declaredOnly)
			{
				methodBase = Get(inheritedMethods, type, name, arguments, () => AccessTools.Method(type, name, arguments));
			}
			return methodBase;
		}
	}
	internal static class PatchArgumentExtensions
	{
		private static HarmonyArgument[] AllHarmonyArguments(object[] attributes)
		{
			return (from attr in attributes
				select (attr.GetType().Name != "HarmonyArgument") ? null : AccessTools.MakeDeepCopy<HarmonyArgument>(attr) into harg
				where harg != null
				select harg).ToArray();
		}

		private static HarmonyArgument GetArgumentAttribute(this ParameterInfo parameter)
		{
			return AllHarmonyArguments(parameter.GetCustomAttributes(inherit: false)).FirstOrDefault();
		}

		private static HarmonyArgument[] GetArgumentAttributes(this MethodInfo method)
		{
			if ((object)method == null || method is DynamicMethod)
			{
				return null;
			}
			return AllHarmonyArguments(method.GetCustomAttributes(inherit: false));
		}

		private static HarmonyArgument[] GetArgumentAttributes(this Type type)
		{
			return AllHarmonyArguments(type.GetCustomAttributes(inherit: false));
		}

		private static string GetOriginalArgumentName(this ParameterInfo parameter, string[] originalParameterNames)
		{
			HarmonyArgument argumentAttribute = parameter.GetArgumentAttribute();
			if (argumentAttribute == null)
			{
				return null;
			}
			if (!string.IsNullOrEmpty(argumentAttribute.OriginalName))
			{
				return argumentAttribute.OriginalName;
			}
			if (argumentAttribute.Index >= 0 && argumentAttribute.Index < originalParameterNames.Length)
			{
				return originalParameterNames[argumentAttribute.Index];
			}
			return null;
		}

		private static string GetOriginalArgumentName(HarmonyArgument[] attributes, string name, string[] originalParameterNames)
		{
			if (((attributes != null && attributes.Length != 0) ? 1 : 0) <= (false ? 1 : 0))
			{
				return null;
			}
			HarmonyArgument harmonyArgument = attributes.SingleOrDefault((HarmonyArgument p) => p.NewName == name);
			if (harmonyArgument == null)
			{
				return null;
			}
			if (!string.IsNullOrEmpty(harmonyArgument.OriginalName))
			{
				return harmonyArgument.OriginalName;
			}
			if (originalParameterNames != null && harmonyArgument.Index >= 0 && harmonyArgument.Index < originalParameterNames.Length)
			{
				return originalParameterNames[harmonyArgument.Index];
			}
			return null;
		}

		private static string GetOriginalArgumentName(this MethodInfo method, string[] originalParameterNames, string name)
		{
			string originalArgumentName = GetOriginalArgumentName(((object)method != null) ? method.GetArgumentAttributes() : null, name, originalParameterNames);
			if (originalArgumentName != null)
			{
				return originalArgumentName;
			}
			object attributes;
			if ((object)method == null)
			{
				attributes = null;
			}
			else
			{
				Type? declaringType = method.DeclaringType;
				attributes = (((object)declaringType != null) ? declaringType.GetArgumentAttributes() : null);
			}
			originalArgumentName = GetOriginalArgumentName((HarmonyArgument[])attributes, name, originalParameterNames);
			if (originalArgumentName != null)
			{
				return originalArgumentName;
			}
			return name;
		}

		internal static int GetArgumentIndex(this MethodInfo patch, string[] originalParameterNames, ParameterInfo patchParam)
		{
			if (patch is DynamicMethod)
			{
				return Array.IndexOf<string>(originalParameterNames, patchParam.Name);
			}
			string originalArgumentName = patchParam.GetOriginalArgumentName(originalParameterNames);
			if (originalArgumentName != null)
			{
				return Array.IndexOf(originalParameterNames, originalArgumentName);
			}
			originalArgumentName = patch.GetOriginalArgumentName(originalParameterNames, patchParam.Name);
			if (originalArgumentName != null)
			{
				return Array.IndexOf(originalParameterNames, originalArgumentName);
			}
			return -1;
		}
	}
	internal static class PatchFunctions
	{
		internal static List<MethodInfo> GetSortedPatchMethods(MethodBase original, Patch[] patches, bool debug)
		{
			return new PatchSorter(patches, debug).Sort(original);
		}

		internal static Patch[] GetSortedPatchMethodsAsPatches(MethodBase original, Patch[] patches, bool debug)
		{
			return new PatchSorter(patches, debug).SortAsPatches(original);
		}

		internal static MethodInfo UpdateWrapper(MethodBase original, PatchInfo patchInfo)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			MethodPatcher methodPatcher = original.GetMethodPatcher();
			DynamicMethodDefinition val = methodPatcher.PrepareOriginal();
			if (val != null)
			{
				ILContext ctx = new ILContext(val.Definition);
				HarmonyManipulator.Manipulate(original, patchInfo, ctx);
			}
			try
			{
				return methodPatcher.DetourTo((val != null) ? val.Generate() : null) as MethodInfo;
			}
			catch (Exception ex)
			{
				object body;
				if (val == null)
				{
					body = null;
				}
				else
				{
					MethodDefinition definition = val.Definition;
					body = ((definition != null) ? definition.Body : null);
				}
				throw HarmonyException.Create(ex, (MethodBody)body);
			}
		}

		internal static MethodInfo ReversePatch(HarmonyMethod standin, MethodBase original, MethodInfo postTranspiler, MethodInfo postManipulator)
		{
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			if (standin == null)
			{
				throw new ArgumentNullException("standin");
			}
			if ((object)standin.method == null)
			{
				throw new ArgumentNullException("standin", "standin.method is NULL");
			}
			bool debug = standin.debug.GetValueOrDefault();
			List<MethodInfo> transpilers = new List<MethodInfo>();
			List<MethodInfo> ilmanipulators = new List<MethodInfo>();
			if (standin.reversePatchType == HarmonyReversePatchType.Snapshot)
			{
				Patches patchInfo = Harmony.GetPatchInfo(original);
				transpilers.AddRange(GetSortedPatchMethods(original, patchInfo.Transpilers.ToArray(), debug));
				ilmanipulators.AddRange(GetSortedPatchMethods(original, patchInfo.ILManipulators.ToArray(), debug));
			}
			if ((object)postTranspiler != null)
			{
				transpilers.Add(postTranspiler);
			}
			if ((object)postManipulator != null)
			{
				ilmanipulators.Add(postManipulator);
			}
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine("Reverse patching " + standin.method.FullDescription() + " with " + original.FullDescription());
				PrintInfo(stringBuilder, transpilers, "Transpiler");
				PrintInfo(stringBuilder, ilmanipulators, "Manipulators");
				return stringBuilder.ToString();
			}, debug);
			MethodBody patchBody = null;
			ILHook val = new ILHook((MethodBase)standin.method, (Manipulator)delegate(ILContext ctx)
			{
				//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: 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_00fb: Expected O, but got Unknown
				//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
				if (original is MethodInfo methodInfo2)
				{
					patchBody = ctx.Body;
					MethodPatcher methodPatcher = methodInfo2.GetMethodPatcher();
					DynamicMethodDefinition val2 = methodPatcher.CopyOriginal();
					if (val2 == null)
					{
						throw new NullReferenceException("Cannot reverse patch " + methodInfo2.FullDescription() + ": method patcher (" + methodPatcher.GetType().FullDescription() + ") can't copy original method body");
					}
					ILManipulator iLManipulator = new ILManipulator(val2.Definition.Body, debug);
					ctx.Body.Variables.Clear();
					Enumerator<VariableDefinition> enumerator2 = iLManipulator.Body.Variables.GetEnumerator();
					try
					{
						while (enumerator2.MoveNext())
						{
							VariableDefinition current2 = enumerator2.Current;
							ctx.Body.Variables.Add(new VariableDefinition(ctx.Module.ImportReference(((VariableReference)current2).VariableType)));
						}
					}
					finally
					{
						((IDisposable)enumerator2).Dispose();
					}
					foreach (MethodInfo item in transpilers)
					{
						iLManipulator.AddTranspiler(item);
					}
					iLManipulator.WriteTo(ctx.Body, standin.method);
					HarmonyManipulator.ApplyManipulators(ctx, original, ilmanipulators, null);
					Instruction val3 = null;
					foreach (Instruction item2 in ((IEnumerable<Instruction>)ctx.Instrs).Where((Instruction i) => i.OpCode == OpCodes.Ret))
					{
						if (val3 == null)
						{
							val3 = ctx.IL.Create(OpCodes.Ret);
						}
						item2.OpCode = OpCodes.Br;
						item2.Operand = val3;
					}
					if (val3 != null)
					{
						ctx.IL.Append(val3);
					}
					Logger.Log(Logger.LogChannel.IL, () => "Generated reverse patcher (" + ((MemberReference)ctx.Method).FullName + "):\n" + ctx.Body.ToILDasmString(), debug);
				}
			}, new ILHookConfig
			{
				ManualApply = true
			});
			try
			{
				val.Apply();
			}
			catch (Exception ex)
			{
				throw HarmonyException.Create(ex, patchBody);
			}
			MethodInfo methodInfo = val.GetCurrentTarget() as MethodInfo;
			PatchTools.RememberObject(standin.method, methodInfo);
			return methodInfo;
			static void PrintInfo(StringBuilder sb, ICollection<MethodInfo> methods, string name)
			{
				if (methods.Count <= 0)
				{
					return;
				}
				sb.AppendLine(name + ":");
				foreach (MethodInfo method in methods)
				{
					sb.AppendLine("  * " + method.FullDescription());
				}
			}
		}

		internal static IEnumerable<CodeInstruction> ApplyTranspilers(MethodBase methodBase, ILGenerator generator, int maxTranspilers = 0)
		{
			MethodPatcher methodPatcher = methodBase.GetMethodPatcher();
			DynamicMethodDefinition val = methodPatcher.CopyOriginal();
			if (val == null)
			{
				throw new NullReferenceException("Cannot reverse patch " + methodBase.FullDescription() + ": method patcher (" + methodPatcher.GetType().FullDescription() + ") can't copy original method body");
			}
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body, debug: false);
			PatchInfo patchInfo = methodBase.GetPatchInfo();
			if (patchInfo != null)
			{
				List<MethodInfo> sortedPatchMethods = GetSortedPatchMethods(methodBase, patchInfo.transpilers, debug: false);
				for (int i = 0; i < maxTranspilers && i < sortedPatchMethods.Count; i++)
				{
					iLManipulator.AddTranspiler(sortedPatchMethods[i]);
				}
			}
			return iLManipulator.GetInstructions(generator, methodBase);
		}

		internal static void UnpatchConditional(Func<Patch, bool> executionCondition)
		{
			foreach (MethodBase item in PatchProcessor.GetAllPatchedMethods().ToList())
			{
				bool num = item.HasMethodBody();
				Patches patchInfo2 = PatchProcessor.GetPatchInfo(item);
				PatchProcessor patchProcessor = new PatchProcessor(null, item);
				if (num)
				{
					patchInfo2.Postfixes.DoIf(executionCondition, delegate(Patch patchInfo)
					{
						patchProcessor.Unpatch(patchInfo.PatchMethod);
					});
					patchInfo2.Prefixes.DoIf(executionCondition, delegate(Patch patchInfo)
					{
						patchProcessor.Unpatch(patchInfo.PatchMethod);
					});
				}
				patchInfo2.ILManipulators.DoIf(executionCondition, delegate(Patch patchInfo)
				{
					patchProcessor.Unpatch(patchInfo.PatchMethod);
				});
				patchInfo2.Transpilers.DoIf(executionCondition, delegate(Patch patchInfo)
				{
					patchProcessor.Unpatch(patchInfo.PatchMethod);
				});
				if (num)
				{
					patchInfo2.Finalizers.DoIf(executionCondition, delegate(Patch patchInfo)
					{
						patchProcessor.Unpatch(patchInfo.PatchMethod);
					});
				}
			}
		}
	}
	internal class PatchJobs<T>
	{
		internal class Job
		{
			internal MethodBase original;

			internal T replacement;

			internal List<HarmonyMethod> prefixes = new List<HarmonyMethod>();

			internal List<HarmonyMethod> postfixes = new List<HarmonyMethod>();

			internal List<HarmonyMethod> transpilers = new List<HarmonyMethod>();

			internal List<HarmonyMethod> finalizers = new List<HarmonyMethod>();

			internal List<HarmonyMethod> ilmanipulators = new List<HarmonyMethod>();

			internal void AddPatch(AttributePatch patch)
			{
				HarmonyPatchType? type = patch.type;
				if (type.HasValue)
				{
					switch (type.GetValueOrDefault())
					{
					case HarmonyPatchType.Prefix:
						prefixes.Add(patch.info);
						break;
					case HarmonyPatchType.Postfix:
						postfixes.Add(patch.info);
						break;
					case HarmonyPatchType.Transpiler:
						transpilers.Add(patch.info);
						break;
					case HarmonyPatchType.Finalizer:
						finalizers.Add(patch.info);
						break;
					case HarmonyPatchType.ILManipulator:
						ilmanipulators.Add(patch.info);
						break;
					case HarmonyPatchType.ReversePatch:
						break;
					}
				}
			}
		}

		internal Dictionary<MethodBase, Job> state = new Dictionary<MethodBase, Job>();

		internal Job GetJob(MethodBase method)
		{
			if ((object)method == null)
			{
				return null;
			}
			if (!state.TryGetValue(method, out var value))
			{
				value = new Job
				{
					original = method
				};
				state[method] = value;
			}
			return value;
		}

		internal List<Job> GetJobs()
		{
			return state.Values.Where((Job job) => job.prefixes.Count + job.postfixes.Count + job.transpilers.Count + job.finalizers.Count + job.ilmanipulators.Count > 0).ToList();
		}

		internal List<T> GetReplacements()
		{
			return state.Values.Select((Job job) => job.replacement).ToList();
		}
	}
	internal class AttributePatch
	{
		private static readonly HarmonyPatchType[] allPatchTypes = new HarmonyPatchType[6]
		{
			HarmonyPatchType.Prefix,
			HarmonyPatchType.Postfix,
			HarmonyPatchType.Transpiler,
			HarmonyPatchType.Finalizer,
			HarmonyPatchType.ReversePatch,
			HarmonyPatchType.ILManipulator
		};

		internal HarmonyMethod info;

		internal HarmonyPatchType? type;

		private static readonly string harmonyAttributeName = typeof(HarmonyAttribute).FullName;

		internal static IEnumerable<AttributePatch> Create(MethodInfo patch, bool collectIncomplete = false)
		{
			if ((object)patch == null)
			{
				throw new NullReferenceException("Patch method cannot be null");
			}
			object[] customAttributes = patch.GetCustomAttributes(inherit: true);
			string name = patch.Name;
			HarmonyPatchType? type = GetPatchType(name, customAttributes);
			if (!type.HasValue)
			{
				return Enumerable.Empty<AttributePatch>();
			}
			if (type != HarmonyPatchType.ReversePatch && !patch.IsStatic)
			{
				throw new ArgumentException("Patch method " + patch.FullDescription() + " must be static");
			}
			List<HarmonyMethod> list = (from attr in customAttributes
				where attr.GetType().BaseType.FullName == harmonyAttributeName
				select AccessTools.Field(attr.GetType(), "info").GetValue(attr) into harmonyInfo
				select AccessTools.MakeDeepCopy<HarmonyMethod>(harmonyInfo)).ToList();
			List<HarmonyMethod> list2 = new List<HarmonyMethod>();
			ILookup<bool, HarmonyMethod> lookup = list.ToLookup((HarmonyMethod m) => IsComplete(m, collectIncomplete));
			List<HarmonyMethod> incomplete = lookup[false].ToList();
			HarmonyMethod info = HarmonyMethod.Merge(incomplete);
			List<HarmonyMethod> list3 = lookup[true].Where((HarmonyMethod m) => !Same(m, info)).ToList();
			if (list3.Count > 1)
			{
				list2.AddRange(list3.Select((HarmonyMethod m) => HarmonyMethod.Merge(incomplete.AddItem(m))));
			}
			else
			{
				list2.Add(HarmonyMethod.Merge(list));
			}
			foreach (HarmonyMethod item in list2)
			{
				item.method = patch;
			}
			return list2.Select((HarmonyMethod i) => new AttributePatch
			{
				info = i,
				type = type
			}).ToList();
			static bool IsComplete(HarmonyMethod m, bool collectIncomplete)
			{
				if (collectIncomplete || (object)m.GetDeclaringType() != null)
				{
					return m.methodName != null;
				}
				return false;
			}
			static bool Same(HarmonyMethod m1, HarmonyMethod m2)
			{
				if ((object)m1.GetDeclaringType() == m2.GetDeclaringType() && m1.methodName == m2.methodName)
				{
					return m1.GetArgumentList().SequenceEqual(m2.GetArgumentList());
				}
				return false;
			}
		}

		private static HarmonyPatchType? GetPatchType(string methodName, object[] allAttributes)
		{
			HashSet<string> hashSet = new HashSet<string>(from attr in allAttributes
				select attr.GetType().FullName into name
				where name.StartsWith("Harmony")
				select name);
			HarmonyPatchType? result = null;
			HarmonyPatchType[] array = allPatchTypes;
			for (int i = 0; i < array.Length; i++)
			{
				HarmonyPatchType value = array[i];
				string text = value.ToString();
				if (text == methodName || hashSet.Contains("HarmonyLib.Harmony" + text))
				{
					result = value;
					break;
				}
			}
			return result;
		}
	}
	internal class PatchSorter
	{
		private class PatchSortingWrapper : IComparable
		{
			internal readonly HashSet<PatchSortingWrapper> after;

			internal readonly HashSet<PatchSortingWrapper> before;

			internal readonly Patch innerPatch;

			internal PatchSortingWrapper(Patch patch)
			{
				innerPatch = patch;
				before = new HashSet<PatchSortingWrapper>();
				after = new HashSet<PatchSortingWrapper>();
			}

			public int CompareTo(object obj)
			{
				return PatchInfoSerialization.PriorityComparer((obj as PatchSortingWrapper)?.innerPatch, innerPatch.index, innerPatch.priority);
			}

			public override bool Equals(object obj)
			{
				if (obj is PatchSortingWrapper patchSortingWrapper)
				{
					return (object)innerPatch.PatchMethod == patchSortingWrapper.innerPatch.PatchMethod;
				}
				return false;
			}

			public override int GetHashCode()
			{
				return innerPatch.PatchMethod.GetHashCode();
			}

			internal void AddBeforeDependency(IEnumerable<PatchSortingWrapper> dependencies)
			{
				foreach (PatchSortingWrapper dependency in dependencies)
				{
					before.Add(dependency);
					dependency.after.Add(this);
				}
			}

			internal void AddAfterDependency(IEnumerable<PatchSortingWrapper> dependencies)
			{
				foreach (PatchSortingWrapper dependency in dependencies)
				{
					after.Add(dependency);
					dependency.before.Add(this);
				}
			}

			internal void RemoveAfterDependency(PatchSortingWrapper afterNode)
			{
				after.Remove(afterNode);
				afterNode.before.Remove(this);
			}

			internal void RemoveBeforeDependency(PatchSortingWrapper beforeNode)
			{
				before.Remove(beforeNode);
				beforeNode.after.Remove(this);
			}
		}

		internal class PatchDetailedComparer : IEqualityComparer<Patch>
		{
			public bool Equals(Patch x, Patch y)
			{
				if (y != null && x != null && x.owner == y.owner && (object)x.PatchMethod == y.PatchMethod && x.index == y.index && x.priority == y.priority && x.before.Length == y.before.Length && x.after.Length == y.after.Length && x.before.All(((IEnumerable<string>)y.before).Contains<string>))
				{
					return x.after.All(((IEnumerable<string>)y.after).Contains<string>);
				}
				return false;
			}

			public int GetHashCode(Patch obj)
			{
				return obj.GetHashCode();
			}
		}

		private List<PatchSortingWrapper> patches;

		private HashSet<PatchSortingWrapper> handledPatches;

		private List<PatchSortingWrapper> result;

		private List<PatchSortingWrapper> waitingList;

		internal Patch[] sortedPatchArray;

		private readonly bool debug;

		internal PatchSorter(Patch[] patches, bool debug = false)
		{
			this.patches = patches.Select((Patch x) => new PatchSortingWrapper(x)).ToList();
			this.debug = debug;
			foreach (PatchSortingWrapper node in this.patches)
			{
				node.AddBeforeDependency(this.patches.Where((PatchSortingWrapper x) => node.innerPatch.before.Contains(x.innerPatch.owner)));
				node.AddAfterDependency(this.patches.Where((PatchSortingWrapper x) => node.innerPatch.after.Contains(x.innerPatch.owner)));
			}
			this.patches.Sort();
		}

		internal List<MethodInfo> Sort(MethodBase original)
		{
			return (from x in SortAsPatches(original)
				select x.GetMethod(original)).ToList();
		}

		internal Patch[] SortAsPatches(MethodBase original)
		{
			if (sortedPatchArray != null)
			{
				return sortedPatchArray;
			}
			handledPatches = new HashSet<PatchSortingWrapper>();
			waitingList = new List<PatchSortingWrapper>();
			result = new List<PatchSortingWrapper>(patches.Count);
			Queue<PatchSortingWrapper> queue = new Queue<PatchSortingWrapper>(patches);
			while (queue.Count != 0)
			{
				foreach (PatchSortingWrapper item in queue)
				{
					if (item.after.All((PatchSortingWrapper x) => handledPatches.Contains(x)))
					{
						AddNodeToResult(item);
						if (item.before.Count != 0)
						{
							ProcessWaitingList();
						}
					}
					else
					{
						waitingList.Add(item);
					}
				}
				CullDependency();
				queue = new Queue<PatchSortingWrapper>(waitingList);
				waitingList.Clear();
			}
			sortedPatchArray = result.Select((PatchSortingWrapper x) => x.innerPatch).ToArray();
			handledPatches = null;
			waitingList = null;
			patches = null;
			return sortedPatchArray;
		}

		internal bool ComparePatchLists(Patch[] patches)
		{
			if (sortedPatchArray == null)
			{
				Sort(null);
			}
			if (patches != null && sortedPatchArray.Length == patches.Length)
			{
				return sortedPatchArray.All((Patch x) => patches.Contains(x, new PatchDetailedComparer()));
			}
			return false;
		}

		private void CullDependency()
		{
			for (int i = waitingList.Count - 1; i >= 0; i--)
			{
				foreach (PatchSortingWrapper afterNode in waitingList[i].after)
				{
					if (!handledPatches.Contains(afterNode))
					{
						waitingList[i].RemoveAfterDependency(afterNode);
						Logger.Log(Logger.LogChannel.Debug, delegate
						{
							string text = afterNode.innerPatch.PatchMethod.FullDescription();
							string text2 = waitingList[i].innerPatch.PatchMethod.FullDescription();
							return "Breaking dependence between " + text + " and " + text2;
						}, debug);
						return;
					}
				}
			}
		}

		private void ProcessWaitingList()
		{
			int num = waitingList.Count;
			int num2 = 0;
			while (num2 < num)
			{
				PatchSortingWrapper patchSortingWrapper = waitingList[num2];
				if (patchSortingWrapper.after.All(handledPatches.Contains))
				{
					waitingList.Remove(patchSortingWrapper);
					AddNodeToResult(patchSortingWrapper);
					num--;
					num2 = 0;
				}
				else
				{
					num2++;
				}
			}
		}

		private void AddNodeToResult(PatchSortingWrapper node)
		{
			result.Add(node);
			handledPatches.Add(node);
		}
	}
	internal static class PatchTools
	{
		[ThreadStatic]
		private static Dictionary<object, object> objectReferences;

		internal static void RememberObject(object key, object value)
		{
			if (objectReferences == null)
			{
				objectReferences = new Dictionary<object, object>();
			}
			objectReferences[key] = value;
		}

		internal static MethodInfo GetPatchMethod(Type patchType, string attributeName)
		{
			MethodInfo methodInfo = patchType.GetMethods(AccessTools.all).FirstOrDefault((MethodInfo m) => m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == attributeName));
			if ((object)methodInfo == null)
			{
				string name = attributeName.Replace("HarmonyLib.Harmony", "");
				methodInfo = patchType.GetMethod(name, AccessTools.all);
			}
			return methodInfo;
		}

		internal static AssemblyBuilder DefineDynamicAssembly(string name)
		{
			AssemblyName assemblyName = new AssemblyName(name);
			return AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
		}

		internal static List<AttributePatch> GetPatchMethods(Type type, bool collectIncomplete = false)
		{
			return (from attributePatch in AccessTools.GetDeclaredMethods(type).SelectMany((MethodInfo m) => AttributePatch.Create(m, collectIncomplete))
				where attributePatch != null
				select attributePatch).ToList();
		}

		internal static MethodBase GetOriginalMethod(this HarmonyMethod attr)
		{
			try
			{
				MethodType? methodType = attr.methodType;
				if (methodType.HasValue)
				{
					switch (methodType.GetValueOrDefault())
					{
					case MethodType.Normal:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.DeclaredMethod(attr.GetDeclaringType(), attr.methodName, attr.argumentTypes);
					case MethodType.Getter:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.DeclaredProperty(attr.GetDeclaringType(), attr.methodName).GetGetMethod(nonPublic: true);
					case MethodType.Setter:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.DeclaredProperty(attr.GetDeclaringType(), attr.methodName).GetSetMethod(nonPublic: true);
					case MethodType.Constructor:
						return AccessTools.DeclaredConstructor(attr.GetDeclaringType(), attr.argumentTypes);
					case MethodType.StaticConstructor:
						return AccessTools.GetDeclaredConstructors(attr.GetDeclaringType()).FirstOrDefault((ConstructorInfo c) => c.IsStatic);
					case MethodType.Enumerator:
						if (attr.methodName == null)
						{
							return null;
						}
						return AccessTools.EnumeratorMoveNext(AccessTools.DeclaredMethod(attr.GetDeclaringType(), attr.methodName, attr.argumentTypes));
					}
				}
			}
			catch (AmbiguousMatchException ex)
			{
				throw new HarmonyException("Ambiguous match for HarmonyMethod[" + attr.Description() + "]", ex.InnerException ?? ex);
			}
			return null;
		}
	}
	public enum MethodType
	{
		Normal,
		Getter,
		Setter,
		Constructor,
		StaticConstructor,
		Enumerator
	}
	public enum ArgumentType
	{
		Normal,
		Ref,
		Out,
		Pointer
	}
	public enum HarmonyPatchType
	{
		All,
		Prefix,
		Postfix,
		Transpiler,
		Finalizer,
		ReversePatch,
		ILManipulator
	}
	public enum HarmonyReversePatchType
	{
		Original,
		Snapshot
	}
	public enum MethodDispatchType
	{
		VirtualCall,
		Call
	}
	[MeansImplicitUse]
	public class HarmonyAttribute : Attribute
	{
		public HarmonyMethod info = new HarmonyMethod();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Delegate, AllowMultiple = true)]
	public class HarmonyPatch : HarmonyAttribute
	{
		public HarmonyPatch()
		{
		}

		public HarmonyPatch(Type declaringType)
		{
			info.declaringType = declaringType;
		}

		public HarmonyPatch(Type declaringType, Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
		}

		public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(string assemblyQualifiedDeclaringType, string methodName)
		{
			info.assemblyQualifiedDeclaringTypeName = assemblyQualifiedDeclaringType;
			info.methodName = methodName;
		}

		public HarmonyPatch(string assemblyQualifiedDeclaringType, string methodName, MethodType methodType, Type[] argumentTypes = null, ArgumentType[] argumentVariations = null)
		{
			info.assemblyQualifiedDeclaringTypeName = assemblyQualifiedDeclaringType;
			info.methodName = methodName;
			info.methodType = methodType;
			if (argumentTypes != null)
			{
				ParseSpecialArguments(argumentTypes, argumentVariations);
			}
		}

		public HarmonyPatch(Type declaringType, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type declaringType, string methodName, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(string methodName)
		{
			info.methodName = methodName;
		}

		public HarmonyPatch(string methodName, params Type[] argumentTypes)
		{
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(string methodName, MethodType methodType)
		{
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType)
		{
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
		{
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type[] argumentTypes)
		{
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		private void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			if (argumentVariations == null || argumentVariations.Length == 0)
			{
				info.argumentTypes = argumentTypes;
				return;
			}
			if (argumentTypes.Length < argumentVariations.Length)
			{
				throw new ArgumentException("argumentVariations contains more elements than argumentTypes", "argumentVariations");
			}
			List<Type> list = new List<Type>();
			for (int i = 0; i < argumentTypes.Length; i++)
			{
				Type type = argumentTypes[i];
				switch (argumentVariations[i])
				{
				case ArgumentType.Ref:
				case ArgumentType.Out:
					type = type.MakeByRefType();
					break;
				case ArgumentType.Pointer:
					type = type.MakePointerType();
					break;
				}
				list.Add(type);
			}
			info.argumentTypes = list.ToArray();
		}
	}
	[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = true)]
	public class HarmonyDelegate : HarmonyPatch
	{
		public HarmonyDelegate(Type declaringType)
			: base(declaringType)
		{
		}

		public HarmonyDelegate(Type declaringType, Type[] argumentTypes)
			: base(declaringType, argumentTypes)
		{
		}

		public HarmonyDelegate(Type declaringType, string methodName)
			: base(declaringType, methodName)
		{
		}

		public HarmonyDelegate(Type declaringType, string methodName, params Type[] argumentTypes)
			: base(declaringType, methodName, argumentTypes)
		{
		}

		public HarmonyDelegate(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(declaringType, methodName, argumentTypes, argumentVariations)
		{
		}

		public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType)
			: base(declaringType, MethodType.Normal)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, params Type[] argumentTypes)
			: base(declaringType, MethodType.Normal, argumentTypes)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(declaringType, MethodType.Normal, argumentTypes, argumentVariations)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type declaringType, string methodName, MethodDispatchType methodDispatchType)
			: base(declaringType, methodName, MethodType.Normal)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(string methodName)
			: base(methodName)
		{
		}

		public HarmonyDelegate(string methodName, params Type[] argumentTypes)
			: base(methodName, argumentTypes)
		{
		}

		public HarmonyDelegate(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(methodName, argumentTypes, argumentVariations)
		{
		}

		public HarmonyDelegate(string methodName, MethodDispatchType methodDispatchType)
			: base(methodName, MethodType.Normal)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(MethodDispatchType methodDispatchType)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(MethodDispatchType methodDispatchType, params Type[] argumentTypes)
			: base(MethodType.Normal, argumentTypes)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(MethodType.Normal, argumentTypes, argumentVariations)
		{
			info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
		}

		public HarmonyDelegate(Type[] argumentTypes)
			: base(argumentTypes)
		{
		}

		public HarmonyDelegate(Type[] argumentTypes, ArgumentType[] argumentVariations)
			: base(argumentTypes, argumentVariations)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
	public class HarmonyReversePatch : HarmonyAttribute
	{
		public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
		{
			info.reversePatchType = type;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class HarmonyPatchAll : HarmonyAttribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyPriority : HarmonyAttribute
	{
		public HarmonyPriority(int priority)
		{
			info.priority = priority;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyBefore : HarmonyAttribute
	{
		public HarmonyBefore(params string[] before)
		{
			info.before = before;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyAfter : HarmonyAttribute
	{
		public HarmonyAfter(params string[] after)
		{
			info.after = after;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyDebug : HarmonyAttribute
	{
		public HarmonyDebug()
		{
			info.debug = true;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyEmitIL : HarmonyAttribute
	{
		public HarmonyEmitIL()
		{
			info.debugEmitPath = "./";
		}

		public HarmonyEmitIL(string dir)
		{
			info.debugEmitPath = dir;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyWrapSafe : HarmonyAttribute
	{
		public HarmonyWrapSafe()
		{
			info.wrapTryCatch = true;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrepare : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyCleanup : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethod : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethods : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrefix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPostfix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTranspiler : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyILManipulator : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyFinalizer : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)]
	public class HarmonyArgument : Attribute
	{
		public string OriginalName { get; private set; }

		public int Index { get; private set; }

		public string NewName { get; private set; }

		public HarmonyArgument(string originalName)
			: this(originalName, null)
		{
		}

		public HarmonyArgument(int index)
			: this(index, null)
		{
		}

		public HarmonyArgument(string originalName, string newName)
		{
			OriginalName = originalName;
			Index = -1;
			NewName = newName;
		}

		public HarmonyArgument(int index, string name)
		{
			OriginalName = null;
			Index = index;
			NewName = name;
		}
	}
	public class CodeInstruction
	{
		public OpCode opcode;

		public object operand;

		public List<Label> labels = new List<Label>();

		public List<ExceptionBlock> blocks = new List<ExceptionBlock>();

		internal CodeInstruction()
		{
		}

		public CodeInstruction(OpCode opcode, object operand = null)
		{
			this.opcode = opcode;
			this.operand = operand;
		}

		public CodeInstruction(CodeInstruction instruction)
		{
			opcode = instruction.opcode;
			operand = instruction.operand;
			labels = instruction.labels.ToList();
			blocks = instruction.blocks.ToList();
		}

		public CodeInstruction Clone()
		{
			return new CodeInstruction(this)
			{
				labels = new List<Label>(),
				blocks = new List<ExceptionBlock>()
			};
		}

		public CodeInstruction Clone(OpCode opcode)
		{
			CodeInstruction codeInstruction = Clone();
			codeInstruction.opcode = opcode;
			return codeInstruction;
		}

		public CodeInstruction Clone(object operand)
		{
			CodeInstruction codeInstruction = Clone();
			codeInstruction.operand = operand;
			return codeInstruction;
		}

		public static CodeInstruction Call(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			MethodInfo methodInfo = AccessTools.Method(type, name, parameters, generics);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException($"No method found for type={type}, name={name}, parameters={parameters.Description()}, generics={generics.Description()}");
			}
			return new CodeInstruction(OpCodes.Call, methodInfo);
		}

		public static CodeInstruction Call(string typeColonMethodname, Type[] parameters = null, Type[] generics = null)
		{
			MethodInfo methodInfo = AccessTools.Method(typeColonMethodname, parameters, generics);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException("No method found for " + typeColonMethodname + ", parameters=" + parameters.Description() + ", generics=" + generics.Description());
			}
			return new CodeInstruction(OpCodes.Call, methodInfo);
		}

		public static CodeInstruction Call(Expression<Action> expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction Call<T>(Expression<Action<T>> expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction Call<T, TResult>(Expression<Func<T, TResult>> expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction Call(LambdaExpression expression)
		{
			return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression));
		}

		public static CodeInstruction CallClosure<T>(T closure) where T : Delegate
		{
			return Transpilers.EmitDelegate(closure);
		}

		public static CodeInstruction LoadField(Type type, string name, bool useAddress = false)
		{
			FieldInfo fieldInfo = AccessTools.Field(type, name);
			if ((object)fieldInfo == null)
			{
				throw new ArgumentException($"No field found for {type} and {name}");
			}
			return new CodeInstruction((!useAddress) ? (fieldInfo.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld) : (fieldInfo.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda), fieldInfo);
		}

		public static CodeInstruction StoreField(Type type, string name)
		{
			FieldInfo fieldInfo = AccessTools.Field(type, name);
			if ((object)fieldInfo == null)
			{
				throw new ArgumentException($"No field found for {type} and {name}");
			}
			return new CodeInstruction(fieldInfo.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, fieldInfo);
		}

		public override string ToString()
		{
			List<string> list = new List<string>();
			foreach (Label label in labels)
			{
				list.Add($"Label{label.GetHashCode()}");
			}
			foreach (ExceptionBlock block in blocks)
			{
				list.Add("EX_" + block.blockType.ToString().Replace("Block", ""));
			}
			string text = ((list.Count > 0) ? (" [" + string.Join(", ", list.ToArray()) + "]") : "");
			string text2 = FormatArgument(operand);
			if (text2.Length > 0)
			{
				text2 = " " + text2;
			}
			OpCode opCode = opcode;
			return opCode.ToString() + text2 + text;
		}

		internal static string FormatArgument(object argument, string extra = null)
		{
			if (argument == null)
			{
				return "NULL";
			}
			Type type = argument.GetType();
			if (argument is MethodBase member)
			{
				return member.FullDescription() + ((extra != null) ? (" " + extra) : "");
			}
			if (argument is FieldInfo fieldInfo)
			{
				return fieldInfo.FieldType.FullDescription() + " " + fieldInfo.DeclaringType.FullDescription() + "::" + fieldInfo.Name;
			}
			if ((object)type == typeof(Label))
			{
				return $"Label{((Label)argument).GetHashCode()}";
			}
			if ((object)type == typeof(Label[]))
			{
				return "Labels" + string.Join(",", ((Label[])argument).Select((Label l) => l.GetHashCode().ToString()).ToArray());
			}
			if ((object)type == typeof(LocalBuilder))
			{
				return $"{((LocalBuilder)argument).LocalIndex} ({((LocalBuilder)argument).LocalType})";
			}
			if ((object)type == typeof(string))
			{
				return argument.ToString().ToLiteral();
			}
			return argument.ToString().Trim();
		}
	}
	public enum ExceptionBlockType
	{
		BeginExceptionBlock,
		BeginCatchBlock,
		BeginExceptFilterBlock,
		BeginFaultBlock,
		BeginFinallyBlock,
		EndExceptionBlock
	}
	public class ExceptionBlock
	{
		public ExceptionBlockType blockType;

		public Type catchType;

		public ExceptionBlock(ExceptionBlockType blockType, Type catchType = null)
		{
			this.blockType = blockType;
			this.catchType = catchType ?? typeof(object);
		}
	}
	public class InvalidHarmonyPatchArgumentException : Exception
	{
		public MethodBase Original { get; }

		public MethodInfo Patch { get; }

		public override string Message => "(" + Patch.FullDescription() + "): " + base.Message;

		public InvalidHarmonyPatchArgumentException(string message, MethodBase original, MethodInfo patch)
			: base(message)
		{
			Original = original;
			Patch = patch;
		}
	}
	public class MemberNotFoundException : Exception
	{
		public MemberNotFoundException(string message)
			: base(message)
		{
		}
	}
	public class Harmony : IDisposable
	{
		[Obsolete("Use HarmonyFileLog.Enabled instead")]
		public static bool DEBUG;

		public string Id { get; }

		static Harmony()
		{
			StackTraceFixes.Install();
		}

		public Harmony(string id)
		{
			if (string.IsNullOrEmpty(id))
			{
				throw new ArgumentException("id cannot be null or empty");
			}
			try
			{
				string environmentVariable = Environment.GetEnvironmentVariable("HARMONY_DEBUG");
				if (environmentVariable != null && environmentVariable.Length > 0)
				{
					environmentVariable = environmentVariable.Trim();
					DEBUG = environmentVariable == "1" || bool.Parse(environmentVariable);
				}
			}
			catch
			{
			}
			if (DEBUG)
			{
				HarmonyFileLog.Enabled = true;
			}
			MethodBase callingMethod = (Logger.IsEnabledFor(Logger.LogChannel.Info) ? AccessTools.GetOutsideCaller() : null);
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
				StringBuilder stringBuilder = new StringBuilder();
				Assembly assembly = typeof(Harmony).Assembly;
				Version version = assembly.GetName().Version;
				string text = assembly.Location;
				string text2 = Environment.Version.ToString();
				string text3 = Environment.OSVersion.Platform.ToString();
				if (string.IsNullOrEmpty(text))
				{
					text = new Uri(assembly.CodeBase).LocalPath;
				}
				int size = IntPtr.Size;
				Platform current = PlatformHelper.Current;
				stringBuilder.AppendLine($"### Harmony id={id}, version={version}, location={text}, env/clr={text2}, platform={text3}, ptrsize:runtime/env={size}/{current}");
				if ((object)callingMethod?.DeclaringType != null)
				{
					Assembly assembly2 = callingMethod.DeclaringType.Assembly;
					text = assembly2.Location;
					if (string.IsNullOrEmpty(text))
					{
						text = new Uri(assembly2.CodeBase).LocalPath;
					}
					stringBuilder.AppendLine("### Started from " + callingMethod.FullDescription() + ", location " + text);
					stringBuilder.Append($"### At {DateTime.Now:yyyy-MM-dd hh.mm.ss}");
				}
				return stringBuilder.ToString();
			});
			Id = id;
		}

		public void PatchAll()
		{
			Assembly assembly = new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly;
			PatchAll(assembly);
		}

		public PatchProcessor CreateProcessor(MethodBase original)
		{
			return new PatchProcessor(this, original);
		}

		public PatchClassProcessor CreateClassProcessor(Type type)
		{
			return new PatchClassProcessor(this, type);
		}

		public PatchClassProcessor CreateClassProcessor(Type type, bool allowUnannotatedType)
		{
			return new PatchClassProcessor(this, type, allowUnannotatedType);
		}

		public ReversePatcher CreateReversePatcher(MethodBase original, HarmonyMethod standin)
		{
			return new ReversePatcher(this, original, standin);
		}

		public void PatchAll(Assembly assembly)
		{
			AccessTools.GetTypesFromAssembly(assembly).Do(delegate(Type type)
			{
				CreateClassProcessor(type).Patch();
			});
		}

		public void PatchAll(Type type)
		{
			CreateClassProcessor(type, allowUnannotatedType: true).Patch();
		}

		public MethodInfo Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null, HarmonyMethod ilmanipulator = null)
		{
			PatchProcessor patchProcessor = CreateProcessor(original);
			patchProcessor.AddPrefix(prefix);
			patchProcessor.AddPostfix(postfix);
			patchProcessor.AddTranspiler(transpiler);
			patchProcessor.AddFinalizer(finalizer);
			patchProcessor.AddILManipulator(ilmanipulator);
			return patchProcessor.Patch();
		}

		[Obsolete("Use newer Patch() instead", true)]
		public MethodInfo Patch(MethodBase original, HarmonyMethod prefix, HarmonyMethod postfix, HarmonyMethod transpiler, HarmonyMethod finalizer)
		{
			return Patch(original, prefix, postfix, transpiler, finalizer, null);
		}

		public static MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler = null, MethodInfo ilmanipulator = null)
		{
			return PatchFunctions.ReversePatch(standin, original, transpiler, ilmanipulator);
		}

		[Obsolete("Use newer ReversePatch() instead", true)]
		public static MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler)
		{
			return PatchFunctions.ReversePatch(standin, original, transpiler, null);
		}

		public static void UnpatchID(string harmonyID)
		{
			if (string.IsNullOrEmpty(harmonyID))
			{
				throw new ArgumentNullException("harmonyID", "UnpatchID was called with a null or empty harmonyID.");
			}
			PatchFunctions.UnpatchConditional((Patch patchInfo) => patchInfo.owner == harmonyID);
		}

		void IDisposable.Dispose()
		{
			UnpatchSelf();
		}

		public void UnpatchSelf()
		{
			UnpatchID(Id);
		}

		public static void UnpatchAll()
		{
			Logger.Log(Logger.LogChannel.Warn, () => "UnpatchAll has been called - This will remove ALL HARMONY PATCHES.");
			PatchFunctions.UnpatchConditional((Patch _) => true);
		}

		[Obsolete("Use UnpatchSelf() to unpatch the current instance. The functionality to unpatch either other ids or EVERYTHING has been moved the static methods UnpatchID() and UnpatchAll() respectively", true)]
		public void UnpatchAll(string harmonyID = null)
		{
			if (harmonyID == null)
			{
				if (HarmonyGlobalSettings.DisallowLegacyGlobalUnpatchAll)
				{
					Logger.Log(Logger.LogChannel.Warn, () => "Legacy UnpatchAll has been called AND DisallowLegacyGlobalUnpatchAll=true. Skipping execution of UnpatchAll");
				}
				else
				{
					UnpatchAll();
				}
			}
			else if (harmonyID.Length == 0)
			{
				Logger.Log(Logger.LogChannel.Warn, () => "Legacy UnpatchAll was called with harmonyID=\"\" which is an invalid id. Skipping execution of UnpatchAll");
			}
			else
			{
				UnpatchID(harmonyID);
			}
		}

		public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = null)
		{
			CreateProcessor(original).Unpatch(type, harmonyID);
		}

		public void Unpatch(MethodBase original, MethodInfo patch)
		{
			CreateProcessor(original).Unpatch(patch);
		}

		public static bool HasAnyPatches(string harmonyID)
		{
			return (from original in GetAllPatchedMethods()
				select GetPatchInfo(original)).Any((Patches info) => info.Owners.Contains(harmonyID));
		}

		public static Patches GetPatchInfo(MethodBase method)
		{
			return PatchProcessor.GetPatchInfo(method);
		}

		public IEnumerable<MethodBase> GetPatchedMethods()
		{
			return from original in GetAllPatchedMethods()
				where GetPatchInfo(original).Owners.Contains(Id)
				select original;
		}

		public static IEnumerable<MethodBase> GetAllPatchedMethods()
		{
			return PatchProcessor.GetAllPatchedMethods();
		}

		public static MethodBase GetOriginalMethod(MethodInfo replacement)
		{
			if ((object)replacement == null)
			{
				throw new ArgumentNullException("replacement");
			}
			return PatchManager.GetOriginal(replacement);
		}

		public static MethodBase GetMethodFromStackframe(StackFrame frame)
		{
			if (frame == null)
			{
				throw new ArgumentNullException("frame");
			}
			return PatchManager.FindReplacement(frame) ?? frame.GetMethod();
		}

		public static Dictionary<string, Version> VersionInfo(out Version currentVersion)
		{
			return PatchProcessor.VersionInfo(out currentVersion);
		}

		public static Harmony CreateAndPatchAll(Type type, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(type);
			return harmony;
		}

		public static Harmony CreateAndPatchAll(Assembly assembly, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(assembly);
			return harmony;
		}
	}
	[Serializable]
	public class HarmonyException : Exception
	{
		private Dictionary<int, CodeInstruction> instructions;

		private int errorOffset;

		internal HarmonyException()
		{
		}

		internal HarmonyException(string message)
			: base(message)
		{
		}

		internal HarmonyException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		protected HarmonyException(SerializationInfo serializationInfo, StreamingContext streamingContext)
		{
			throw new NotImplementedException();
		}

		internal HarmonyException(Exception innerException, Dictionary<int, CodeInstruction> instructions, int errorOffset)
			: base("IL Compile Error", innerException)
		{
			this.instructions = instructions;
			this.errorOffset = errorOffset;
		}

		internal static Exception Create(Exception ex, MethodBody body)
		{
			Match match = Regex.Match(ex.Message.TrimEnd(new char[0]), "Reason: Invalid IL code in.+: IL_(\\d{4}): (.+)$");
			if (!match.Success)
			{
				return new HarmonyException("IL Compile Error (unknown location)", ex);
			}
			Dictionary<int, CodeInstruction> dictionary = ILManipulator.GetInstructions(body) ?? new Dictionary<int, CodeInstruction>();
			int num = int.Parse(match.Groups[1].Value, NumberStyles.HexNumber);
			Regex.Replace(match.Groups[2].Value, " {2,}", " ");
			if (ex is HarmonyException ex2)
			{
				if (dictionary.Count != 0)
				{
					ex2.instructions = dictionary;
					ex2.errorOffset = num;
				}
				return ex2;
			}
			return new HarmonyException(ex, dictionary, num);
		}

		public List<KeyValuePair<int, CodeInstruction>> GetInstructionsWithOffsets()
		{
			return instructions.OrderBy((KeyValuePair<int, CodeInstruction> ins) => ins.Key).ToList();
		}

		public List<CodeInstruction> GetInstructions()
		{
			return (from ins in instructions
				orderby ins.Key
				select ins.Value).ToList();
		}

		public int GetErrorOffset()
		{
			return errorOffset;
		}

		public int GetErrorIndex()
		{
			if (instructions.TryGetValue(errorOffset, out var value))
			{
				return GetInstructions().IndexOf(value);
			}
			return -1;
		}
	}
	public static class HarmonyGlobalSettings
	{
		public static bool DisallowLegacyGlobalUnpatchAll { get; set; }
	}
	public class HarmonyMethod
	{
		public MethodInfo method;

		public Type declaringType;

		public string methodName;

		public MethodType? methodType;

		public Type[] argumentTypes;

		public int priority = -1;

		public string[] before;

		public string[] after;

		public HarmonyReversePatchType? reversePatchType;

		public bool? debug;

		public string debugEmitPath;

		public bool nonVirtualDelegate;

		public bool? wrapTryCatch;

		internal string assemblyQualifiedDeclaringTypeName;

		public HarmonyMethod()
		{
		}

		private void ImportMethod(MethodInfo theMethod)
		{
			method = theMethod;
			if ((object)method != null)
			{
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(method);
				if (fromMethod != null)
				{
					Merge(fromMethod).CopyTo(this);
				}
			}
		}

		public HarmonyMethod(MethodInfo method)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			ImportMethod(method);
		}

		public HarmonyMethod(MethodInfo method, int priority = -1, string[] before = null, string[] after = null, bool? debug = null)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			ImportMethod(method);
			this.priority = priority;
			this.before = before;
			this.after = after;
			this.debug = debug;
		}

		public HarmonyMethod(Type methodType, string methodName, Type[] argumentTypes = null)
		{
			MethodInfo methodInfo = AccessTools.Method(methodType, methodName, argumentTypes);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException($"Cannot not find method for type {methodType} and name {methodName} and parameters {argumentTypes?.Description()}");
			}
			ImportMethod(methodInfo);
		}

		public static List<string> HarmonyFields()
		{
			return (from s in AccessTools.GetFieldNames(typeof(HarmonyMethod))
				where s != "method"
				select s).ToList();
		}

		public static HarmonyMethod Merge(List<HarmonyMethod> attributes)
		{
			return Merge((IEnumerable<HarmonyMethod>)attributes);
		}

		internal static HarmonyMethod Merge(IEnumerable<HarmonyMethod> attributes)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			if (attributes == null)
			{
				return harmonyMethod;
			}
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			attributes.Do(delegate(HarmonyMethod attribute)
			{
				Traverse trv = Traverse.Create(attribute);
				HarmonyFields().ForEach(delegate(string f)
				{
					object value = trv.Field(f).GetValue();
					if (value != null && (f != "priority" || (int)value != -1))
					{
						HarmonyMethodExtensions.SetValue(resultTrv, f, value);
					}
				});
			});
			return harmonyMethod;
		}

		public override string ToString()
		{
			string result = "";
			Traverse trv = Traverse.Create(this);
			HarmonyFields().ForEach(delegate(string f)
			{
				if (result.Length > 0)
				{
					result += ", ";
				}
				result += $"{f}={trv.Field(f).GetValue()}";
			});
			return "HarmonyMethod[" + result + "]";
		}

		internal string Description()
		{
			string text = (((object)declaringType != null) ? declaringType.FullName : ((assemblyQualifiedDeclaringTypeName != null) ? assemblyQualifiedDeclaringTypeName : "undefined"));
			string text2 = methodName ?? "undefined";
			string text3 = (methodType.HasValue ? methodType.Value.ToString() : "undefined");
			string text4 = ((argumentTypes != null) ? argumentTypes.Description() : "undefined");
			return "(class=" + text + ", methodname=" + text2 + ", type=" + text3 + ", args=" + text4 + ")";
		}

		internal Type GetDeclaringType()
		{
			if ((object)declaringType == null && assemblyQualifiedDeclaringTypeName != null)
			{
				declaringType = Type.GetType(assemblyQualifiedDeclaringTypeName, throwOnError: true);
			}
			return declaringType;
		}

		internal Type[] GetArgumentList()
		{
			return argumentTypes ?? EmptyType.NoArgs;
		}
	}
	internal static class EmptyType
	{
		internal static readonly Type[] NoArgs = new Type[0];
	}
	public static class HarmonyMethodExtensions
	{
		internal static void SetValue(Traverse trv, string name, object val)
		{
			if (val != null)
			{
				Traverse traverse = trv.Field(name);
				if (name == "methodType" || name == "reversePatchType")
				{
					val = Enum.ToObject(Nullable.GetUnderlyingType(traverse.GetValueType()), (int)val);
				}
				traverse.SetValue(val);
			}
		}

		public static void CopyTo(this HarmonyMethod from, HarmonyMethod to)
		{
			if (to == null)
			{
				return;
			}
			Traverse fromTrv = Traverse.Create(from);
			Traverse toTrv = Traverse.Create(to);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = fromTrv.Field(f).GetValue();
				if (value != null)
				{
					SetValue(toTrv, f, value);
				}
			});
		}

		public static HarmonyMethod Clone(this HarmonyMethod original)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			original.CopyTo(harmonyMethod);
			return harmonyMethod;
		}

		public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail)
		{
			if (detail == null)
			{
				return master;
			}
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			Traverse masterTrv = Traverse.Create(master);
			Traverse detailTrv = Traverse.Create(detail);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = masterTrv.Field(f).GetValue();
				object value2 = detailTrv.Field(f).GetValue();
				if (f != "priority" || (int)value2 != -1)
				{
					SetValue(resultTrv, f, value2 ?? value);
				}
			});
			return harmonyMethod;
		}

		private static HarmonyMethod GetHarmonyMethodInfo(object attribute)
		{
			FieldInfo field = attribute.GetType().GetField("info", AccessTools.all);
			if ((object)field == null)
			{
				return null;
			}
			if (field.FieldType.FullName != typeof(HarmonyMethod).FullName)
			{
				return null;
			}
			return AccessTools.MakeDeepCopy<HarmonyMethod>(field.GetValue(attribute));
		}

		public static List<HarmonyMethod> GetFromType(Type type)
		{
			return (from attr in type.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}

		public static HarmonyMethod GetMergedFromType(Type type)
		{
			return HarmonyMethod.Merge(GetFromType(type));
		}

		public static List<HarmonyMethod> GetFromMethod(MethodBase method)
		{
			return (from attr in method.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}

		public static HarmonyMethod GetMergedFromMethod(MethodBase method)
		{
			return HarmonyMethod.Merge(GetFromMethod(method));
		}
	}
	public class InlineSignature : ICallSiteGenerator
	{
		public class ModifierType
		{
			public bool IsOptional;

			public Type Modifier;

			public object Type;

			public override string ToString()
			{
				return ((Type is Type type) ? type.FullDescription() : Type?.ToString()) + " mod" + (IsOptional ? "opt" : "req") + "(" + Modifier?.FullDescription() + ")";
			}

			internal TypeReference ToTypeReference(ModuleDefinition module)
			{
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Expected O, but got Unknown
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Expected O, but got Unknown
				if (!IsOptional)
				{
					return (TypeReference)new RequiredModifierType(module.ImportReference(Modifier), GetTypeReference(module, Type));
				}
				return (TypeReference)new OptionalModifierType(module.ImportReference(Modifier), GetTypeReference(module, Type));
			}
		}

		public bool HasThis { get; set; }

		public bool ExplicitThis { get; set; }

		public CallingConvention CallingConvention { get; set; } = CallingConvention.Winapi;


		public List<object> Parameters { get; set; } = new List<object>();


		public object ReturnType { get; set; } = typeof(void);


		public override string ToString()
		{
			return ((ReturnType is Type type) ? type.FullDescription() : ReturnType?.ToString()) + " (" + Parameters.Join((object p) => (!(p is Type type2)) ? p?.ToString() : type2.FullDescription()) + ")";
		}

		internal static TypeReference GetTypeReference(ModuleDefinition module, object param)
		{
			if (!(param is Type type))
			{
				if (!(param is InlineSignature inlineSignature))
				{
					if (param is ModifierType modifierType)
					{
						return modifierType.ToTypeReference(module);
					}
					throw new NotSupportedException($"Unsupported inline signature parameter type: {param} ({param?.GetType().FullDescription()})");
				}
				return (TypeReference)(object)inlineSignature.ToFunctionPointer(module);
			}
			return module.ImportReference(type);
		}

		CallSite ICallSiteGenerator.ToCallSite(ModuleDefinition module)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: 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
			CallSite val = new CallSite(GetTypeReference(module, ReturnType))
			{
				HasThis = HasThis,
				ExplicitThis = ExplicitThis,
				CallingConvention = (MethodCallingConvention)(byte)((byte)CallingConvention - 1)
			};
			foreach (object parameter in Parameters)
			{
				val.Parameters.Add(new ParameterDefinition(GetTypeReference(module, parameter)));
			}
			return val;
		}

		private FunctionPointerType ToFunctionPointer(ModuleDefinition module)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			FunctionPointerType val = new FunctionPointerType
			{
				ReturnType = GetTypeReference(module, ReturnType),
				HasThis = HasThis,
				ExplicitThis = ExplicitThis,
				CallingConvention = (MethodCallingConvention)(byte)((byte)CallingConvention - 1)
			};
			foreach (object parameter in Parameters)
			{
				val.Parameters.Add(new ParameterDefinition(GetTypeReference(module, parameter)));
			}
			return val;
		}
	}
	internal static class PatchInfoSerialization
	{
		private class Binder : SerializationBinder
		{
			public override Type BindToType(string assemblyName, string typeName)
			{
				Type[] array = new Type[3]
				{
					typeof(PatchInfo),
					typeof(Patch[]),
					typeof(Patch)
				};
				foreach (Type type in array)
				{
					if (typeName == type.FullName)
					{
						return type;
					}
				}
				return Type.GetType($"{typeName}, {assemblyName}");
			}
		}

		internal static byte[] Serialize(this PatchInfo patchInfo)
		{
			using MemoryStream memoryStream = new MemoryStream();
			new BinaryFormatter().Serialize(memoryStream, patchInfo);
			return memoryStream.GetBuffer();
		}

		internal static PatchInfo Deserialize(byte[] bytes)
		{
			BinaryFormatter obj = new BinaryFormatter
			{
				Binder = new Binder()
			};
			MemoryStream serializationStream = new MemoryStream(bytes);
			return (PatchInfo)obj.Deserialize(serializationStream);
		}

		internal static int PriorityComparer(object obj, int index, int priority)
		{
			Traverse traverse = Traverse.Create(obj);
			int value = traverse.Field("priority").GetValue<int>();
			int value2 = traverse.Field("index").GetValue<int>();
			if (priority != value)
			{
				return -priority.CompareTo(value);
			}
			return index.CompareTo(value2);
		}
	}
	[Serializable]
	public class PatchInfo
	{
		public Patch[] prefixes = new Patch[0];

		public Patch[] postfixes = new Patch[0];

		public Patch[] transpilers = new Patch[0];

		public Patch[] finalizers = new Patch[0];

		public Patch[] ilmanipulators = new Patch[0];

		public bool Debugging
		{
			get
			{
				if (!prefixes.Any((Patch p) => p.debug) && !postfixes.Any((Patch p) => p.debug) && !transpilers.Any((Patch p) => p.debug) && !finalizers.Any((Patch p) => p.debug))
				{
					return ilmanipulators.Any((Patch p) => p.debug);
				}
				return true;
			}
		}

		public string[] DebugEmitPaths => (from p in prefixes.Concat(postfixes).Concat(transpilers).Concat(finalizers)
				.Concat(ilmanipulators)
			select p.debugEmitPath into p
			where p != null
			select p).ToArray();

		internal void AddPrefixes(string owner, params HarmonyMethod[] methods)
		{
			prefixes = Add(owner, methods, prefixes);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddPrefix(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddPrefixes(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemovePrefix(string owner)
		{
			prefixes = Remove(owner, prefixes);
		}

		internal void AddPostfixes(string owner, params HarmonyMethod[] methods)
		{
			postfixes = Add(owner, methods, postfixes);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddPostfix(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddPostfixes(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemovePostfix(string owner)
		{
			postfixes = Remove(owner, postfixes);
		}

		internal void AddTranspilers(string owner, params HarmonyMethod[] methods)
		{
			transpilers = Add(owner, methods, transpilers);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddTranspiler(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddTranspilers(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemoveTranspiler(string owner)
		{
			transpilers = Remove(owner, transpilers);
		}

		internal void AddFinalizers(string owner, params HarmonyMethod[] methods)
		{
			finalizers = Add(owner, methods, finalizers);
		}

		[Obsolete("This method only exists for backwards compatibility since the class is public.")]
		public void AddFinalizer(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug)
		{
			AddFinalizers(owner, new HarmonyMethod(patch, priority, before, after, debug));
		}

		public void RemoveFinalizer(string owner)
		{
			finalizers = Remove(owner, finalizers);
		}

		internal void AddILManipulators(string owner, params HarmonyMethod[] methods)
		{
			ilmanipulators = Add(owner, methods, ilmanipulators);
		}

		public void RemoveILManipulator(string owner)
		{
			ilmanipulators = Remove(owner, ilmanipulators);
		}

		public void RemovePatch(MethodInfo patch)
		{
			prefixes = prefixes.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			postfixes = postfixes.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			transpilers = transpilers.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			finalizers = finalizers.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
			ilmanipulators = ilmanipulators.Where((Patch p) => (object)p.PatchMethod != patch).ToArray();
		}

		private static Patch[] Add(string owner, HarmonyMethod[] add, Patch[] current)
		{
			if (add.Length == 0)
			{
				return current;
			}
			int initialIndex = current.Length;
			return current.Concat(add.Where((HarmonyMethod method) => method != null).Select((HarmonyMethod method, int i) => new Patch(method, i + initialIndex, owner))).ToArray();
		}

		private static Patch[] Remove(string owner, Patch[] current)
		{
			if (!(owner == "*"))
			{
				return current.Where((Patch patch) => patch.owner != owner).ToArray();
			}
			return new Patch[0];
		}
	}
	[Serializable]
	public class Patch : IComparable
	{
		public readonly int index;

		public readonly string owner;

		public readonly int priority;

		public readonly string[] before;

		public readonly string[] after;

		public readonly bool debug;

		public readonly string debugEmitPath;

		public readonly bool wrapTryCatch;

		[NonSerialized]
		private MethodInfo patchMethod;

		private int methodToken;

		private string moduleGUID;

		public MethodInfo PatchMethod
		{
			get
			{
				if ((object)patchMethod == null)
				{
					Module module = (from a in AppDomain.CurrentDomain.GetAssemblies()
						where !a.FullName.StartsWith("Microsoft.VisualStudio")
						select a).SelectMany((Assembly a) => a.GetLoadedModules()).First((Module m) => m.ModuleVersionId.ToString() == moduleGUID);
					patchMethod = (MethodInfo)module.ResolveMethod(methodToken);
				}
				return patchMethod;
			}
			set
			{
				patchMethod = value;
				methodToken = patchMethod.MetadataToken;
				moduleGUID = patchMethod.Module.ModuleVersionId.ToString();
			}
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug)
		{
			if (patch is DynamicMethod)
			{
				throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method.");
			}
			this.index = index;
			this.owner = owner;
			this.priority = ((priority == -1) ? 400 : priority);
			this.before = before ?? new string[0];
			this.after = after ?? new string[0];
			this.debug = debug;
			PatchMethod = patch;
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug, bool wrapTryCatch)
		{
			if (patch is DynamicMethod)
			{
				throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method.");
			}
			this.index = index;
			this.owner = owner;
			this.priority = ((priority == -1) ? 400 : priority);
			this.before = before ?? new string[0];
			this.after = after ?? new string[0];
			this.debug = debug;
			this.wrapTryCatch = wrapTryCatch;
			PatchMethod = patch;
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug, bool wrapTryCatch, string debugEmitPath)
		{
			if (patch is DynamicMethod)
			{
				throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method.");
			}
			this.index = index;
			this.owner = owner;
			this.priority = ((priority == -1) ? 400 : priority);
			this.before = before ?? new string[0];
			this.after = after ?? new string[0];
			this.debug = debug;
			this.debugEmitPath = debugEmitPath;
			this.wrapTryCatch = wrapTryCatch;
			PatchMethod = patch;
		}

		public Patch(HarmonyMethod method, int index, string owner)
			: this(method.method, index, owner, method.priority, method.before, method.after, method.debug.GetValueOrDefault(), method.wrapTryCatch.GetValueOrDefault(), method.debugEmitPath)
		{
		}

		public MethodInfo GetMethod(MethodBase original)
		{
			MethodInfo methodInfo = PatchMethod;
			if ((object)methodInfo.ReturnType != typeof(DynamicMethod) && (object)methodInfo.ReturnType != typeof(MethodInfo))
			{
				return methodInfo;
			}
			if (!methodInfo.IsStatic)
			{
				return methodInfo;
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			if (parameters.Length != 1)
			{
				return methodInfo;
			}
			if ((object)parameters[0].ParameterType != typeof(MethodBase))
			{
				return methodInfo;
			}
			return methodInfo.Invoke(null, new object[1] { original }) as MethodInfo;
		}

		public override bool Equals(object obj)
		{
			if (obj != null && obj is Patch)
			{
				return (object)PatchMethod == ((Patch)obj).PatchMethod;
			}
			return false;
		}

		public int CompareTo(object obj)
		{
			return PatchInfoSerialization.PriorityComparer(obj, index, priority);
		}

		public override int GetHashCode()
		{
			return PatchMethod.GetHashCode();
		}
	}
	public class PatchClassProcessor
	{
		private readonly Harmony instance;

		private readonly Type containerType;

		private readonly HarmonyMethod containerAttributes;

		private readonly Dictionary<Type, MethodInfo> auxilaryMethods;

		private readonly List<AttributePatch> patchMethods;

		private static readonly List<Type> auxilaryTypes = new List<Type>
		{
			typeof(HarmonyPrepare),
			typeof(HarmonyCleanup),
			typeof(HarmonyTargetMethod),
			typeof(HarmonyTargetMethods)
		};

		public PatchClassProcessor(Harmony instance, Type type)
			: this(instance, type, allowUnannotatedType: false)
		{
		}

		public PatchClassProcessor(Harmony instance, Type type, bool allowUnannotatedType)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			this.instance = instance;
			containerType = type;
			List<HarmonyMethod> fromType = HarmonyMethodExtensions.GetFromType(type);
			if (!allowUnannotatedType && (fromType == null || fromType.Count == 0))
			{
				return;
			}
			containerAttributes = HarmonyMethod.Merge(fromType);
			MethodType? methodType = containerAttributes.methodType;
			if (!methodType.HasValue)
			{
				containerAttributes.methodType = MethodType.Normal;
			}
			auxilaryMethods = new Dictionary<Type, MethodInfo>();
			foreach (Type auxilaryType in auxilaryTypes)
			{
				MethodInfo patchMethod = PatchTools.GetPatchMethod(containerType, auxilaryType.FullName);
				if ((object)patchMethod != null)
				{
					auxilaryMethods[auxilaryType] = patchMethod;
				}
			}
			patchMethods = PatchTools.GetPatchMethods(containerType, (object)containerAttributes.GetDeclaringType() != null);
			foreach (AttributePatch patchMethod2 in patchMethods)
			{
				MethodInfo method = patchMethod2.info.method;
				patchMethod2.info = containerAttributes.Merge(patchMethod2.info);
				patchMethod2.info.method = method;
			}
		}

		public List<MethodInfo> Patch()
		{
			if (containerAttributes == null)
			{
				return null;
			}
			Exception exception = null;
			if (!RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, defaultIfFailing: false, null, new object[0]))
			{
				RunMethod<HarmonyCleanup>(ref exception, new object[0]);
				ReportException(exception, null);
				return new List<MethodInfo>();
			}
			List<MethodInfo> result = new List<MethodInfo>();
			MethodBase lastOriginal = null;
			try
			{
				List<MethodBase> bulkMethods = GetBulkMethods();
				if (bulkMethods.Count == 1)
				{
					lastOriginal = bulkMethods[0];
				}
				ReversePatch(ref lastOriginal);
				result = ((bulkMethods.Count > 0) ? BulkPatch(bulkMethods, ref lastOriginal) : PatchWithAttributes(ref lastOriginal));
			}
			catch (Exception ex)
			{
				exception = ex;
			}
			RunMethod<HarmonyCleanup>(ref exception, new object[1] { exception });
			ReportException(exception, lastOriginal);
			return result;
		}

		private void ReversePatch(ref MethodBase lastOriginal)
		{
			for (int i = 0; i < patchMethods.Count; i++)
			{
				AttributePatch attributePatch = patchMethods[i];
				if (attributePatch.type == HarmonyPatchType.ReversePatch)
				{
					MethodBase originalMethod = attributePatch.info.GetOriginalMethod();
					if ((object)originalMethod != null)
					{
						lastOriginal = originalMethod;
					}
					ReversePatcher reversePatcher = instance.CreateReversePatcher(lastOriginal, attributePatch.info);
					lock (PatchProcessor.locker)
					{
						reversePatcher.Patch();
					}
				}
			}
		}

		private List<MethodInfo> BulkPatch(List<MethodBase> originals, ref MethodBase lastOriginal)
		{
			PatchJobs<MethodInfo> patchJobs = new PatchJobs<MethodInfo>();
			for (int i = 0; i < originals.Count; i++)
			{
				lastOriginal = originals[i];
				PatchJobs<MethodInfo>.Job job = patchJobs.GetJob(lastOriginal);
				foreach (AttributePatch patchMethod in patchMethods)
				{
					string text = "You cannot combine TargetMethod, TargetMethods or [HarmonyPatchAll] with individual annotations";
					HarmonyMethod info = patchMethod.info;
					if (info.methodName != null)
					{
						throw new ArgumentException(text + " [" + info.methodName + "]");
					}
					if (info.methodType.HasValue && info.methodType.Value != 0)
					{
						throw new ArgumentException($"{text} [{info.methodType}]");
					}
					if (info.argumentTypes != null)
					{
						throw new ArgumentException(text + " [" + info.argumentTypes.Description() + "]");
					}
					job.AddPatch(patchMethod);
				}
			}
			foreach (PatchJobs<MethodInfo>.Job job2 in patchJobs.GetJobs())
			{
				lastOriginal = job2.original;
				ProcessPatchJob(job2);
			}
			return patchJobs.GetReplacements();
		}

		private List<MethodInfo> PatchWithAttributes(ref MethodBase lastOriginal)
		{
			PatchJobs<MethodInfo> patchJobs = new PatchJobs<MethodInfo>();
			foreach (AttributePatch patchMethod in patchMethods)
			{
				lastOriginal = patchMethod.info.GetOriginalMethod();
				if ((object)lastOriginal == null)
				{
					throw new ArgumentException("Undefined target method for patch method " + patchMethod.info.method.FullDescription());
				}
				patchJobs.GetJob(lastOriginal).AddPatch(patchMethod);
			}
			foreach (PatchJob

FrozenDevv-ModPack-1.1.0/BepInEx/core/0Harmony20.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using HarmonyLib.Internal;
using HarmonyLib.Internal.Patching;
using HarmonyLib.Internal.Util;
using HarmonyLib.Tools;
using HarmonyXInterop;
using JetBrains.Annotations;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.Utils;
using MonoMod.Utils.Cil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("HarmonyX2Interop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HarmonyX2Interop")]
[assembly: AssemblyCopyright("Copyright ©  2020")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("69F6541D-A0F5-419D-B0EE-F5017F1D34F3")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.0.0")]
[module: UnverifiableCode]
namespace JetBrains.Annotations
{
	[AttributeUsage(AttributeTargets.All)]
	internal sealed class UsedImplicitlyAttribute : Attribute
	{
		public ImplicitUseKindFlags UseKindFlags { get; }

		public ImplicitUseTargetFlags TargetFlags { get; }

		public UsedImplicitlyAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter | AttributeTargets.GenericParameter)]
	internal sealed class MeansImplicitUseAttribute : Attribute
	{
		[UsedImplicitly]
		public ImplicitUseKindFlags UseKindFlags { get; }

		[UsedImplicitly]
		public ImplicitUseTargetFlags TargetFlags { get; }

		public MeansImplicitUseAttribute()
			: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
			: this(useKindFlags, ImplicitUseTargetFlags.Default)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
			: this(ImplicitUseKindFlags.Default, targetFlags)
		{
		}

		public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
		{
			UseKindFlags = useKindFlags;
			TargetFlags = targetFlags;
		}
	}
	[Flags]
	internal enum ImplicitUseKindFlags
	{
		Default = 7,
		Access = 1,
		Assign = 2,
		InstantiatedWithFixedConstructorSignature = 4,
		InstantiatedNoFixedConstructorSignature = 8
	}
	[Flags]
	internal enum ImplicitUseTargetFlags
	{
		Default = 1,
		Itself = 1,
		Members = 2,
		WithInheritors = 4,
		WithMembers = 3
	}
}
namespace HarmonyLib
{
	public static class Priority
	{
		public const int Last = 0;

		public const int VeryLow = 100;

		public const int Low = 200;

		public const int LowerThanNormal = 300;

		public const int Normal = 400;

		public const int HigherThanNormal = 500;

		public const int High = 600;

		public const int VeryHigh = 700;

		public const int First = 800;
	}
	public enum MethodType
	{
		Normal,
		Getter,
		Setter,
		Constructor,
		StaticConstructor
	}
	public enum ArgumentType
	{
		Normal,
		Ref,
		Out,
		Pointer
	}
	public enum HarmonyPatchType
	{
		All,
		Prefix,
		Postfix,
		Transpiler,
		Finalizer,
		ReversePatch
	}
	public enum HarmonyReversePatchType
	{
		Original,
		Snapshot
	}
	[MeansImplicitUse]
	public class HarmonyAttribute : Attribute
	{
		public HarmonyMethod info = new HarmonyMethod();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
	public class HarmonyPatch : HarmonyAttribute
	{
		public HarmonyPatch()
		{
		}

		public HarmonyPatch(Type declaringType)
		{
			info.declaringType = declaringType;
		}

		public HarmonyPatch(Type declaringType, Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
		}

		public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type declaringType, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.declaringType = declaringType;
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type declaringType, string methodName, MethodType methodType)
		{
			info.declaringType = declaringType;
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(string methodName)
		{
			info.methodName = methodName;
		}

		public HarmonyPatch(string methodName, params Type[] argumentTypes)
		{
			info.methodName = methodName;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodName = methodName;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(string methodName, MethodType methodType)
		{
			info.methodName = methodName;
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType)
		{
			info.methodType = methodType;
		}

		public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
		{
			info.methodType = methodType;
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			info.methodType = methodType;
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		public HarmonyPatch(Type[] argumentTypes)
		{
			info.argumentTypes = argumentTypes;
		}

		public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			ParseSpecialArguments(argumentTypes, argumentVariations);
		}

		private void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations)
		{
			if (argumentVariations == null || argumentVariations.Length == 0)
			{
				info.argumentTypes = argumentTypes;
				return;
			}
			if (argumentTypes.Length < argumentVariations.Length)
			{
				throw new ArgumentException("argumentVariations contains more elements than argumentTypes", "argumentVariations");
			}
			List<Type> list = new List<Type>();
			for (int i = 0; i < argumentTypes.Length; i++)
			{
				Type type = argumentTypes[i];
				switch (argumentVariations[i])
				{
				case ArgumentType.Ref:
				case ArgumentType.Out:
					type = type.MakeByRefType();
					break;
				case ArgumentType.Pointer:
					type = type.MakePointerType();
					break;
				}
				list.Add(type);
			}
			info.argumentTypes = list.ToArray();
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
	public class HarmonyReversePatch : HarmonyAttribute
	{
		public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
		{
			info.reversePatchType = type;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	public class HarmonyPatchAll : HarmonyAttribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyPriority : HarmonyAttribute
	{
		public HarmonyPriority(int priority)
		{
			info.priority = priority;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyBefore : HarmonyAttribute
	{
		public HarmonyBefore(params string[] before)
		{
			info.before = before;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	public class HarmonyAfter : HarmonyAttribute
	{
		public HarmonyAfter(params string[] after)
		{
			info.after = after;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrepare : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyCleanup : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethod : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTargetMethods : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPrefix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyPostfix : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyTranspiler : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class HarmonyFinalizer : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)]
	public class HarmonyArgument : Attribute
	{
		public string OriginalName { get; private set; }

		public int Index { get; private set; }

		public string NewName { get; private set; }

		public HarmonyArgument(string originalName)
			: this(originalName, null)
		{
		}

		public HarmonyArgument(int index)
			: this(index, null)
		{
		}

		public HarmonyArgument(string originalName, string newName)
		{
			OriginalName = originalName;
			Index = -1;
			NewName = newName;
		}

		public HarmonyArgument(int index, string name)
		{
			OriginalName = null;
			Index = index;
			NewName = name;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public class ParameterByRefAttribute : Attribute
	{
		public int[] ParameterIndices { get; }

		public ParameterByRefAttribute(params int[] parameterIndices)
		{
			ParameterIndices = parameterIndices;
		}
	}
	public class InvalidHarmonyPatchArgumentException : Exception
	{
		public MethodBase Original { get; }

		public MethodInfo Patch { get; }

		public override string Message => "(" + Extensions.GetID((MethodBase)Patch, (string)null, (string)null, true, false, false) + "): " + base.Message;

		public InvalidHarmonyPatchArgumentException(string message, MethodBase original, MethodInfo patch)
			: base(message)
		{
			Original = original;
			Patch = patch;
		}
	}
	public class MemberNotFoundException : Exception
	{
		public MemberNotFoundException(string message)
			: base(message)
		{
		}
	}
	public class Harmony
	{
		[Obsolete("No longer used, subscribe to Logger.LogChannel.Info")]
		public static bool DEBUG;

		[Obsolete("Not supported by HarmonyX", true)]
		public static bool SELF_PATCHING;

		public string Id { get; private set; }

		public Harmony(string id)
		{
			if (string.IsNullOrEmpty(id))
			{
				throw new ArgumentException("id cannot be null or empty");
			}
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				Assembly assembly = typeof(Harmony).Assembly;
				Version version = assembly.GetName().Version;
				string text = assembly.Location;
				if (string.IsNullOrEmpty(text))
				{
					text = new Uri(assembly.CodeBase).LocalPath;
				}
				MethodBase outsideCaller = AccessTools.GetOutsideCaller();
				Assembly assembly2 = outsideCaller.DeclaringType?.Assembly;
				string text2 = assembly2?.Location;
				if (string.IsNullOrEmpty(text2))
				{
					text2 = (((object)assembly2 != null) ? new Uri(assembly2.CodeBase).LocalPath : string.Empty);
				}
				return $"Created Harmony instance id={id}, version={version}, location={text} - Started from {Extensions.GetID(outsideCaller, (string)null, (string)null, true, false, false)} location={text2}";
			});
			Id = id;
		}

		public void PatchAll()
		{
			Assembly assembly = new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly;
			PatchAll(assembly);
		}

		public PatchProcessor ProcessorForAnnotatedClass(Type type)
		{
			List<HarmonyMethod> fromType = HarmonyMethodExtensions.GetFromType(type);
			if (fromType != null && fromType.Any())
			{
				HarmonyMethod attributes = HarmonyMethod.Merge(fromType);
				return new PatchProcessor(this, type, attributes);
			}
			return null;
		}

		public void PatchAll(Assembly assembly)
		{
			if ((object)assembly == null)
			{
				throw new ArgumentNullException("assembly");
			}
			List<PatchProcessor> list = (from x in assembly.GetTypes().Select(ProcessorForAnnotatedClass)
				where x != null
				select x).ToList();
			foreach (PatchProcessor item in list)
			{
				item.Patch();
			}
			if (list.Count == 0)
			{
				Logger.Log(Logger.LogChannel.Warn, () => "Could not find any valid Harmony patches inside of assembly " + assembly.FullName);
			}
		}

		public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null)
		{
			PatchProcessor patchProcessor = new PatchProcessor(this, original);
			patchProcessor.AddPrefix(prefix);
			patchProcessor.AddPostfix(postfix);
			patchProcessor.AddTranspiler(transpiler);
			patchProcessor.AddFinalizer(finalizer);
			return patchProcessor.Patch().FirstOrDefault();
		}

		public MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler = null)
		{
			return null;
		}

		public ReversePatcher CreateReversePatcher(MethodBase original, MethodInfo standin)
		{
			return new ReversePatcher(this, original, standin);
		}

		public void UnpatchAll(string harmonyID = null)
		{
			foreach (MethodBase item in GetAllPatchedMethods().ToList())
			{
				Patches patchInfo = GetPatchInfo(item);
				UnpatchAllId(item, patchInfo.Prefixes);
				UnpatchAllId(item, patchInfo.Postfixes);
				UnpatchAllId(item, patchInfo.Transpilers);
				UnpatchAllId(item, patchInfo.Finalizers);
			}
			void UnpatchAllId(MethodBase original, IEnumerable<Patch> patches)
			{
				foreach (Patch patch in patches)
				{
					if (harmonyID == null || patch.owner == harmonyID)
					{
						Unpatch(original, patch.patch);
					}
				}
			}
		}

		public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = null)
		{
			new PatchProcessor(this, original).Unpatch(type, harmonyID);
		}

		public void Unpatch(MethodBase original, MethodInfo patch)
		{
			new PatchProcessor(this, original).Unpatch(patch);
		}

		public static bool HasAnyPatches(string harmonyID)
		{
			return GetAllPatchedMethods().Select(GetPatchInfo).Any((Patches info) => info.Owners.Contains(harmonyID));
		}

		public static Patches GetPatchInfo(MethodBase method)
		{
			return PatchProcessor.GetPatchInfo(method);
		}

		public IEnumerable<MethodBase> GetPatchedMethods()
		{
			return from original in GetAllPatchedMethods()
				where GetPatchInfo(original).Owners.Contains(Id)
				select original;
		}

		public static IEnumerable<MethodBase> GetAllPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		public static Dictionary<string, Version> VersionInfo(out Version currentVersion)
		{
			return PatchProcessor.VersionInfo(out currentVersion);
		}

		public void PatchAll(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(methodInfo);
				if (fromMethod != null && fromMethod.Any())
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(inherit: true);
					HarmonyMethod combinedInfo = HarmonyMethod.Merge(fromMethod);
					List<HarmonyMethod> list = fromMethod.Where(IsMethodComplete).ToList();
					if (fromMethod.All((HarmonyMethod x) => (object)x.declaringType != combinedInfo.declaringType && x.methodName != combinedInfo.methodName))
					{
						list.Add(combinedInfo);
					}
					List<MethodBase> list2 = new List<MethodBase>();
					foreach (HarmonyMethod item in list)
					{
						foreach (int item2 in customAttributes.OfType<ParameterByRefAttribute>().SelectMany((ParameterByRefAttribute x) => x.ParameterIndices))
						{
							if (!item.argumentTypes[item2].IsByRef)
							{
								item.argumentTypes[item2] = item.argumentTypes[item2].MakeByRefType();
							}
						}
						if (!item.methodType.HasValue)
						{
							item.methodType = MethodType.Normal;
						}
						if ((object)item.method == null)
						{
							item.method = methodInfo;
						}
						MethodBase originalMethod = PatchProcessor.GetOriginalMethod(item);
						if ((object)originalMethod != null)
						{
							list2.Add(originalMethod);
						}
					}
					PatchProcessor patchProcessor = new PatchProcessor(this);
					foreach (MethodBase item3 in list2)
					{
						patchProcessor.AddOriginal(item3);
					}
					if (customAttributes.Any((object x) => x is HarmonyPrefix))
					{
						patchProcessor.AddPrefix(new HarmonyMethod(methodInfo));
					}
					if (customAttributes.Any((object x) => x is HarmonyTranspiler))
					{
						patchProcessor.AddTranspiler(new HarmonyMethod(methodInfo));
					}
					if (customAttributes.Any((object x) => x is HarmonyPostfix))
					{
						patchProcessor.AddPostfix(new HarmonyMethod(methodInfo));
					}
					if (customAttributes.Any((object x) => x is HarmonyFinalizer))
					{
						patchProcessor.AddFinalizer(new HarmonyMethod(methodInfo));
					}
					patchProcessor.Patch();
				}
				else if ((Logger.ChannelFilter & Logger.LogChannel.Warn) != 0 && methodInfo.GetCustomAttributes(typeof(HarmonyAttribute), inherit: true).Any())
				{
					Logger.LogText(Logger.LogChannel.Warn, "Method " + methodInfo.FullDescription() + " has an invalid combination of Harmony attributes and will be ignored");
				}
			}
			static bool IsMethodComplete(HarmonyMethod m)
			{
				if ((object)m.declaringType != null)
				{
					if (m.methodName == null && m.methodType != MethodType.Constructor)
					{
						return m.methodType == MethodType.StaticConstructor;
					}
					return true;
				}
				return false;
			}
		}

		public static Harmony CreateAndPatchAll(Type type, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(type);
			return harmony;
		}

		public static Harmony CreateAndPatchAll(Assembly assembly, string harmonyInstanceId = null)
		{
			Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}");
			harmony.PatchAll(assembly);
			return harmony;
		}
	}
	public class HarmonyMethod
	{
		public MethodInfo method;

		public Type declaringType;

		public string methodName;

		public MethodType? methodType;

		public Type[] argumentTypes;

		public int priority = -1;

		public string[] before;

		public string[] after;

		public HarmonyReversePatchType? reversePatchType;

		public HarmonyMethod()
		{
		}

		private void ImportMethod(MethodInfo theMethod)
		{
			method = theMethod;
			if ((object)method != null)
			{
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(method);
				if (fromMethod != null)
				{
					Merge(fromMethod).CopyTo(this);
				}
			}
		}

		public HarmonyMethod(MethodInfo method)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			ImportMethod(method);
		}

		public HarmonyMethod(Type type, string name, Type[] parameters = null)
		{
			MethodInfo methodInfo = AccessTools.Method(type, name, parameters);
			if ((object)methodInfo == null)
			{
				throw new ArgumentException($"Cannot not find method for type {type} and name {name} and parameters {parameters?.Description()}");
			}
			ImportMethod(methodInfo);
		}

		public static List<string> HarmonyFields()
		{
			return (from s in AccessTools.GetFieldNames(typeof(HarmonyMethod))
				where s != "method"
				select s).ToList();
		}

		public static HarmonyMethod Merge(List<HarmonyMethod> attributes)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			if (attributes == null)
			{
				return harmonyMethod;
			}
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			attributes.ForEach(delegate(HarmonyMethod attribute)
			{
				Traverse trv = Traverse.Create(attribute);
				HarmonyFields().ForEach(delegate(string f)
				{
					object value = trv.Field(f).GetValue();
					if (value != null)
					{
						HarmonyMethodExtensions.SetValue(resultTrv, f, value);
					}
				});
			});
			return harmonyMethod;
		}

		public override string ToString()
		{
			string result = "HarmonyMethod[";
			Traverse trv = Traverse.Create(this);
			HarmonyFields().ForEach(delegate(string f)
			{
				result += $"{f}{'='}{trv.Field(f).GetValue()}";
			});
			return result + "]";
		}
	}
	public static class HarmonyMethodExtensions
	{
		internal static void SetValue(Traverse trv, string name, object val)
		{
			if (val != null)
			{
				Traverse traverse = trv.Field(name);
				if (name == "methodType" || name == "reversePatchType")
				{
					val = Enum.ToObject(Nullable.GetUnderlyingType(traverse.GetValueType()), (int)val);
				}
				traverse.SetValue(val);
			}
		}

		public static void CopyTo(this HarmonyMethod from, HarmonyMethod to)
		{
			if (to == null)
			{
				return;
			}
			Traverse fromTrv = Traverse.Create(from);
			Traverse toTrv = Traverse.Create(to);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = fromTrv.Field(f).GetValue();
				if (value != null)
				{
					SetValue(toTrv, f, value);
				}
			});
		}

		public static HarmonyMethod Clone(this HarmonyMethod original)
		{
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			original.CopyTo(harmonyMethod);
			return harmonyMethod;
		}

		public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail)
		{
			if (detail == null)
			{
				return master;
			}
			HarmonyMethod harmonyMethod = new HarmonyMethod();
			Traverse resultTrv = Traverse.Create(harmonyMethod);
			Traverse masterTrv = Traverse.Create(master);
			Traverse detailTrv = Traverse.Create(detail);
			HarmonyMethod.HarmonyFields().ForEach(delegate(string f)
			{
				object value = masterTrv.Field(f).GetValue();
				object value2 = detailTrv.Field(f).GetValue();
				SetValue(resultTrv, f, value2 ?? value);
			});
			return harmonyMethod;
		}

		private static HarmonyMethod GetHarmonyMethodInfo(object attribute)
		{
			FieldInfo field = attribute.GetType().GetField("info", AccessTools.all);
			if ((object)field == null)
			{
				return null;
			}
			if (field.FieldType.Name != "HarmonyMethod")
			{
				return null;
			}
			return AccessTools.MakeDeepCopy<HarmonyMethod>(field.GetValue(attribute));
		}

		public static List<HarmonyMethod> GetFromType(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from attr in type.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}

		public static HarmonyMethod GetMergedFromType(Type type)
		{
			return HarmonyMethod.Merge(GetFromType(type));
		}

		public static HarmonyMethod GetMergedFromMethod(MethodBase method)
		{
			return HarmonyMethod.Merge(GetFromMethod(method));
		}

		public static List<HarmonyMethod> GetFromMethod(MethodBase method)
		{
			return (from attr in method.GetCustomAttributes(inherit: true)
				select GetHarmonyMethodInfo(attr) into info
				where info != null
				select info).ToList();
		}
	}
	[Obsolete("Exists for legacy support", true)]
	internal static class HarmonySharedState
	{
		[Obsolete("Exists for legacy support", true)]
		public static PatchInfo GetPatchInfo(MethodBase method)
		{
			return method.ToPatchInfo();
		}

		[Obsolete("Exists for legacy support", true)]
		public static IEnumerable<MethodBase> GetPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		[Obsolete("Exists for legacy support", true)]
		public static void UpdatePatchInfo(MethodBase methodBase, PatchInfo patchInfo)
		{
		}
	}
	[Obsolete("Exists for legacy support", true)]
	internal static class PatchFunctions
	{
		[Obsolete("Exists for legacy support", true)]
		public static DynamicMethod UpdateWrapper(MethodBase original, PatchInfo info, string id)
		{
			original.GetMethodPatcher().Apply();
			return null;
		}
	}
	public class PatchInfo
	{
		public Patch[] prefixes;

		public Patch[] postfixes;

		public Patch[] transpilers;

		public Patch[] finalizers;

		public PatchInfo()
		{
			prefixes = new Patch[0];
			postfixes = new Patch[0];
			transpilers = new Patch[0];
			finalizers = new Patch[0];
		}

		private void AddPatch(ref Patch[] list, string owner, HarmonyMethod info)
		{
			if ((object)info?.method != null)
			{
				int priority = ((info.priority == -1) ? 400 : info.priority);
				string[] before = info.before ?? new string[0];
				string[] after = info.after ?? new string[0];
				AddPatch(ref list, info.method, owner, priority, before, after);
			}
		}

		private void AddPatch(ref Patch[] list, MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			List<Patch> list2 = list.ToList();
			list2.Add(new Patch(patch, prefixes.Count() + 1, owner, priority, before, after));
			list = list2.ToArray();
		}

		private void RemovePatch(ref Patch[] list, string owner)
		{
			if (owner == "*")
			{
				list = new Patch[0];
				return;
			}
			list = list.Where((Patch patch) => patch.owner != owner).ToArray();
		}

		public void AddPrefix(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref prefixes, patch, owner, priority, before, after);
		}

		public void AddPrefix(string owner, HarmonyMethod info)
		{
			AddPatch(ref prefixes, owner, info);
		}

		public void RemovePrefix(string owner)
		{
			RemovePatch(ref prefixes, owner);
		}

		public void AddPostfix(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref postfixes, patch, owner, priority, before, after);
		}

		public void AddPostfix(string owner, HarmonyMethod info)
		{
			AddPatch(ref postfixes, owner, info);
		}

		public void RemovePostfix(string owner)
		{
			RemovePatch(ref postfixes, owner);
		}

		public void AddTranspiler(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref transpilers, patch, owner, priority, before, after);
		}

		public void AddTranspiler(string owner, HarmonyMethod info)
		{
			AddPatch(ref transpilers, owner, info);
		}

		public void RemoveTranspiler(string owner)
		{
			RemovePatch(ref transpilers, owner);
		}

		public void AddFinalizer(MethodInfo patch, string owner, int priority, string[] before, string[] after)
		{
			AddPatch(ref finalizers, patch, owner, priority, before, after);
		}

		public void AddFinalizer(string owner, HarmonyMethod info)
		{
			AddPatch(ref finalizers, owner, info);
		}

		public void RemoveFinalizer(string owner)
		{
			RemovePatch(ref finalizers, owner);
		}

		public void RemovePatch(MethodInfo patch)
		{
			lock (this)
			{
				prefixes = prefixes.Where((Patch p) => (object)p.patch != patch).ToArray();
				postfixes = postfixes.Where((Patch p) => (object)p.patch != patch).ToArray();
				transpilers = transpilers.Where((Patch p) => (object)p.patch != patch).ToArray();
				finalizers = finalizers.Where((Patch p) => (object)p.patch != patch).ToArray();
			}
		}
	}
	public class Patch : IComparable
	{
		public readonly int index;

		public readonly string owner;

		public readonly int priority;

		public readonly string[] before;

		public readonly string[] after;

		public MethodInfo patch;

		public MethodInfo PatchMethod
		{
			get
			{
				return patch;
			}
			set
			{
				patch = value;
			}
		}

		public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after)
		{
			if (patch is DynamicMethod)
			{
				throw new ArgumentException("Cannot directly reference dynamic method \"" + Extensions.GetID((MethodBase)patch, (string)null, (string)null, true, false, false) + "\" in Harmony. Use a factory method instead that will return the dynamic method.", "patch");
			}
			this.index = index;
			this.owner = owner;
			this.priority = priority;
			this.before = before;
			this.after = after;
			this.patch = patch;
		}

		public MethodInfo GetMethod(MethodBase original)
		{
			if ((object)patch.ReturnType != typeof(DynamicMethod) && (object)patch.ReturnType != typeof(MethodInfo))
			{
				return patch;
			}
			if (!patch.IsStatic)
			{
				return patch;
			}
			ParameterInfo[] parameters = patch.GetParameters();
			if (parameters.Count() != 1)
			{
				return patch;
			}
			if ((object)parameters[0].ParameterType != typeof(MethodBase))
			{
				return patch;
			}
			return patch.Invoke(null, new object[1] { original }) as MethodInfo;
		}

		public override bool Equals(object obj)
		{
			if (obj is Patch patch)
			{
				return (object)this.patch == patch.patch;
			}
			return false;
		}

		public int CompareTo(object obj)
		{
			if (!(obj is Patch patch))
			{
				return 0;
			}
			int num;
			if (patch.priority != priority)
			{
				num = priority;
				return -num.CompareTo(patch.priority);
			}
			num = index;
			return num.CompareTo(patch.index);
		}

		public override int GetHashCode()
		{
			return patch.GetHashCode();
		}
	}
	public class Patches
	{
		public readonly ReadOnlyCollection<Patch> Prefixes;

		public readonly ReadOnlyCollection<Patch> Postfixes;

		public readonly ReadOnlyCollection<Patch> Transpilers;

		public readonly ReadOnlyCollection<Patch> Finalizers;

		public ReadOnlyCollection<string> Owners
		{
			get
			{
				HashSet<string> hashSet = new HashSet<string>();
				hashSet.UnionWith(Prefixes.Select((Patch p) => p.owner));
				hashSet.UnionWith(Postfixes.Select((Patch p) => p.owner));
				hashSet.UnionWith(Transpilers.Select((Patch p) => p.owner));
				hashSet.UnionWith(Finalizers.Select((Patch p) => p.owner));
				return hashSet.ToList().AsReadOnly();
			}
		}

		public Patches(Patch[] prefixes, Patch[] postfixes, Patch[] transpilers, Patch[] finalizers)
		{
			if (prefixes == null)
			{
				prefixes = new Patch[0];
			}
			if (postfixes == null)
			{
				postfixes = new Patch[0];
			}
			if (transpilers == null)
			{
				transpilers = new Patch[0];
			}
			if (finalizers == null)
			{
				finalizers = new Patch[0];
			}
			Prefixes = prefixes.ToList().AsReadOnly();
			Postfixes = postfixes.ToList().AsReadOnly();
			Transpilers = transpilers.ToList().AsReadOnly();
			Finalizers = finalizers.ToList().AsReadOnly();
		}
	}
	public class PatchProcessor
	{
		private readonly Harmony instance;

		private readonly Type container;

		private readonly HarmonyMethod containerAttributes;

		private readonly List<MethodBase> originals = new List<MethodBase>();

		private HarmonyMethod prefix;

		private HarmonyMethod postfix;

		private HarmonyMethod transpiler;

		private HarmonyMethod finalizer;

		public PatchProcessor(Harmony instance, MethodBase original = null)
		{
			this.instance = instance;
			if ((object)original != null)
			{
				originals.Add(original);
			}
		}

		public PatchProcessor(Harmony instance, Type type, HarmonyMethod attributes)
		{
			this.instance = instance;
			container = type;
			containerAttributes = attributes ?? new HarmonyMethod();
			prefix = containerAttributes.Clone();
			postfix = containerAttributes.Clone();
			transpiler = containerAttributes.Clone();
			finalizer = containerAttributes.Clone();
			PrepareType();
		}

		[Obsolete("Use other constructors and Add* methods")]
		public PatchProcessor(Harmony instance, List<MethodBase> originals, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null)
		{
			this.instance = instance;
			this.originals = originals;
			this.prefix = prefix;
			this.postfix = postfix;
			this.transpiler = transpiler;
			this.finalizer = finalizer;
		}

		public PatchProcessor AddOriginal(MethodBase original)
		{
			if (!originals.Contains(original))
			{
				originals.Add(original);
			}
			return this;
		}

		public PatchProcessor SetOriginals(List<MethodBase> originals)
		{
			this.originals.Clear();
			this.originals.AddRange(originals);
			return this;
		}

		public PatchProcessor AddPrefix(HarmonyMethod prefix)
		{
			this.prefix = prefix;
			return this;
		}

		public PatchProcessor AddPrefix(MethodInfo fixMethod)
		{
			prefix = new HarmonyMethod(fixMethod);
			return this;
		}

		public PatchProcessor AddPostfix(HarmonyMethod postfix)
		{
			this.postfix = postfix;
			return this;
		}

		public PatchProcessor AddPostfix(MethodInfo fixMethod)
		{
			postfix = new HarmonyMethod(fixMethod);
			return this;
		}

		public PatchProcessor AddTranspiler(HarmonyMethod transpiler)
		{
			this.transpiler = transpiler;
			return this;
		}

		public PatchProcessor AddTranspiler(MethodInfo fixMethod)
		{
			transpiler = new HarmonyMethod(fixMethod);
			return this;
		}

		public PatchProcessor AddFinalizer(HarmonyMethod finalizer)
		{
			this.finalizer = finalizer;
			return this;
		}

		public PatchProcessor AddFinalizer(MethodInfo fixMethod)
		{
			finalizer = new HarmonyMethod(fixMethod);
			return this;
		}

		public static Patches GetPatchInfo(MethodBase method)
		{
			PatchInfo patchInfo = method.GetPatchInfo();
			if (patchInfo == null)
			{
				return null;
			}
			lock (patchInfo)
			{
				return new Patches(patchInfo.prefixes, patchInfo.postfixes, patchInfo.transpilers, patchInfo.finalizers);
			}
		}

		public static Dictionary<string, Version> VersionInfo(out Version currentVersion)
		{
			currentVersion = typeof(Harmony).Assembly.GetName().Version;
			Dictionary<string, Assembly> assemblies = new Dictionary<string, Assembly>();
			foreach (MethodBase allPatchedMethod in GetAllPatchedMethods())
			{
				Patches patchInfo = GetPatchInfo(allPatchedMethod);
				AddAssemblies(patchInfo.Prefixes);
				AddAssemblies(patchInfo.Postfixes);
				AddAssemblies(patchInfo.Transpilers);
				AddAssemblies(patchInfo.Finalizers);
			}
			Dictionary<string, Version> dictionary = new Dictionary<string, Version>();
			foreach (KeyValuePair<string, Assembly> item in assemblies)
			{
				AssemblyName assemblyName = item.Value.GetReferencedAssemblies().FirstOrDefault((AssemblyName a) => a.FullName.StartsWith("0Harmony, Version", StringComparison.Ordinal));
				if (assemblyName != null)
				{
					dictionary[item.Key] = assemblyName.Version;
				}
			}
			return dictionary;
			void AddAssemblies(IEnumerable<Patch> patches)
			{
				foreach (Patch patch in patches)
				{
					assemblies[patch.owner] = patch.patch.DeclaringType?.Assembly;
				}
			}
		}

		public static List<CodeInstruction> GetOriginalInstructions(MethodBase original, ILGenerator generator = null)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			DynamicMethodDefinition val = new DynamicMethodDefinition(original);
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body);
			ILGenerator il = generator ?? ((ILGeneratorShim)new CecilILGenerator(val.GetILProcessor())).GetProxy();
			return iLManipulator.GetInstructions(il);
		}

		public static List<CodeInstruction> GetOriginalInstructions(MethodBase original, out ILGenerator generator)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			DynamicMethodDefinition val = new DynamicMethodDefinition(original);
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body);
			generator = ((ILGeneratorShim)new CecilILGenerator(val.GetILProcessor())).GetProxy();
			return iLManipulator.GetInstructions(generator);
		}

		[Obsolete("Use GetAllPatchedMethods instead")]
		public static IEnumerable<MethodBase> AllPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		public static IEnumerable<MethodBase> GetAllPatchedMethods()
		{
			return GlobalPatchState.GetPatchedMethods();
		}

		public List<DynamicMethod> Patch()
		{
			Stopwatch sw = null;
			Logger.Log(Logger.LogChannel.Info, delegate
			{
				sw = Stopwatch.StartNew();
				return "Patching " + instance.Id + "...";
			});
			List<DynamicMethod> result = new List<DynamicMethod>();
			foreach (MethodBase original in originals)
			{
				if ((object)original == null)
				{
					throw new NullReferenceException("Null method for " + instance.Id);
				}
				Logger.Log(Logger.LogChannel.Info, () => "Patching " + Extensions.GetID(original, (string)null, (string)null, true, false, false));
				bool individualPrepareResult = RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, new object[1] { original });
				Logger.Log(Logger.LogChannel.Info, () => $"HarmonyPrepare result: {individualPrepareResult}");
				if (individualPrepareResult)
				{
					PatchInfo patchInfo = original.ToPatchInfo();
					lock (patchInfo)
					{
						patchInfo.AddPrefix(instance.Id, prefix);
						patchInfo.AddPostfix(instance.Id, postfix);
						patchInfo.AddTranspiler(instance.Id, transpiler);
						patchInfo.AddFinalizer(instance.Id, finalizer);
					}
					original.GetMethodPatcher().Apply();
					RunMethod<HarmonyCleanup>(new object[1] { original });
				}
			}
			Logger.Log(Logger.LogChannel.Info, () => $"Patching {instance.Id} took {sw.ElapsedMilliseconds}ms");
			return result;
		}

		public PatchProcessor Unpatch(HarmonyPatchType type, string harmonyID)
		{
			foreach (MethodBase original in originals)
			{
				PatchInfo patchInfo = original.ToPatchInfo();
				lock (patchInfo)
				{
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Prefix)
					{
						patchInfo.RemovePrefix(harmonyID);
					}
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Postfix)
					{
						patchInfo.RemovePostfix(harmonyID);
					}
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Transpiler)
					{
						patchInfo.RemoveTranspiler(harmonyID);
					}
					if (type == HarmonyPatchType.All || type == HarmonyPatchType.Finalizer)
					{
						patchInfo.RemoveFinalizer(harmonyID);
					}
				}
				original.GetMethodPatcher().Apply();
			}
			return this;
		}

		public PatchProcessor Unpatch(MethodInfo patch)
		{
			foreach (MethodBase original in originals)
			{
				original.ToPatchInfo().RemovePatch(patch);
				original.GetMethodPatcher().Apply();
			}
			return this;
		}

		private void PrepareType()
		{
			if (!RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, new object[0]))
			{
				return;
			}
			MethodType? methodType = containerAttributes.methodType;
			if (!containerAttributes.methodType.HasValue)
			{
				containerAttributes.methodType = MethodType.Normal;
			}
			string reversePatchAttr = typeof(HarmonyReversePatch).FullName;
			foreach (MethodInfo item in (from m in container.GetMethods(AccessTools.all)
				where m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == reversePatchAttr)
				select m).ToList())
			{
				MethodBase originalMethod = GetOriginalMethod(containerAttributes.Merge(new HarmonyMethod(item)));
				instance.CreateReversePatcher(originalMethod, item).Patch();
			}
			IEnumerable<MethodBase> enumerable = RunMethod<HarmonyTargetMethods, IEnumerable<MethodBase>>(null, new object[0]);
			if (enumerable != null)
			{
				originals.Clear();
				originals.AddRange(enumerable);
			}
			else if (container.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == typeof(HarmonyPatchAll).FullName))
			{
				Type declaringType = containerAttributes.declaringType;
				originals.AddRange(AccessTools.GetDeclaredConstructors(declaringType).Cast<MethodBase>());
				originals.AddRange(AccessTools.GetDeclaredMethods(declaringType).Cast<MethodBase>());
				List<PropertyInfo> declaredProperties = AccessTools.GetDeclaredProperties(declaringType);
				originals.AddRange((from prop in declaredProperties
					select prop.GetGetMethod(nonPublic: true) into method
					where (object)method != null
					select method).Cast<MethodBase>());
				originals.AddRange((from prop in declaredProperties
					select prop.GetSetMethod(nonPublic: true) into method
					where (object)method != null
					select method).Cast<MethodBase>());
			}
			else
			{
				MethodBase methodBase = RunMethod<HarmonyTargetMethod, MethodBase>(null, new object[0]) ?? GetOriginalMethod(containerAttributes);
				if ((object)methodBase == null)
				{
					string text = "(";
					text += $"declaringType={containerAttributes.declaringType}, ";
					text = text + "methodName =" + containerAttributes.methodName + ", ";
					text += $"methodType={methodType}, ";
					text = text + "argumentTypes=" + containerAttributes.argumentTypes.Description();
					text += ")";
					throw new ArgumentException("No target method specified for class " + container.FullName + " " + text);
				}
				originals.Add(methodBase);
			}
			GetPatches(container, out var methodInfo, out var methodInfo2, out var methodInfo3, out var methodInfo4);
			if (prefix != null)
			{
				prefix.method = methodInfo;
			}
			if (postfix != null)
			{
				postfix.method = methodInfo2;
			}
			if (transpiler != null)
			{
				transpiler.method = methodInfo3;
			}
			if (finalizer != null)
			{
				finalizer.method = methodInfo4;
			}
			if ((object)methodInfo != null)
			{
				if (!methodInfo.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(methodInfo);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod)).CopyTo(prefix);
			}
			if ((object)methodInfo2 != null)
			{
				if (!methodInfo2.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo2, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod2 = HarmonyMethodExtensions.GetFromMethod(methodInfo2);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod2)).CopyTo(postfix);
			}
			if ((object)methodInfo3 != null)
			{
				if (!methodInfo3.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo3, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod3 = HarmonyMethodExtensions.GetFromMethod(methodInfo3);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod3)).CopyTo(transpiler);
			}
			if ((object)methodInfo4 != null)
			{
				if (!methodInfo4.IsStatic)
				{
					throw new ArgumentException("Patch method " + Extensions.GetID((MethodBase)methodInfo4, (string)null, (string)null, true, false, false) + " must be static");
				}
				List<HarmonyMethod> fromMethod4 = HarmonyMethodExtensions.GetFromMethod(methodInfo4);
				containerAttributes.Merge(HarmonyMethod.Merge(fromMethod4)).CopyTo(finalizer);
			}
		}

		internal static MethodBase GetOriginalMethod(HarmonyMethod attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			if ((object)attribute.declaringType == null)
			{
				return MakeFailure("declaringType cannot be null");
			}
			switch (attribute.methodType)
			{
			case MethodType.Normal:
			{
				if (string.IsNullOrEmpty(attribute.methodName))
				{
					return MakeFailure("methodName can't be empty");
				}
				if (attribute.methodName == ".ctor")
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.Constructor should be used instead of setting methodName to .ctor");
					goto case MethodType.Constructor;
				}
				if (attribute.methodName == ".cctor")
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.StaticConstructor should be used instead of setting methodName to .cctor");
					goto case MethodType.StaticConstructor;
				}
				if (attribute.methodName.StartsWith("get_") || attribute.methodName.StartsWith("set_"))
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.Getter and MethodType.Setter should be used instead adding get_ and set_ to property names");
				}
				MethodInfo methodInfo = AccessTools.DeclaredMethod(attribute.declaringType, attribute.methodName, attribute.argumentTypes);
				if ((object)methodInfo != null)
				{
					return methodInfo;
				}
				methodInfo = AccessTools.Method(attribute.declaringType, attribute.methodName, attribute.argumentTypes);
				if ((object)methodInfo != null)
				{
					string text = GetPatchName();
					object[] obj = new object[4] { attribute.methodName, null, null, null };
					Type[] argumentTypes = attribute.argumentTypes;
					obj[1] = ((argumentTypes != null) ? argumentTypes.Length : 0);
					obj[2] = attribute.declaringType.FullDescription();
					obj[3] = methodInfo.DeclaringType.FullDescription();
					Logger.LogText(Logger.LogChannel.Warn, text + string.Format(" - Could not find method {0} with {1} parameters in type {2}, but it was found in base class of this type {3}", obj));
					return methodInfo;
				}
				return MakeFailure("Could not find method " + attribute.methodName + " with " + attribute.argumentTypes.Description() + " parameters in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.Getter:
			{
				if (string.IsNullOrEmpty(attribute.methodName))
				{
					return MakeFailure("methodName can't be empty");
				}
				PropertyInfo propertyInfo2 = AccessTools.DeclaredProperty(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo2 != null)
				{
					MethodInfo getMethod = propertyInfo2.GetGetMethod(nonPublic: true);
					if ((object)getMethod == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Getter");
					}
					return getMethod;
				}
				propertyInfo2 = AccessTools.Property(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo2 != null)
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription() + ", but it was found in base class of this type: " + propertyInfo2.DeclaringType.FullDescription());
					MethodInfo getMethod2 = propertyInfo2.GetGetMethod(nonPublic: true);
					if ((object)getMethod2 == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Getter");
					}
					return getMethod2;
				}
				return MakeFailure("Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.Setter:
			{
				if (string.IsNullOrEmpty(attribute.methodName))
				{
					return MakeFailure("methodName can't be empty");
				}
				PropertyInfo propertyInfo = AccessTools.DeclaredProperty(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo != null)
				{
					MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
					if ((object)setMethod == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Setter");
					}
					return setMethod;
				}
				propertyInfo = AccessTools.Property(attribute.declaringType, attribute.methodName);
				if ((object)propertyInfo != null)
				{
					Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription() + ", but it was found in base class of this type: " + propertyInfo.DeclaringType.FullDescription());
					MethodInfo setMethod2 = propertyInfo.GetSetMethod(nonPublic: true);
					if ((object)setMethod2 == null)
					{
						return MakeFailure("Property " + attribute.methodName + " does not have a Setter");
					}
					return setMethod2;
				}
				return MakeFailure("Could not find property " + attribute.methodName + " in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.Constructor:
			{
				ConstructorInfo constructorInfo2 = AccessTools.DeclaredConstructor(attribute.declaringType, attribute.argumentTypes);
				if ((object)constructorInfo2 != null)
				{
					return constructorInfo2;
				}
				return MakeFailure("Could not find constructor with " + attribute.argumentTypes.Description() + " parameters in type " + attribute.declaringType.FullDescription());
			}
			case MethodType.StaticConstructor:
			{
				ConstructorInfo constructorInfo = AccessTools.GetDeclaredConstructors(attribute.declaringType).FirstOrDefault((ConstructorInfo c) => c.IsStatic);
				if ((object)constructorInfo != null)
				{
					return constructorInfo;
				}
				return MakeFailure("Could not find static constructor in type " + attribute.declaringType.FullDescription());
			}
			default:
				throw new ArgumentOutOfRangeException("methodType", attribute.methodType, "Unknown method type");
			}
			string GetPatchName()
			{
				return attribute.method?.FullDescription() ?? "Unknown patch";
			}
			MethodBase MakeFailure(string reason)
			{
				Logger.Log(Logger.LogChannel.Error, () => "Failed to process patch " + GetPatchName() + " - " + reason);
				return null;
			}
		}

		private T RunMethod<S, T>(T defaultIfNotExisting, params object[] parameters)
		{
			if ((object)container == null)
			{
				return defaultIfNotExisting;
			}
			string name = typeof(S).Name.Replace("Harmony", "");
			MethodInfo patchMethod = GetPatchMethod<S>(container, name);
			if ((object)patchMethod != null)
			{
				if (typeof(T).IsAssignableFrom(patchMethod.ReturnType))
				{
					object[] emptyTypes = Type.EmptyTypes;
					return (T)patchMethod.Invoke(null, emptyTypes);
				}
				object[] inputs = (parameters ?? new object[0]).Union(new object[1] { instance }).ToArray();
				object[] parameters2 = AccessTools.ActualParameters(patchMethod, inputs);
				patchMethod.Invoke(null, parameters2);
				return defaultIfNotExisting;
			}
			return defaultIfNotExisting;
		}

		private void RunMethod<S>(params object[] parameters)
		{
			if ((object)container != null)
			{
				string name = typeof(S).Name.Replace("Harmony", "");
				MethodInfo patchMethod = GetPatchMethod<S>(container, name);
				if ((object)patchMethod != null)
				{
					object[] inputs = (parameters ?? new object[0]).Union(new object[1] { instance }).ToArray();
					object[] parameters2 = AccessTools.ActualParameters(patchMethod, inputs);
					patchMethod.Invoke(null, parameters2);
				}
			}
		}

		private MethodInfo GetPatchMethod<T>(Type patchType, string name)
		{
			string attributeType = typeof(T).FullName;
			MethodInfo methodInfo = patchType.GetMethods(AccessTools.all).FirstOrDefault((MethodInfo m) => m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == attributeType));
			if ((object)methodInfo == null)
			{
				methodInfo = patchType.GetMethod(name, AccessTools.all);
			}
			return methodInfo;
		}

		private void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler, out MethodInfo finalizer)
		{
			prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix");
			postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix");
			transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler");
			finalizer = GetPatchMethod<HarmonyFinalizer>(patchType, "Finalizer");
		}
	}
	public class ReversePatcher
	{
		private readonly Harmony instance;

		private readonly MethodBase original;

		private readonly MethodInfo standin;

		private readonly ILHook ilHook;

		public ReversePatcher(Harmony instance, MethodBase original, MethodInfo standin)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			this.instance = instance;
			this.original = original;
			this.standin = standin;
			ilHook = new ILHook((MethodBase)standin, new Manipulator(ApplyReversePatch), new ILHookConfig
			{
				ManualApply = true
			});
		}

		private void ApplyReversePatch(ILContext ctx)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			DynamicMethodDefinition val = new DynamicMethodDefinition(original);
			ILManipulator iLManipulator = new ILManipulator(val.Definition.Body);
			ctx.Body.Variables.Clear();
			Enumerator<VariableDefinition> enumerator = val.Definition.Body.Variables.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					VariableDefinition current = enumerator.Current;
					ctx.Body.Variables.Add(new VariableDefinition(ctx.Module.ImportReference(((VariableReference)current).VariableType)));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodInfo transpiler = GetTranspiler(standin);
			if ((object)transpiler != null)
			{
				iLManipulator.AddTranspiler(transpiler);
			}
			iLManipulator.WriteTo(ctx.Body, standin);
			ctx.IL.Emit(OpCodes.Ret);
		}

		public void Patch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
		{
			if ((object)original == null)
			{
				throw new NullReferenceException("Null method for " + instance.Id);
			}
			ilHook.Apply();
		}

		private MethodInfo GetTranspiler(MethodInfo method)
		{
			string methodName = method.Name;
			List<MethodInfo> declaredMethods = AccessTools.GetDeclaredMethods(method.DeclaringType);
			Type ici = typeof(IEnumerable<CodeInstruction>);
			return declaredMethods.FirstOrDefault((MethodInfo m) => (object)m.ReturnType == ici && m.Name.StartsWith("<" + methodName + ">"));
		}
	}
	public class CodeMatch
	{
		public string name;

		public List<OpCode> opcodes = new List<OpCode>();

		public List<object> operands = new List<object>();

		public List<Label> labels = new List<Label>();

		public List<ExceptionBlock> blocks = new List<ExceptionBlock>();

		public List<int> jumpsFrom = new List<int>();

		public List<int> jumpsTo = new List<int>();

		public Func<CodeInstruction, bool> predicate;

		public CodeMatch(OpCode? opcode = null, object operand = null, string name = null)
		{
			if (opcode.HasValue)
			{
				OpCode valueOrDefault = opcode.GetValueOrDefault();
				opcodes.Add(valueOrDefault);
			}
			if (operand != null)
			{
				operands.Add(operand);
			}
			this.name = name;
		}

		public CodeMatch(CodeInstruction instruction, string name = null)
			: this(instruction.opcode, instruction.operand, name)
		{
		}

		public CodeMatch(Func<CodeInstruction, bool> predicate, string name = null)
		{
			this.predicate = predicate;
			this.name = name;
		}

		internal bool Matches(List<CodeInstruction> codes, CodeInstruction instruction)
		{
			if (predicate != null)
			{
				return predicate(instruction);
			}
			if (opcodes.Count > 0 && !opcodes.Contains(instruction.opcode))
			{
				return false;
			}
			if (operands.Count > 0 && !operands.Contains(instruction.operand))
			{
				return false;
			}
			if (labels.Count > 0 && !labels.Intersect(instruction.labels).Any())
			{
				return false;
			}
			if (blocks.Count > 0 && !blocks.Intersect(instruction.blocks).Any())
			{
				return false;
			}
			if (jumpsFrom.Count > 0 && !jumpsFrom.Select((int index) => codes[index].operand).OfType<Label>().Intersect(instruction.labels)
				.Any())
			{
				return false;
			}
			if (jumpsTo.Count > 0)
			{
				object operand = instruction.operand;
				if (operand == null || (object)operand.GetType() != typeof(Label))
				{
					return false;
				}
				Label label = (Label)operand;
				IEnumerable<int> second = from idx in Enumerable.Range(0, codes.Count)
					where codes[idx].labels.Contains(label)
					select idx;
				if (!jumpsTo.Intersect(second).Any())
				{
					return false;
				}
			}
			return true;
		}

		public override string ToString()
		{
			string text = "[";
			if (name != null)
			{
				text = text + name + ": ";
			}
			if (opcodes.Count > 0)
			{
				text = text + "opcodes=" + opcodes.Join() + " ";
			}
			if (operands.Count > 0)
			{
				text = text + "operands=" + operands.Join() + " ";
			}
			if (labels.Count > 0)
			{
				text = text + "labels=" + labels.Join() + " ";
			}
			if (blocks.Count > 0)
			{
				text = text + "blocks=" + blocks.Join() + " ";
			}
			if (jumpsFrom.Count > 0)
			{
				text = text + "jumpsFrom=" + jumpsFrom.Join() + " ";
			}
			if (jumpsTo.Count > 0)
			{
				text = text + "jumpsTo=" + jumpsTo.Join() + " ";
			}
			if (predicate != null)
			{
				text += "predicate=yes ";
			}
			return text.TrimEnd(new char[0]) + "]";
		}
	}
	public class CodeMatcher
	{
		private readonly ILGenerator generator;

		private readonly List<CodeInstruction> codes = new List<CodeInstruction>();

		private Dictionary<string, CodeInstruction> lastMatches = new Dictionary<string, CodeInstruction>();

		private string lastError;

		private bool lastUseEnd;

		private CodeMatch[] lastCodeMatches;

		public int Pos { get; private set; } = -1;


		public int Length => codes.Count;

		public bool IsValid
		{
			get
			{
				if (Pos >= 0)
				{
					return Pos < Length;
				}
				return false;
			}
		}

		public bool IsInvalid
		{
			get
			{
				if (Pos >= 0)
				{
					return Pos >= Length;
				}
				return true;
			}
		}

		public int Remaining => Length - Math.Max(0, Pos);

		public ref OpCode Opcode => ref codes[Pos].opcode;

		public ref object Operand => ref codes[Pos].operand;

		public ref List<Label> Labels => ref codes[Pos].labels;

		public ref List<ExceptionBlock> Blocks => ref codes[Pos].blocks;

		public CodeInstruction Instruction => codes[Pos];

		private void FixStart()
		{
			Pos = Math.Max(0, Pos);
		}

		private void SetOutOfBounds(int direction)
		{
			Pos = ((direction > 0) ? Length : (-1));
		}

		public CodeMatcher()
		{
		}

		public CodeMatcher(IEnumerable<CodeInstruction> instructions, ILGenerator generator = null)
		{
			this.generator = generator;
			codes = instructions.Select((CodeInstruction c) => new CodeInstruction(c)).ToList();
		}

		public CodeMatcher Clone()
		{
			return new CodeMatcher(codes, generator)
			{
				Pos = Pos,
				lastMatches = lastMatches,
				lastError = lastError,
				lastUseEnd = lastUseEnd,
				lastCodeMatches = lastCodeMatches
			};
		}

		public CodeInstruction InstructionAt(int offset)
		{
			return codes[Pos + offset];
		}

		public List<CodeInstruction> Instructions()
		{
			return codes;
		}

		public IEnumerable<CodeInstruction> InstructionEnumeration()
		{
			return codes.AsEnumerable();
		}

		public List<CodeInstruction> Instructions(int count)
		{
			return (from c in codes.GetRange(Pos, count)
				select new CodeInstruction(c)).ToList();
		}

		public List<CodeInstruction> InstructionsInRange(int start, int end)
		{
			List<CodeInstruction> list = codes;
			if (start > end)
			{
				int num = start;
				start = end;
				end = num;
			}
			return (from c in list.GetRange(start, end - start + 1)
				select new CodeInstruction(c)).ToList();
		}

		public List<CodeInstruction> InstructionsWithOffsets(int startOffset, int endOffset)
		{
			return InstructionsInRange(Pos + startOffset, Pos + endOffset);
		}

		public List<Label> DistinctLabels(IEnumerable<CodeInstruction> instructions)
		{
			return instructions.SelectMany((CodeInstruction instruction) => instruction.labels).Distinct().ToList();
		}

		public bool ReportFailure(MethodBase method, Action<string> logger)
		{
			if (IsValid)
			{
				return false;
			}
			string arg = lastError ?? "Unexpected code";
			logger($"{arg} in {method}");
			return true;
		}

		public CodeMatcher SetInstruction(CodeInstruction instruction)
		{
			codes[Pos] = instruction;
			return this;
		}

		public CodeMatcher SetInstructionAndAdvance(CodeInstruction instruction)
		{
			SetInstruction(instruction);
			Pos++;
			return this;
		}

		public CodeMatcher Set(OpCode opcode, object operand)
		{
			Opcode = opcode;
			Operand = operand;
			return this;
		}

		public CodeMatcher SetAndAdvance(OpCode opcode, object operand)
		{
			Set(opcode, operand);
			Pos++;
			return this;
		}

		public CodeMatcher SetOpcodeAndAdvance(OpCode opcode)
		{
			Opcode = opcode;
			Pos++;
			return this;
		}

		public CodeMatcher SetOperandAndAdvance(object operand)
		{
			Operand = operand;
			Pos++;
			return this;
		}

		public CodeMatcher CreateLabel(out Label label)
		{
			label = generator.DefineLabel();
			Labels.Add(label);
			return this;
		}

		public CodeMatcher CreateLabelAt(int position, out Label label)
		{
			label = generator.DefineLabel();
			AddLabelsAt(position, new Label[1] { label });
			return this;
		}

		public CodeMatcher AddLabels(IEnumerable<Label> labels)
		{
			Labels.AddRange(labels);
			return this;
		}

		public CodeMatcher AddLabelsAt(int position, IEnumerable<Label> labels)
		{
			codes[position].labels.AddRange(labels);
			return this;
		}

		public CodeMatcher SetJumpTo(OpCode opcode, int destination, out Label label)
		{
			CreateLabelAt(destination, out label);
			Set(opcode, label);
			return this;
		}

		public CodeMatcher Insert(params CodeInstruction[] instructions)
		{
			codes.InsertRange(Pos, instructions);
			return this;
		}

		public CodeMatcher Insert(IEnumerable<CodeInstruction> instructions)
		{
			codes.InsertRange(Pos, instructions);
			return this;
		}

		public CodeMatcher InsertBranch(OpCode opcode, int destination)
		{
			CreateLabelAt(destination, out var label);
			codes.Insert(Pos, new CodeInstruction(opcode, label));
			return this;
		}

		public CodeMatcher InsertAndAdvance(params CodeInstruction[] instructions)
		{
			foreach (CodeInstruction codeInstruction in instructions)
			{
				Insert(codeInstruction);
				Pos++;
			}
			return this;
		}

		public CodeMatcher InsertAndAdvance(IEnumerable<CodeInstruction> instructions)
		{
			foreach (CodeInstruction instruction in instructions)
			{
				InsertAndAdvance(instruction);
			}
			return this;
		}

		public CodeMatcher InsertBranchAndAdvance(OpCode opcode, int destination)
		{
			InsertBranch(opcode, destination);
			Pos++;
			return this;
		}

		public CodeMatcher RemoveInstruction()
		{
			codes.RemoveAt(Pos);
			return this;
		}

		public CodeMatcher RemoveInstructions(int count)
		{
			codes.RemoveRange(Pos, count);
			return this;
		}

		public CodeMatcher RemoveInstructionsInRange(int start, int end)
		{
			if (start > end)
			{
				int num = start;
				start = end;
				end = num;
			}
			codes.RemoveRange(start, end - start + 1);
			return this;
		}

		public CodeMatcher RemoveInstructionsWithOffsets(int startOffset, int endOffset)
		{
			RemoveInstructionsInRange(Pos + startOffset, Pos + endOffset);
			return this;
		}

		public CodeMatcher Advance(int offset)
		{
			Pos += offset;
			if (!IsValid)
			{
				SetOutOfBounds(offset);
			}
			return this;
		}

		public CodeMatcher Start()
		{
			Pos = 0;
			return this;
		}

		public CodeMatcher End()
		{
			Pos = Length - 1;
			return this;
		}

		public CodeMatcher SearchForward(Func<CodeInstruction, bool> predicate)
		{
			return Search(predicate, 1);
		}

		public CodeMatcher SearchBack(Func<CodeInstruction, bool> predicate)
		{
			return Search(predicate, -1);
		}

		private CodeMatcher Search(Func<CodeInstruction, bool> predicate, int direction)
		{
			FixStart();
			while (IsValid && !predicate(Instruction))
			{
				Pos += direction;
			}
			lastError = (IsInvalid ? $"Cannot find {predicate}" : null);
			return this;
		}

		public CodeMatcher MatchForward(bool useEnd, params CodeMatch[] matches)
		{
			return Match(matches, 1, useEnd);
		}

		public CodeMatcher MatchBack(bool useEnd, params CodeMatch[] matches)
		{
			return Match(matches, -1, useEnd);
		}

		private CodeMatcher Match(CodeMatch[] matches, int direction, bool useEnd)
		{
			FixStart();
			while (IsValid)
			{
				lastUseEnd = useEnd;
				lastCodeMatches = matches;
				if (MatchSequence(Pos, matches))
				{
					if (useEnd)
					{
						Pos += matches.Count() - 1;
					}
					break;
				}
				Pos += direction;
			}
			lastError = (IsInvalid ? ("Cannot find " + matches.Join()) : null);
			return this;
		}

		public CodeMatcher Repeat(Action<CodeMatcher> matchAction, Action<string> notFoundAction = null)
		{
			int num = 0;
			if (lastCodeMatches == null)
			{
				throw new InvalidOperationException("No previous Match operation - cannot repeat");
			}
			while (IsValid)
			{
				matchAction(this);
				MatchForward(lastUseEnd, lastCodeMatches);
				num++;
			}
			lastCodeMatches = null;
			if (num == 0)
			{
				notFoundAction?.Invoke(lastError);
			}
			return this;
		}

		public CodeInstruction NamedMatch(string name)
		{
			return lastMatches[name];
		}

		private bool MatchSequence(int start, CodeMatch[] matches)
		{
			if (start < 0)
			{
				return false;
			}
			lastMatches = new Dictionary<string, CodeInstruction>();
			foreach (CodeMatch codeMatch in matches)
			{
				if (start >= Length || !codeMatch.Matches(codes, codes[start]))
				{
					return false;
				}
				if (codeMatch.name != null)
				{
					lastMatches.Add(codeMatch.name, codes[start]);
				}
				start++;
			}
			return true;
		}
	}
	public static class CodeInstructionExtensions
	{
		private static readonly HashSet<OpCode> LoadVarCodes = new HashSet<OpCode>
		{
			OpCodes.Ldloc_0,
			OpCodes.Ldloc_1,
			OpCodes.Ldloc_2,
			OpCodes.Ldloc_3,
			OpCodes.Ldloc,
			OpCodes.Ldloca,
			OpCodes.Ldloc_S,
			OpCodes.Ldloca_S
		};

		private static readonly HashSet<OpCode> StoreVarCodes = new HashSet<OpCode>
		{
			OpCodes.Stloc_0,
			OpCodes.Stloc_1,
			OpCodes.Stloc_2,
			OpCodes.Stloc_3,
			OpCodes.Stloc,
			OpCodes.Stloc_S
		};

		private static readonly HashSet<OpCode> BranchCodes = new HashSet<OpCode>
		{
			OpCodes.Br_S,
			OpCodes.Brfalse_S,
			OpCodes.Brtrue_S,
			OpCodes.Beq_S,
			OpCodes.Bge_S,
			OpCodes.Bgt_S,
			OpCodes.Ble_S,
			OpCodes.Blt_S,
			OpCodes.Bne_Un_S,
			OpCodes.Bge_Un_S,
			OpCodes.Bgt_Un_S,
			OpCodes.Ble_Un_S,
			OpCodes.Blt_Un_S,
			OpCodes.Br,
			OpCodes.Brfalse,
			OpCodes.Brtrue,
			OpCodes.Beq,
			OpCodes.Bge,
			OpCodes.Bgt,
			OpCodes.Ble,
			OpCodes.Blt,
			OpCodes.Bne_Un,
			OpCodes.Bge_Un,
			OpCodes.Bgt_Un,
			OpCodes.Ble_Un,
			OpCodes.Blt_Un
		};

		private static readonly HashSet<OpCode> ConstantLoadingCodes = new HashSet<OpCode>
		{
			OpCodes.Ldc_I4_M1,
			OpCodes.Ldc_I4_0,
			OpCodes.Ldc_I4_1,
			OpCodes.Ldc_I4_2,
			OpCodes.Ldc_I4_3,
			OpCodes.Ldc_I4_4,
			OpCodes.Ldc_I4_5,
			OpCodes.Ldc_I4_6,
			OpCodes.Ldc_I4_7,
			OpCodes.Ldc_I4_8,
			OpCodes.Ldc_I4,
			OpCodes.Ldc_I4_S,
			OpCodes.Ldc_I8,
			OpCodes.Ldc_R4,
			OpCodes.Ldc_R8
		};

		public static bool OperandIs(this CodeInstruction code, object value)
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			if (code.operand == null)
			{
				return false;
			}
			Type type = value.GetType();
			Type type2 = code.operand.GetType();
			if (AccessTools.IsInteger(type) && AccessTools.IsNumber(type2))
			{
				return Convert.ToInt64(code.operand) == Convert.ToInt64(value);
			}
			if (AccessTools.IsFloatingPoint(type) && AccessTools.IsNumber(type2))
			{
				return Convert.ToDouble(code.operand) == Convert.ToDouble(value);
			}
			return object.Equals(code.operand, value);
		}

		public static bool Is(this CodeInstruction code, OpCode opcode, object operand)
		{
			if (code.opcode == opcode)
			{
				return code.OperandIs(operand);
			}
			return false;
		}

		public static bool IsLdarg(this CodeInstruction code, int? n = null)
		{
			if ((!n.HasValue || n.Value == 0) && code.opcode == OpCodes.Ldarg_0)
			{
				return true;
			}
			if ((!n.HasValue || n.Value == 1) && code.opcode == OpCodes.Ldarg_1)
			{
				return true;
			}
			if ((!n.HasValue || n.Value == 2) && code.opcode == OpCodes.Ldarg_2)
			{
				return true;
			}
			if ((!n.HasValue || n.Value == 3) && code.opcode == OpCodes.Ldarg_3)
			{
				return true;
			}
			if (code.opcode == OpCodes.Ldarg && (!n.HasValue || n.Value == Convert.ToInt32(code.operand)))
			{
				return true;
			}
			if (code.opcode == OpCodes.Ldarg_S && (!n.HasValue || n.Value == Convert.ToInt32(code.operand)))
			{
				return true;
			}
			return false;
		}

		public static bool IsLdarga(this CodeInstruction code, int? n = null)
		{
			if (code.opcode != OpCodes.Ldarga && code.opcode != OpCodes.Ldarga_S)
			{
				return false;
			}
			if (n.HasValue)
			{
				return n.Value == Convert.ToInt32(code.operand);
			}
			return true;
		}

		public static bool IsStarg(this CodeInstruction code, int? n = null)
		{
			if (code.opcode != OpCodes.Starg && code.opcode != OpCodes.Starg_S)
			{
				return false;
			}
			if (n.HasValue)
			{
				return n.Value == Convert.ToInt32(code.operand);
			}
			return true;
		}

		public static bool IsLdloc(this CodeInstruction code, LocalBuilder variable = null)
		{
			if (!LoadVarCodes.Contains(code.opcode))
			{
				return false;
			}
			if (variable != null)
			{
				return object.Equals(variable, code.operand);
			}
			return true;
		}

		public static bool IsStloc(this CodeInstruction code, LocalBuilder variable = null)
		{
			if (!StoreVarCodes.Contains(code.opcode))
			{
				return false;
			}
			if (variable != null)
			{
				return object.Equals(variable, code.operand);
			}
			return true;
		}

		public static bool Branches(this CodeInstruction code, out Label? label)
		{
			if (BranchCodes.Contains(code.opcode))
			{
				label = (Label)code.operand;
				return true;
			}
			label = null;
			return false;
		}

		public static bool Calls(this CodeInstruction code, MethodInfo method)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			if (code.opcode != OpCodes.Call && code.opcode != OpCodes.Callvirt)
			{
				return false;
			}
			return object.Equals(code.operand, method);
		}

		public static bool LoadsConstant(this CodeInstruction code)
		{
			return ConstantLoadingCodes.Contains(code.opcode);
		}

		public static bool LoadsConstant(this CodeInstruction code, long number)
		{
			OpCode opcode = code.opcode;
			if (number == -1 && opcode == OpCodes.Ldc_I4_M1)
			{
				return true;
			}
			if (number == 0L && opcode == OpCodes.Ldc_I4_0)
			{
				return true;
			}
			if (number == 1 && opcode == OpCodes.Ldc_I4_1)
			{
				return true;
			}
			if (number == 2 && opcode == OpCodes.Ldc_I4_2)
			{
				return true;
			}
			if (number == 3 && opcode == OpCodes.Ldc_I4_3)
			{
				return true;
			}
			if (number == 4 && opcode == OpCodes.Ldc_I4_4)
			{
				return true;
			}
			if (number == 5 && opcode == OpCodes.Ldc_I4_5)
			{
				return true;
			}
			if (number == 6 && opcode == OpCodes.Ldc_I4_6)
			{
				return true;
			}
			if (number == 7 && opcode == OpCodes.Ldc_I4_7)
			{
				return true;
			}
			if (number == 8 && opcode == OpCodes.Ldc_I4_8)
			{
				return true;
			}
			if (opcode != OpCodes.Ldc_I4 && opcode != OpCodes.Ldc_I4_S && opcode != OpCodes.Ldc_I8)
			{
				return false;
			}
			return Convert.ToInt64(code.operand) == number;
		}

		public static bool LoadsConstant(this CodeInstruction code, double number)
		{
			if (code.opcode != OpCodes.Ldc_R4 && code.opcode != OpCodes.Ldc_R8)
			{
				return false;
			}
			return Convert.ToDouble(code.operand) == number;
		}

		public static bool LoadsConstant(this CodeInstruction code, Enum e)
		{
			return code.LoadsConstant(Convert.ToInt64(e));
		}

		public static bool LoadsField(this CodeInstruction code, FieldInfo field, bool byAddress = false)
		{
			if ((object)field == null)
			{
				throw new ArgumentNullException("field");
			}
			OpCode opCode = (field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld);
			if (!byAddress && code.opcode == opCode && object.Equals(code.operand, field))
			{
				return true;
			}
			OpCode opCode2 = (field.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda);
			if (byAddress && code.opcode == opCode2 && object.Equals(code.operand, field))
			{
				return true;
			}
			return false;
		}

		public static bool StoresField(this CodeInstruction code, FieldInfo field)
		{
			if ((object)field == null)
			{
				throw new ArgumentNullException("field");
			}
			OpCode opCode = (field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld);
			if (code.opcode == opCode)
			{
				return object.Equals(code.operand, field);
			}
			return false;
		}

		public static CodeInstruction WithLabels(this CodeInstruction code, params Label[] labels)
		{
			code.labels.AddRange(labels);
			return code;
		}

		public static CodeInstruction WithLabels(this CodeInstruction code, IEnumerable<Label> labels)
		{
			code.labels.AddRange(labels);
			return code;
		}

		public static List<Label> ExtractLabels(this CodeInstruction code)
		{
			List<Label> result = new List<Label>(code.labels);
			code.labels.Clear();
			return result;
		}

		public static CodeInstruction MoveLabelsTo(this CodeInstruction code, CodeInstruction other)
		{
			other.WithLabels(code.ExtractLabels());
			return code;
		}

		public static CodeInstruction MoveLabelsFrom(this CodeInstruction code, CodeInstruction other)
		{
			return code.WithLabels(other.ExtractLabels());
		}

		public static CodeInstruction WithBlocks(this CodeInstruction code, params ExceptionBlock[] blocks)
		{
			code.blocks.AddRange(blocks);
			return code;
		}

		public static CodeInstruction WithBlocks(this CodeInstruction code, IEnumerable<ExceptionBlock> blocks)
		{
			code.blocks.AddRange(blocks);
			return code;
		}

		public static List<ExceptionBlock> ExtractBlocks(this CodeInstruction code)
		{
			List<ExceptionBlock> result = new List<ExceptionBlock>(code.blocks);
			code.blocks.Clear();
			return result;
		}

		public static CodeInstruction MoveBlocksTo(this CodeInstruction code, CodeInstruction other)
		{
			other.WithBlocks(code.ExtractBlocks());
			return code;
		}

		public static CodeInstruction MoveBlocksFrom(this CodeInstruction code, CodeInstruction other)
		{
			return code.WithBlocks(other.ExtractBlocks());
		}
	}
	public static class CollectionExtensions
	{
		public static void Do<T>(this IEnumerable<T> sequence, Action<T> action)
		{
			if (sequence != null)
			{
				IEnumerator<T> enumerator = sequence.GetEnumerator();
				while (enumerator.MoveNext())
				{
					action(enumerator.Current);
				}
			}
		}

		public static void DoIf<T>(this IEnumerable<T> sequence, Func<T, bool> condition, Action<T> action)
		{
			sequence.Where(condition).Do(action);
		}

		public static IEnumerable<T> AddItem<T>(this IEnumerable<T> sequence, T item)
		{
			return (sequence ?? Enumerable.Empty<T>()).Concat(new T[1] { item });
		}

		public static T[] AddToArray<T>(this T[] sequence, T item)
		{
			return sequence.AddItem(item).ToArray();
		}

		public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)
		{
			return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray();
		}
	}
	public static class GeneralExtensions
	{
		public static string Join<T>(this IEnumerable<T> enumeration, Func<T, string> converter = null, string delimiter = ", ")
		{
			if (converter == null)
			{
				converter = (T t) => t.ToString();
			}
			return enumeration.Aggregate("", (string prev, T curr) => prev + ((prev != "") ? delimiter : "") + converter(curr));
		}

		public static string Description(this Type[] parameters)
		{
			if (parameters == null)
			{
				return "NULL";
			}
			return "(" + parameters.Join((Type p) => p.FullDescription()) + ")";
		}

		public static string FullDescription(this Type type)
		{
			if ((object)type == null)
			{
				return "null";
			}
			string text = type.Namespace;
			if (!string.IsNullOrEmpty(text))
			{
				text += ".";
			}
			string text2 = text + type.Name;
			if (type.IsGenericType)
			{
				text2 += "<";
				Type[] genericArguments = type.GetGenericArguments();
				for (int i = 0; i < genericArguments.Length; i++)
				{
					if (!text2.EndsWith("<", StringComparison.Ordinal))
					{
						text2 += ", ";
					}
					text2 += genericArguments[i].FullDescription();
				}
				text2 += ">";
			}
			return text2;
		}

		public static string FullDescription(this MethodBase method)
		{
			if ((object)method == null)
			{
				return "null";
			}
			Type[] parameters = (from p in method.GetParameters()
				select p.ParameterType).ToArray();
			Type returnedType = AccessTools.GetReturnedType(method);
			return returnedType.FullDescription() + " " + method.DeclaringType.FullDescription() + "." + method.Name + parameters.Description();
		}

		public static Type[] Types(this ParameterInfo[] pinfo)
		{
			return pinfo.Select((ParameterInfo pi) => pi.ParameterType).ToArray();
		}

		public static T GetValueSafe<S, T>(this Dictionary<S, T> dictionary, S key)
		{
			if (dictionary.TryGetValue(key, out var value))
			{
				return value;
			}
			return default(T);
		}

		public static T GetTypedValue<T>(this Dictionary<string, object> dictionary, string key)
		{
			if (dictionary.TryGetValue(key, out var value) && value is T)
			{
				return (T)value;
			}
			return default(T);
		}
	}
	public static class SymbolExtensions
	{
		public static MethodInfo GetMethodInfo(Expression<Action> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		public static MethodInfo GetMethodInfo<T>(Expression<Action<T>> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		public static MethodInfo GetMethodInfo<T, TResult>(Expression<Func<T, TResult>> expression)
		{
			return GetMethodInfo((LambdaExpression)expression);
		}

		public static MethodInfo GetMethodInfo(LambdaExpression expression)
		{
			return ((expression.Body as MethodCallExpression) ?? throw new ArgumentException("Invalid Expression. Expression should consist of a Method call only.")).Method ?? throw new MemberNotFoundException($"Cannot find method for expression {expression}");
		}
	}
	[Obsolete("Use HarmonyFileLog instead", true)]
	public static class FileLog
	{
		public static string logPath;

		public static char indentChar;

		public static int indentLevel;

		private static List<string> buffer;

		static FileLog()
		{
			indentChar = '\t';
			buffer = new List<string>();
			logPath = $"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}{Path.DirectorySeparatorChar}harmony.log.txt";
		}

		private static string IndentString()
		{
			return new string(indentChar, indentLevel);
		}

		public static void ChangeIndent(int delta)
		{
			indentLevel = Math.Max(0, indentLevel + delta);
		}

		public static void LogBuffered(string str)
		{
			lock (logPath)
			{
				buffer.Add(IndentString() + str);
			}
		}

		public static void LogBuffered(List<string> strings)
		{
			lock (logPath)
			{
				buffer.AddRange(strings);
			}
		}

		public static List<string> GetBuffer(bool clear)
		{
			lock (logPath)
			{
				List<string> result = buffer;
				if (clear)
				{
					buffer = new List<string>();
				}
				return result;
			}
		}

		public static void SetBuffer(List<string> buffer)
		{
			lock (logPath)
			{
				FileLog.buffer = buffer;
			}
		}

		public static void FlushBuffer()
		{
			lock (logPath)
			{
				if (buffer.Count <= 0)
				{
					return;
				}
				using (StreamWriter streamWriter = File.AppendText(logPath))
				{
					foreach (string item in buffer)
					{
						streamWriter.WriteLine(item);
					}
				}
				buffer.Clear();
			}
		}

		public static void Log(string str)
		{
			lock (logPath)
			{
				using StreamWriter streamWriter = File.AppendText(logPath);
				streamWriter.WriteLine(IndentString() + str);
			}
		}

		public static void Reset()
		{
			lock (logPath)
			{
				File.Delete($"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}{Path.DirectorySeparatorChar}harmony.log.txt");
			}
		}

		public unsafe static void LogBytes(long ptr, int len)
		{
			lock (logPath)
			{
				byte* ptr2 = (byte*)ptr;
				string text = "";
				for (int i = 1; i <= len; i++)
				{
					if (text == "")
					{
						text = "#  ";
					}
					text = $"{text}{*ptr2:X2} ";
					if (i > 1 || len == 1)
					{
						if (i % 8 == 0 || i == len)
						{
							Log(text);
							text = "";
						}
						else if (i % 4 == 0)
						{
							text += " ";
						}
					}
					ptr2++;
				}
				byte[] destination = new byte[len];
				Marshal.Copy((IntPtr)ptr, destination, 0, len);
				byte[] array = MD5.Create().ComputeHash(destination);
				StringBuilder stringBuilder = new StringBuilder();
				for (int j = 0; j < array.Length; j++)
				{
					stringBuilder.Append(array[j].ToString("X2"));
				}
				Log($"HASH: {stringBuilder}");
			}
		}
	}
	public static class AccessTools
	{
		public delegate ref U FieldRef<T, U>(T obj = default(T));

		public delegate ref F FieldRef<F>();

		public static BindingFlags all = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty;

		public static BindingFlags allDeclared = all | BindingFlags.DeclaredOnly;

		private static readonly MethodInfo m_PrepForRemoting = Method(typeof(Exception), "PrepForRemoting") ?? Method(typeof(Exception), "FixRemotingException");

		private static readonly FastInvokeHandler PrepForRemoting = MethodInvoker.GetHandler(m_PrepForRemoting);

		public static bool IsMonoRuntime { get; } = (object)Type.GetType("Mono.Runtime") != null;


		public static Type TypeByName(string name)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			Type type = Type.GetType(name, throwOnError: false);
			if ((object)type == null)
			{
				type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
					select assembly.GetType(name)).FirstOrDefault((Type t) => (object)t != null);
			}
			if ((object)type == null)
			{
				type = AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly x) => x.GetTypes()).FirstOrDefault((Type x) => x.Name == name);
			}
			if ((object)type == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => "AccessTools.TypeByName: Could not find type named " + name);
			}
			return type;
		}

		public static T FindIncludingBaseTypes<T>(Type type, Func<Type, T> func) where T : class
		{
			while (true)
			{
				T val = func(type);
				if (val != null)
				{
					return val;
				}
				if ((object)type == typeof(object))
				{
					break;
				}
				type = type.BaseType;
			}
			return null;
		}

		public static T FindIncludingInnerTypes<T>(Type type, Func<Type, T> func) where T : class
		{
			T val = func(type);
			if (val != null)
			{
				return val;
			}
			Type[] nestedTypes = type.GetNestedTypes(all);
			for (int i = 0; i < nestedTypes.Length; i++)
			{
				val = FindIncludingInnerTypes(nestedTypes[i], func);
				if (val != null)
				{
					break;
				}
			}
			return val;
		}

		public static FieldInfo DeclaredField(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			FieldInfo? field = type.GetField(name, allDeclared);
			if ((object)field == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredField: Could not find field for type {type} and name {name}");
			}
			return field;
		}

		public static FieldInfo Field(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			FieldInfo? fieldInfo = FindIncludingBaseTypes(type, (Type t) => t.GetField(name, all));
			if ((object)fieldInfo == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Field: Could not find field for type {type} and name {name}");
			}
			return fieldInfo;
		}

		public static FieldInfo DeclaredField(Type type, int idx)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			FieldInfo? fieldInfo = GetDeclaredFields(type).ElementAtOrDefault(idx);
			if ((object)fieldInfo == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredField: Could not find field for type {type} and idx {idx}");
			}
			return fieldInfo;
		}

		public static PropertyInfo DeclaredProperty(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			try
			{
				PropertyInfo? property = type.GetProperty(name, allDeclared);
				if ((object)property == null)
				{
					Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredProperty: Could not find property for type {type} and name {name}");
				}
				return property;
			}
			catch (AmbiguousMatchException inner)
			{
				throw new AmbiguousMatchException($"Ambiguous match for property {type}::{name}", inner);
			}
		}

		public static MethodInfo DeclaredPropertyGetter(Type type, string name)
		{
			return DeclaredProperty(type, name)?.GetGetMethod(nonPublic: true);
		}

		public static MethodInfo DeclaredPropertySetter(Type type, string name)
		{
			return DeclaredProperty(type, name)?.GetSetMethod(nonPublic: true);
		}

		public static PropertyInfo Property(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			PropertyInfo? propertyInfo = FindIncludingBaseTypes(type, (Type t) => t.GetProperty(name, all));
			if ((object)propertyInfo == null)
			{
				Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Property: Could not find property for type {type} and name {name}");
			}
			return propertyInfo;
		}

		public static MethodInfo PropertyGetter(Type type, string name)
		{
			return Property(type, name)?.GetGetMethod(nonPublic: true);
		}

		public static MethodInfo PropertySetter(Type type, string name)
		{
			return Property(type, name)?.GetSetMethod(nonPublic: true);
		}

		public static MethodInfo DeclaredMethod(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			ParameterModifier[] modifiers = new ParameterModifier[0];
			try
			{
				MethodInfo methodInfo = ((parameters != null) ? type.GetMethod(name, allDeclared, null, parameters, modifiers) : type.GetMethod(name, allDeclared));
				if ((object)methodInfo == null)
				{
					Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.DeclaredMethod: Could not find method for type {type} and name {name} and parameters {parameters?.Description()}");
					return null;
				}
				if (generics != null)
				{
					methodInfo = methodInfo.MakeGenericMethod(generics);
				}
				return methodInfo;
			}
			catch (AmbiguousMatchException inner)
			{
				string text = "";
				if (generics != null)
				{
					text = "<" + string.Join(", ", generics.Select((Type g) => g.FullName).ToArray()) + ">";
				}
				string text2 = "";
				if (parameters != null)
				{
					text2 = string.Join(", ", parameters.Select((Type p) => p.FullName).ToArray());
				}
				throw new AmbiguousMatchException($"Ambiguous match for {type}::{name}{text}(${text2})", inner);
			}
		}

		public static MethodInfo Method(Type type, string name, Type[] parameters = null, Type[] generics = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			try
			{
				ParameterModifier[] modifiers = new ParameterModifier[0];
				MethodInfo methodInfo;
				if (parameters == null)
				{
					try
					{
						methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all));
					}
					catch (AmbiguousMatchException inner)
					{
						methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all, null, new Type[0], modifiers));
						if ((object)methodInfo == null)
						{
							throw new AmbiguousMatchException($"Ambiguous match for {type}:{name}", inner);
						}
					}
				}
				else
				{
					methodInfo = FindIncludingBaseTypes(type, (Type t) => t.GetMethod(name, all, null, parameters, modifiers));
				}
				if ((object)methodInfo == null)
				{
					Logger.Log(Logger.LogChannel.Warn, () => $"AccessTools.Method: Could not find method for type {type} and name {name} and parameters {parameters?.Description()}");
					return null;
				}
				if (generics != null)
				{
					methodInfo = methodInfo.MakeGenericMethod(generics);
				}
				return methodInfo;
			}
			catch (AmbiguousMatchException inner2)
			{
				string text = "";
				if (generics != null)
				{
					text = "<" + string.Join(", ", generics.Select((Type g) => g.FullName).ToArray()) + ">";
				}
				string text2 = "";
				if (parameters != null)
				{
					text2 = string.Join(", ", parameters.Select((Type p) => p.FullName).ToArray());
				}
				throw new AmbiguousMatchException($"Ambiguous match for {type}::{name}{text}(${text2})", inner2);
			}
		}

		public static MethodInfo Method(string typeColonMethodname, Type[] parameters = null, Type[] generics = null)
		{
			if (typeColonMethodname == null)
			{
				throw new ArgumentNullException("typeColonMethodname");
			}
			string[] array = typeColonMethodname.Split(new char[1] { ':' });
			if (array.Length != 2)
			{
				throw new ArgumentException("Method must be specified as 'Namespace.Type1.Type2:MethodName", "typeColonMethodname");
			}
			return Method(TypeByName(array[0]), array[1], parameters, generics);
		}

		public static List<string> GetMethodNames(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from m in GetDeclaredMethods(type)
				select m.Name).ToList();
		}

		public static List<string> GetMethodNames(object instance)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			return GetMethodNames(instance.GetType());
		}

		public static List<string> GetFieldNames(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from f in GetDeclaredFields(type)
				select f.Name).ToList();
		}

		public static List<string> GetFieldNames(object instance)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			return GetFieldNames(instance.GetType());
		}

		public static List<string> GetPropertyNames(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from f in GetDeclaredProperties(type)
				select f.Name).ToList();
		}

		public static List<string> GetPropertyNames(object instance)
		{
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			return GetPropertyNames(instance.GetType());
		}

		public static Type GetUnderlyingType(this MemberInfo member)
		{
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			return member.MemberType switch
			{
				MemberTypes.Event => ((EventInfo)member).EventHandlerType, 
				MemberTypes.Field => ((FieldInfo)member).FieldType, 
				MemberTypes.Method => ((MethodInfo)member).ReturnType, 
				MemberTypes.Property => ((PropertyInfo)member).PropertyType, 
				_ => throw new ArgumentException("Member must be of type EventInfo, FieldInfo, MethodInfo, or PropertyInfo"), 
			};
		}

		public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			return type.GetConstructor(allDeclared, null, parameters, new ParameterModifier[0]);
		}

		public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters, bool searchForStatic)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			BindingFlags bindingFlags = (searchForStatic ? BindingFlags.Instance : BindingFlags.Static);
			return type.GetConstructor(allDeclared & ~bindingFlags, null, parameters, new ParameterModifier[0]);
		}

		public static ConstructorInfo Constructor(Type type, Type[] parameters = null)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			return FindIncludingBaseTypes(type, (Type t) => t.GetConstructor(all, null, parameters, new ParameterModifier[0]));
		}

		public static ConstructorInfo Constructor(Type type, Type[] parameters, bool searchForStatic)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (parameters == null)
			{
				parameters = new Type[0];
			}
			BindingFlags exclude = (searchForStatic ? BindingFlags.Instance : BindingFlags.Static);
			return FindIncludingBaseTypes(type, (Type t) => t.GetConstructor(all & ~exclude, null, parameters, new ParameterModifier[0]));
		}

		public static List<ConstructorInfo> GetDeclaredConstructors(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return (from method in type.GetConstructors(allDeclared)
				where (object)method.DeclaringType == type
				select method).ToList();
		}

		public static List<ConstructorInfo> GetDeclaredConstructors(Type type, bool? searchForStatic)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			BindingFlags bindingFlags = BindingFlags.Default;
			if (searchForStatic.HasValue)
			{
				bindingFlags = (searchForStatic.Value ? BindingFlags.Instance : BindingFlags.Static);
			}
			return (from method in type.GetConstructors(allDeclared & ~bindingFlags)
				where (object)method.DeclaringType == type
				select method).ToList();
		}

		public static List<MethodInfo> GetDeclaredMethods(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return type.GetMethods(allDeclared).ToList();
		}

		public static List<PropertyInfo> GetDeclaredProperties(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return type.GetProperties(allDeclared).ToList();
		}

		public static List<FieldInfo> GetDeclaredFields(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			return type.GetFields(allDeclared).ToList();
		}

		public static Type GetReturnedType(MethodBase methodOrConstructor)
		{
			if ((object)methodOrConstructor == null)
			{
				throw new ArgumentNullException("methodOrConstructor");
			}
			if (methodOrConstructor is ConstructorInfo)
			{
				return typeof(void);
			}
			return ((MethodInfo)methodOrConstructor).ReturnType;
		}

		public static Type Inner(Type type, string name)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			return FindIncludingBaseTypes(type, (Type t) => t.GetNestedType(name, all));
		}

		public static Type FirstInner(Type type, Func<Type, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetNestedTypes(all).FirstOrDefault(predicate);
		}

		public static MethodInfo FirstMethod(Type type, Func<MethodInfo, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetMethods(allDeclared).FirstOrDefault(predicate);
		}

		public static ConstructorInfo FirstConstructor(Type type, Func<ConstructorInfo, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetConstructors(allDeclared).FirstOrDefault(predicate);
		}

		public static PropertyInfo FirstProperty(Type type, Func<PropertyInfo, bool> predicate)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (predicate == null)
			{
				throw new ArgumentNullException("predicate");
			}
			return type.GetProperties(allDeclared).FirstOrDefault(predicate);
		}

		public static Type[] GetTypes(object[] parameters)
		{
			if (parameters == null)
			{
				return new Type[0];
			}
			return parameters.Select((object p) => (p != null) ? p.GetType() : typeof(object)).ToArray();
		}

		public static object[] ActualParameters(MethodBase method, object[] inputs)
		{
			if ((object)method == null)
			{
				throw new ArgumentNullException("method");
			}
			if (inputs == null)
			{
				throw new ArgumentNullException("inputs");
			}
			List<Type> inputTypes = inputs.Select((object obj) => obj?.GetType()).ToList();
			return (from p in method.GetParameters()
				select p.ParameterType).Select(delegate(Type pType)
			{
				int num = inputTypes.FindIndex((Type inType) => inputTypes != null && pType.IsAssignableFrom(inType));
				return (num >= 0) ? inputs[num] : GetDefaultValue(pType);
			}).ToArray();
		}

		public static FieldRef<T, U> FieldRefAccess<T, U>(string fieldName)
		{
			return FieldRefAccess<T, U>(typeof(T).GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic));
		}

		public static FieldRef<T, U> FieldRefAccess<T, U>(FieldInfo fieldInfo)
		{
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			if ((object)fieldInfo == null)
			{
				throw new ArgumentNullException("fieldInfo");
			}
			if (!typeof(U).IsAssignableFrom(fieldInfo.FieldType))
			{
				throw new ArgumentException("FieldInfo type does not match FieldRefAccess return type.");
			}
			if ((object)typeof(T) != typeof(object) && ((object)fieldInfo.DeclaringType == null || !fieldInfo.DeclaringType.IsAssignableFrom(typeof(T))))
			{
				throw new MissingFieldException(typeof(T).Name, fieldInfo.Name);
			}
			DynamicMethodDefinition val = new DynamicMethodDefinition("__refget_" + typeof(T).Name + "_fi_" + fieldInfo.Name, typeof(U).MakeByRefType(), new Type[1] { typeof(T) });
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldflda, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return Extensions.CreateDelegate<FieldRef<T, U>>((MethodBase)val.Generate());
		}

		public static ref U FieldRefAccess<T, U>(T instance, string fieldName)
		{
			return ref FieldRefAccess<T, U>(fieldName)(instance);
		}

		public static FieldRef<object, F> FieldRefAccess<F>(Type type, string fieldName)
		{
			return FieldRefAccess<object, F>(Field(type, fieldName));
		}

		public static ref F StaticFieldRefAccess<T, F>(string fieldName)
		{
			return ref StaticFieldRefAccess<F>(typeof(T), fieldName);
		}

		public static ref F StaticFieldRefAccess<T, F>(FieldInfo fieldInfo)
		{
			return ref StaticFieldRefAccess<F>(fieldInfo)();
		}

		public static FieldRef<F> StaticFieldRefAccess<F>(FieldInfo fieldInfo)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if ((object)fieldInfo == null)
			{
				throw new ArgumentNullException("fieldInfo");
			}
			Type declaringType = fieldInfo.DeclaringType;
			DynamicMethodDefinition val = new DynamicMethodDefinition("__refget_" + declaringType.Name + "_static_fi_" + fieldInfo.Name, typeof(F).MakeByRefType(), new Type[0]);
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldsflda, fieldInfo);
			iLGenerator.Emit(OpCodes.Ret);
			return Extensions.CreateDelegate<FieldRef<F>>((MethodBase)val.Generate());
		}

		public static ref F StaticFieldRefAccess<F>(Type type, string fieldName)
		{
			return ref StaticFieldRefAccess<F>(type.GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic))();
		}

		public static MethodBase GetOutsideCaller()
		{
			StackFrame[] frames = new StackTrace(fNeedFileInfo: true).GetFrames();
			for (int i = 0; i < frames.Length; i++)
			{
				Met

FrozenDevv-ModPack-1.1.0/BepInEx/core/BepInEx.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.ConsoleUtil;
using BepInEx.Logging;
using BepInEx.Unix;
using HarmonyLib;
using HarmonyLib.Tools;
using Microsoft.Win32.SafeHandles;
using Mono.Cecil;
using MonoMod.Utils;
using UnityEngine;
using UnityInjector.ConsoleUtil;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("BepInEx")]
[assembly: AssemblyDescription("Unity plugin injection framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BepInEx")]
[assembly: AssemblyCopyright("Copyright © Bepis 2018")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4ffba620-f5ed-47f9-b90c-dad1316fd9b9")]
[assembly: InternalsVisibleTo("BepInEx.Preloader")]
[assembly: InternalsVisibleTo("BepInExTests")]
[assembly: AssemblyFileVersion("5.4.21.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.4.21.0")]
[module: UnverifiableCode]
namespace UnityEngine
{
	internal sealed class UnityLogWriter
	{
		[MethodImpl(MethodImplOptions.InternalCall)]
		public static extern void WriteStringToUnityLogImpl(string s);

		[MethodImpl(MethodImplOptions.InternalCall)]
		public static extern void WriteStringToUnityLog(string s);
	}
}
namespace UnityInjector.ConsoleUtil
{
	internal class ConsoleEncoding : Encoding
	{
		private byte[] _byteBuffer = new byte[256];

		private char[] _charBuffer = new char[256];

		private byte[] _zeroByte = new byte[0];

		private char[] _zeroChar = new char[0];

		private readonly uint _codePage;

		public override int CodePage => (int)_codePage;

		public static Encoding OutputEncoding => new ConsoleEncoding(ConsoleCodePage);

		public static uint ConsoleCodePage
		{
			get
			{
				return GetConsoleOutputCP();
			}
			set
			{
				SetConsoleOutputCP(value);
			}
		}

		private void ExpandByteBuffer(int count)
		{
			if (_byteBuffer.Length < count)
			{
				_byteBuffer = new byte[count];
			}
		}

		private void ExpandCharBuffer(int count)
		{
			if (_charBuffer.Length < count)
			{
				_charBuffer = new char[count];
			}
		}

		private void ReadByteBuffer(byte[] bytes, int index, int count)
		{
			for (int i = 0; i < count; i++)
			{
				bytes[index + i] = _byteBuffer[i];
			}
		}

		private void ReadCharBuffer(char[] chars, int index, int count)
		{
			for (int i = 0; i < count; i++)
			{
				chars[index + i] = _charBuffer[i];
			}
		}

		private void WriteByteBuffer(byte[] bytes, int index, int count)
		{
			ExpandByteBuffer(count);
			for (int i = 0; i < count; i++)
			{
				_byteBuffer[i] = bytes[index + i];
			}
		}

		private void WriteCharBuffer(char[] chars, int index, int count)
		{
			ExpandCharBuffer(count);
			for (int i = 0; i < count; i++)
			{
				_charBuffer[i] = chars[index + i];
			}
		}

		public static uint GetActiveCodePage()
		{
			return GetACP();
		}

		private ConsoleEncoding(uint codePage)
		{
			_codePage = codePage;
		}

		public static ConsoleEncoding GetEncoding(uint codePage)
		{
			return new ConsoleEncoding(codePage);
		}

		public override int GetByteCount(char[] chars, int index, int count)
		{
			WriteCharBuffer(chars, index, count);
			return WideCharToMultiByte(_codePage, 0u, _charBuffer, count, _zeroByte, 0, IntPtr.Zero, IntPtr.Zero);
		}

		public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
		{
			int byteCount = GetByteCount(chars, charIndex, charCount);
			WriteCharBuffer(chars, charIndex, charCount);
			ExpandByteBuffer(byteCount);
			int result = WideCharToMultiByte(_codePage, 0u, chars, charCount, _byteBuffer, byteCount, IntPtr.Zero, IntPtr.Zero);
			ReadByteBuffer(bytes, byteIndex, byteCount);
			return result;
		}

		public override int GetCharCount(byte[] bytes, int index, int count)
		{
			WriteByteBuffer(bytes, index, count);
			return MultiByteToWideChar(_codePage, 0u, bytes, count, _zeroChar, 0);
		}

		public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
		{
			int charCount = GetCharCount(bytes, byteIndex, byteCount);
			WriteByteBuffer(bytes, byteIndex, byteCount);
			ExpandCharBuffer(charCount);
			int result = MultiByteToWideChar(_codePage, 0u, bytes, byteCount, _charBuffer, charCount);
			ReadCharBuffer(chars, charIndex, charCount);
			return result;
		}

		public override int GetMaxByteCount(int charCount)
		{
			return charCount * 2;
		}

		public override int GetMaxCharCount(int byteCount)
		{
			return byteCount;
		}

		[DllImport("kernel32.dll")]
		private static extern uint GetConsoleOutputCP();

		[DllImport("kernel32.dll")]
		private static extern uint GetACP();

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern int MultiByteToWideChar(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, [Out][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar);

		[DllImport("kernel32.dll")]
		private static extern IntPtr SetConsoleOutputCP(uint codepage);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern int WideCharToMultiByte(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar);
	}
	internal class ConsoleWindow
	{
		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		[return: MarshalAs(UnmanagedType.Bool)]
		private delegate bool SetForegroundWindowDelegate(IntPtr hWnd);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		private delegate IntPtr GetForegroundWindowDelegate();

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		private delegate IntPtr GetSystemMenuDelegate(IntPtr hwnd, bool bRevert);

		[UnmanagedFunctionPointer(CallingConvention.Winapi)]
		private delegate bool DeleteMenuDelegate(IntPtr hMenu, uint uPosition, uint uFlags);

		private const uint SC_CLOSE = 61536u;

		private const uint MF_BYCOMMAND = 0u;

		private const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 2048u;

		public static IntPtr ConsoleOutHandle;

		public static IntPtr OriginalStdoutHandle;

		private static bool methodsInited;

		private static SetForegroundWindowDelegate setForeground;

		private static GetForegroundWindowDelegate getForeground;

		private static GetSystemMenuDelegate getSystemMenu;

		private static DeleteMenuDelegate deleteMenu;

		public static bool IsAttached { get; private set; }

		public static string Title
		{
			set
			{
				if (IsAttached)
				{
					if (value == null)
					{
						throw new ArgumentNullException("value");
					}
					if (value.Length > 24500)
					{
						throw new InvalidOperationException("Console title too long");
					}
					if (!SetConsoleTitle(value))
					{
						throw new InvalidOperationException("Console title invalid");
					}
				}
			}
		}

		public static void Attach()
		{
			if (!IsAttached)
			{
				Initialize();
				if (OriginalStdoutHandle == IntPtr.Zero)
				{
					OriginalStdoutHandle = GetStdHandle(-11);
				}
				IntPtr hWnd = getForeground();
				GetConsoleWindow();
				if (GetConsoleWindow() == IntPtr.Zero && !AllocConsole())
				{
					throw new Exception("AllocConsole() failed");
				}
				setForeground(hWnd);
				ConsoleOutHandle = CreateFile("CONOUT$", 3221225472u, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
				Kon.conOut = ConsoleOutHandle;
				if (!SetStdHandle(-11, ConsoleOutHandle))
				{
					throw new Exception("SetStdHandle() failed");
				}
				if (OriginalStdoutHandle != IntPtr.Zero && ConsoleManager.ConfigConsoleOutRedirectType.Value == ConsoleManager.ConsoleOutRedirectType.ConsoleOut)
				{
					CloseHandle(OriginalStdoutHandle);
				}
				IsAttached = true;
			}
		}

		public static void PreventClose()
		{
			if (IsAttached)
			{
				Initialize();
				IntPtr consoleWindow = GetConsoleWindow();
				IntPtr intPtr = getSystemMenu(consoleWindow, bRevert: false);
				if (intPtr != IntPtr.Zero)
				{
					deleteMenu(intPtr, 61536u, 0u);
				}
			}
		}

		public static void Detach()
		{
			if (IsAttached)
			{
				if (!CloseHandle(ConsoleOutHandle))
				{
					throw new Exception("CloseHandle() failed");
				}
				ConsoleOutHandle = IntPtr.Zero;
				if (!FreeConsole())
				{
					throw new Exception("FreeConsole() failed");
				}
				if (!SetStdHandle(-11, OriginalStdoutHandle))
				{
					throw new Exception("SetStdHandle() failed");
				}
				IsAttached = false;
			}
		}

		private static void Initialize()
		{
			if (!methodsInited)
			{
				methodsInited = true;
				IntPtr hModule = LoadLibraryEx("user32.dll", IntPtr.Zero, 2048u);
				setForeground = DynDll.AsDelegate<SetForegroundWindowDelegate>(GetProcAddress(hModule, "SetForegroundWindow"));
				getForeground = DynDll.AsDelegate<GetForegroundWindowDelegate>(GetProcAddress(hModule, "GetForegroundWindow"));
				getSystemMenu = DynDll.AsDelegate<GetSystemMenuDelegate>(GetProcAddress(hModule, "GetSystemMenu"));
				deleteMenu = DynDll.AsDelegate<DeleteMenuDelegate>(GetProcAddress(hModule, "DeleteMenu"));
			}
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool AllocConsole();

		[DllImport("kernel32.dll")]
		private static extern IntPtr GetConsoleWindow();

		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		private static extern bool CloseHandle(IntPtr handle);

		[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		private static extern IntPtr CreateFile(string fileName, uint desiredAccess, int shareMode, IntPtr securityAttributes, int creationDisposition, int flagsAndAttributes, IntPtr templateFile);

		[DllImport("kernel32.dll")]
		private static extern bool FreeConsole();

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr GetStdHandle(int nStdHandle);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool SetStdHandle(int nStdHandle, IntPtr hConsoleOutput);

		[DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Auto, SetLastError = true)]
		private static extern bool SetConsoleTitle(string title);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr LoadLibraryEx(string lpLibFileName, IntPtr hFile, uint dwFlags);
	}
	internal static class SafeConsole
	{
		private delegate ConsoleColor GetColorDelegate();

		private delegate void SetColorDelegate(ConsoleColor value);

		private delegate string GetStringDelegate();

		private delegate void SetStringDelegate(string value);

		private static GetColorDelegate _getBackgroundColor;

		private static SetColorDelegate _setBackgroundColor;

		private static GetColorDelegate _getForegroundColor;

		private static SetColorDelegate _setForegroundColor;

		private static GetStringDelegate _getTitle;

		private static SetStringDelegate _setTitle;

		public static bool BackgroundColorExists { get; private set; }

		public static ConsoleColor BackgroundColor
		{
			get
			{
				return _getBackgroundColor();
			}
			set
			{
				_setBackgroundColor(value);
			}
		}

		public static bool ForegroundColorExists { get; private set; }

		public static ConsoleColor ForegroundColor
		{
			get
			{
				return _getForegroundColor();
			}
			set
			{
				_setForegroundColor(value);
			}
		}

		public static bool TitleExists { get; private set; }

		public static string Title
		{
			get
			{
				return _getTitle();
			}
			set
			{
				_setTitle(value);
			}
		}

		static SafeConsole()
		{
			InitColors(typeof(Console));
		}

		private static void InitColors(Type tConsole)
		{
			MethodInfo method = tConsole.GetMethod("get_ForegroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method2 = tConsole.GetMethod("set_ForegroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method3 = tConsole.GetMethod("get_BackgroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method4 = tConsole.GetMethod("set_BackgroundColor", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method5 = tConsole.GetMethod("get_Title", BindingFlags.Static | BindingFlags.Public);
			MethodInfo method6 = tConsole.GetMethod("set_Title", BindingFlags.Static | BindingFlags.Public);
			_setForegroundColor = (((object)method2 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method2)) : ((SetColorDelegate)delegate
			{
			}));
			_setBackgroundColor = (((object)method4 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method4)) : ((SetColorDelegate)delegate
			{
			}));
			_getForegroundColor = (((object)method != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method)) : ((GetColorDelegate)(() => ConsoleColor.Gray)));
			_getBackgroundColor = (((object)method3 != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method3)) : ((GetColorDelegate)(() => ConsoleColor.Black)));
			_getTitle = (((object)method5 != null) ? ((GetStringDelegate)Delegate.CreateDelegate(typeof(GetStringDelegate), method5)) : ((GetStringDelegate)(() => string.Empty)));
			_setTitle = (((object)method6 != null) ? ((SetStringDelegate)Delegate.CreateDelegate(typeof(SetStringDelegate), method6)) : ((SetStringDelegate)delegate
			{
			}));
			BackgroundColorExists = _setBackgroundColor != null && _getBackgroundColor != null;
			ForegroundColorExists = _setForegroundColor != null && _getForegroundColor != null;
			TitleExists = _setTitle != null && _getTitle != null;
		}
	}
}
namespace BepInEx
{
	public static class UnityInput
	{
		private static IInputSystem _current;

		public static IInputSystem Current
		{
			get
			{
				if (_current != null)
				{
					return _current;
				}
				try
				{
					try
					{
						Input.GetKeyDown((KeyCode)97);
						_current = new LegacyInputSystem();
						Logger.LogDebug("[UnityInput] Using LegacyInputSystem");
					}
					catch (InvalidOperationException)
					{
						_current = new NewInputSystem();
						Logger.LogDebug("[UnityInput] Using NewInputSystem");
					}
				}
				catch (Exception arg)
				{
					Logger.LogWarning($"[UnityInput] Failed to detect available input systems - {arg}");
					_current = new NullInputSystem();
				}
				return _current;
			}
		}

		public static bool LegacyInputSystemAvailable => Current is LegacyInputSystem;
	}
	public interface IInputSystem
	{
		Vector3 mousePosition { get; }

		Vector2 mouseScrollDelta { get; }

		bool mousePresent { get; }

		bool anyKey { get; }

		bool anyKeyDown { get; }

		IEnumerable<KeyCode> SupportedKeyCodes { get; }

		bool GetKey(string name);

		bool GetKey(KeyCode key);

		bool GetKeyDown(string name);

		bool GetKeyDown(KeyCode key);

		bool GetKeyUp(string name);

		bool GetKeyUp(KeyCode key);

		bool GetMouseButton(int button);

		bool GetMouseButtonDown(int button);

		bool GetMouseButtonUp(int button);

		void ResetInputAxes();
	}
	internal class NewInputSystem : IInputSystem
	{
		private delegate bool GetButtonDelegate(KeyCode key);

		private delegate Vector2 GetMouseVectorDelegate();

		private delegate bool GetMouseStateDelegate();

		private static bool initialized;

		private static readonly Dictionary<KeyCode, int> keyCodeToIndex = new Dictionary<KeyCode, int>();

		private static readonly Dictionary<string, string> keyToKeyCodeNameRemap = new Dictionary<string, string>
		{
			["LeftCtrl"] = "LeftControl",
			["RightCtrl"] = "RightControl",
			["LeftMeta"] = "LeftApple",
			["RightMeta"] = "RightApple",
			["ContextMenu"] = "Menu",
			["PrintScreen"] = "Print",
			["Enter"] = "Return"
		};

		private static GetButtonDelegate _getKey;

		private static GetButtonDelegate _getKeyDown;

		private static GetButtonDelegate _getKeyUp;

		private static GetButtonDelegate _getMouseButton;

		private static GetButtonDelegate _getMouseButtonDown;

		private static GetButtonDelegate _getMouseButtonUp;

		private static GetMouseVectorDelegate _getMousePosition;

		private static GetMouseVectorDelegate _getMouseScrollDelta;

		private static GetMouseStateDelegate _getMousePresent;

		private static GetMouseStateDelegate _getKeyboardAnyKeyIsPressed;

		private static GetMouseStateDelegate _getKeyboardAnyKeyWasPressedThisFrame;

		public Vector3 mousePosition => Vector2.op_Implicit(_getMousePosition());

		public Vector2 mouseScrollDelta => _getMouseScrollDelta();

		public bool mousePresent => _getMousePresent();

		public bool anyKey
		{
			get
			{
				if (_getKeyboardAnyKeyIsPressed())
				{
					return true;
				}
				if (!GetMouseButton(0) && !GetMouseButton(1) && !GetMouseButton(2) && !GetMouseButton(3))
				{
					return GetMouseButton(4);
				}
				return true;
			}
		}

		public bool anyKeyDown
		{
			get
			{
				if (_getKeyboardAnyKeyWasPressedThisFrame())
				{
					return true;
				}
				if (!GetMouseButtonDown(0) && !GetMouseButtonDown(1) && !GetMouseButtonDown(2) && !GetMouseButtonDown(3))
				{
					return GetMouseButtonDown(4);
				}
				return true;
			}
		}

		public IEnumerable<KeyCode> SupportedKeyCodes => keyCodeToIndex.Keys.ToArray();

		public NewInputSystem()
		{
			Init();
		}

		private static void Init()
		{
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			if (initialized)
			{
				return;
			}
			Assembly assembly = Assembly.Load("Unity.InputSystem");
			Type type = assembly.GetType("UnityEngine.InputSystem.Key");
			foreach (object value3 in Enum.GetValues(type))
			{
				string text = value3.ToString();
				int value = (int)value3;
				string value2;
				if (text.StartsWith("Numpad"))
				{
					text = text.Replace("Numpad", "Keypad");
				}
				else if (text.StartsWith("Digit"))
				{
					text = text.Replace("Digit", "Alpha");
				}
				else if (keyToKeyCodeNameRemap.TryGetValue(text, out value2))
				{
					text = value2;
				}
				if (TryEnumParse<KeyCode>(text, out var val))
				{
					keyCodeToIndex[val] = value;
				}
				else
				{
					Logger.LogDebug("[UnityInput] Unknown key name: " + text + ", skipping remapping");
				}
			}
			FieldInfo keyCodeToIndexField = AccessTools.Field(typeof(NewInputSystem), "keyCodeToIndex");
			MethodInfo tryGetValueMethod = AccessTools.Method(typeof(Dictionary<KeyCode, int>), "TryGetValue", (Type[])null, (Type[])null);
			Type type2 = assembly.GetType("UnityEngine.InputSystem.Keyboard");
			MethodInfo currentProperty = AccessTools.PropertyGetter(type2, "current");
			MethodInfo indexer = AccessTools.Method(type2, "get_Item", new Type[1] { type }, (Type[])null);
			Type buttonControlType = assembly.GetType("UnityEngine.InputSystem.Controls.ButtonControl");
			_getKey = GenerateKeyGetter("InputSystemGetKey", "isPressed");
			_getKeyDown = GenerateKeyGetter("InputSystemGetKeyDown", "wasPressedThisFrame");
			_getKeyUp = GenerateKeyGetter("InputSystemGetKeyUp", "wasReleasedThisFrame");
			Type mouseType = assembly.GetType("UnityEngine.InputSystem.Mouse");
			MethodInfo mouseCurrentProperty = AccessTools.PropertyGetter(mouseType, "current");
			string[] source = new string[5] { "leftButton", "rightButton", "middleButton", "backButton", "forwardButton" };
			MethodInfo[] buttonPropertyGetters = source.Select((string p) => AccessTools.PropertyGetter(mouseType, p)).ToArray();
			_getMouseButton = GenerateMouseGetter("InputSystemGetMouseButton", "isPressed");
			_getMouseButtonDown = GenerateMouseGetter("InputSystemGetMouseButtonDown", "wasPressedThisFrame");
			_getMouseButtonUp = GenerateMouseGetter("InputSystemGetMouseButtonUp", "wasReleasedThisFrame");
			_getMousePosition = GetPositionDelegate("InputSystemGetMousePosition", "position");
			_getMouseScrollDelta = GetPositionDelegate("InputSystemGetMouseScrollDelta", "scroll");
			DynamicMethodDefinition val2 = new DynamicMethodDefinition("InputSystemGetMouseEnabled", typeof(bool), Type.EmptyTypes);
			ILGenerator iLGenerator = val2.GetILGenerator();
			iLGenerator.Emit(OpCodes.Call, mouseCurrentProperty);
			iLGenerator.Emit(OpCodes.Callvirt, AccessTools.PropertyGetter(mouseType, "enabled"));
			iLGenerator.Emit(OpCodes.Ret);
			_getMousePresent = Extensions.CreateDelegate<GetMouseStateDelegate>((MethodBase)val2.Generate());
			MethodInfo anyKeyProperty = AccessTools.PropertyGetter(type2, "anyKey");
			_getKeyboardAnyKeyIsPressed = GetAnyKeyDelegate("InputSystemGetKeyboardAnyKeyIsPressed", "isPressed");
			_getKeyboardAnyKeyWasPressedThisFrame = GetAnyKeyDelegate("InputSystemGetKeyboardAnyKeyWasPressedThisFrame", "wasPressedThisFrame");
			initialized = true;
			GetButtonDelegate GenerateKeyGetter(string name, string property)
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				MethodInfo meth4 = AccessTools.PropertyGetter(buttonControlType, property);
				DynamicMethodDefinition val6 = new DynamicMethodDefinition(name, typeof(bool), new Type[1] { typeof(KeyCode) });
				ILGenerator iLGenerator4 = val6.GetILGenerator();
				LocalBuilder local = iLGenerator4.DeclareLocal(typeof(int));
				Label label2 = iLGenerator4.DefineLabel();
				iLGenerator4.Emit(OpCodes.Ldsfld, keyCodeToIndexField);
				iLGenerator4.Emit(OpCodes.Ldarg_0);
				iLGenerator4.Emit(OpCodes.Ldloca, local);
				iLGenerator4.Emit(OpCodes.Callvirt, tryGetValueMethod);
				iLGenerator4.Emit(OpCodes.Brfalse, label2);
				iLGenerator4.Emit(OpCodes.Call, currentProperty);
				iLGenerator4.Emit(OpCodes.Ldloc, local);
				iLGenerator4.Emit(OpCodes.Callvirt, indexer);
				iLGenerator4.Emit(OpCodes.Callvirt, meth4);
				iLGenerator4.Emit(OpCodes.Ret);
				iLGenerator4.MarkLabel(label2);
				iLGenerator4.Emit(OpCodes.Ldc_I4_0);
				iLGenerator4.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetButtonDelegate>((MethodBase)val6.Generate());
			}
			GetButtonDelegate GenerateMouseGetter(string name, string property)
			{
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Expected O, but got Unknown
				MethodInfo meth3 = AccessTools.PropertyGetter(buttonControlType, property);
				DynamicMethodDefinition val5 = new DynamicMethodDefinition(name, typeof(bool), new Type[1] { typeof(KeyCode) });
				ILGenerator il = val5.GetILGenerator();
				il.Emit(OpCodes.Ldarg_0);
				il.Emit(OpCodes.Ldc_I4, 323);
				il.Emit(OpCodes.Sub);
				Label[] array = buttonPropertyGetters.Select((MethodInfo _) => il.DefineLabel()).ToArray();
				Label label = il.DefineLabel();
				il.Emit(OpCodes.Switch, array);
				il.Emit(OpCodes.Br, label);
				for (int i = 0; i < array.Length; i++)
				{
					il.MarkLabel(array[i]);
					il.Emit(OpCodes.Call, mouseCurrentProperty);
					il.Emit(OpCodes.Callvirt, buttonPropertyGetters[i]);
					il.Emit(OpCodes.Callvirt, meth3);
					il.Emit(OpCodes.Ret);
				}
				il.MarkLabel(label);
				il.Emit(OpCodes.Ldc_I4_0);
				il.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetButtonDelegate>((MethodBase)val5.Generate());
			}
			GetMouseStateDelegate GetAnyKeyDelegate(string name, string property)
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				MethodInfo meth = AccessTools.PropertyGetter(buttonControlType, property);
				DynamicMethodDefinition val3 = new DynamicMethodDefinition(name, typeof(bool), Type.EmptyTypes);
				ILGenerator iLGenerator2 = val3.GetILGenerator();
				iLGenerator2.Emit(OpCodes.Call, currentProperty);
				iLGenerator2.Emit(OpCodes.Callvirt, anyKeyProperty);
				iLGenerator2.Emit(OpCodes.Callvirt, meth);
				iLGenerator2.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetMouseStateDelegate>((MethodBase)val3.Generate());
			}
			GetMouseVectorDelegate GetPositionDelegate(string name, string property)
			{
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				MethodInfo methodInfo = AccessTools.PropertyGetter(mouseType, property);
				MethodInfo meth2 = AccessTools.Method(methodInfo.ReturnType, "ReadValue", (Type[])null, (Type[])null);
				DynamicMethodDefinition val4 = new DynamicMethodDefinition(name, typeof(Vector2), Type.EmptyTypes);
				ILGenerator iLGenerator3 = val4.GetILGenerator();
				iLGenerator3.Emit(OpCodes.Call, mouseCurrentProperty);
				iLGenerator3.Emit(OpCodes.Callvirt, methodInfo);
				iLGenerator3.Emit(OpCodes.Callvirt, meth2);
				iLGenerator3.Emit(OpCodes.Ret);
				return Extensions.CreateDelegate<GetMouseVectorDelegate>((MethodBase)val4.Generate());
			}
		}

		public bool GetKey(string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return _getKey(GetKeyCode(name));
		}

		public bool GetKey(KeyCode key)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return _getKey(key);
		}

		public bool GetKeyDown(string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyDown(GetKeyCode(name));
		}

		public bool GetKeyDown(KeyCode key)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyDown(key);
		}

		public bool GetKeyUp(string name)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyUp(GetKeyCode(name));
		}

		public bool GetKeyUp(KeyCode key)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return _getKeyUp(key);
		}

		public bool GetMouseButton(int button)
		{
			return _getMouseButton((KeyCode)(323 + button));
		}

		public bool GetMouseButtonDown(int button)
		{
			return _getMouseButtonDown((KeyCode)(323 + button));
		}

		public bool GetMouseButtonUp(int button)
		{
			return _getMouseButtonUp((KeyCode)(323 + button));
		}

		public void ResetInputAxes()
		{
		}

		private static KeyCode GetKeyCode(string name)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			return (KeyCode)Enum.Parse(typeof(KeyCode), name, ignoreCase: true);
		}

		private static bool TryEnumParse<T>(string name, out T val)
		{
			try
			{
				val = (T)Enum.Parse(typeof(T), name, ignoreCase: true);
				return true;
			}
			catch (Exception)
			{
				val = default(T);
				return false;
			}
		}
	}
	internal class LegacyInputSystem : IInputSystem
	{
		public Vector3 mousePosition => Input.mousePosition;

		public Vector2 mouseScrollDelta => Input.mouseScrollDelta;

		public bool mousePresent => Input.mousePresent;

		public bool anyKey => Input.anyKey;

		public bool anyKeyDown => Input.anyKeyDown;

		public IEnumerable<KeyCode> SupportedKeyCodes { get; } = (KeyCode[])Enum.GetValues(typeof(KeyCode));


		public bool GetKey(string name)
		{
			return Input.GetKey(name);
		}

		public bool GetKey(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Input.GetKey(key);
		}

		public bool GetKeyDown(string name)
		{
			return Input.GetKeyDown(name);
		}

		public bool GetKeyDown(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Input.GetKeyDown(key);
		}

		public bool GetKeyUp(string name)
		{
			return Input.GetKeyUp(name);
		}

		public bool GetKeyUp(KeyCode key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Input.GetKeyUp(key);
		}

		public bool GetMouseButton(int button)
		{
			return Input.GetMouseButton(button);
		}

		public bool GetMouseButtonDown(int button)
		{
			return Input.GetMouseButtonDown(button);
		}

		public bool GetMouseButtonUp(int button)
		{
			return Input.GetMouseButtonUp(button);
		}

		public void ResetInputAxes()
		{
			Input.ResetInputAxes();
		}
	}
	internal class NullInputSystem : IInputSystem
	{
		private static readonly KeyCode[] NoKeys = (KeyCode[])(object)new KeyCode[0];

		public Vector3 mousePosition => Vector3.zero;

		public Vector2 mouseScrollDelta => Vector2.zero;

		public bool mousePresent => false;

		public bool anyKey => false;

		public bool anyKeyDown => false;

		public IEnumerable<KeyCode> SupportedKeyCodes => NoKeys;

		public bool GetKey(string name)
		{
			return false;
		}

		public bool GetKey(KeyCode key)
		{
			return false;
		}

		public bool GetKeyDown(string name)
		{
			return false;
		}

		public bool GetKeyDown(KeyCode key)
		{
			return false;
		}

		public bool GetKeyUp(string name)
		{
			return false;
		}

		public bool GetKeyUp(KeyCode key)
		{
			return false;
		}

		public bool GetMouseButton(int button)
		{
			return false;
		}

		public bool GetMouseButtonDown(int button)
		{
			return false;
		}

		public bool GetMouseButtonUp(int button)
		{
			return false;
		}

		public void ResetInputAxes()
		{
		}
	}
	internal static class ConsoleManager
	{
		public enum ConsoleOutRedirectType
		{
			[Description("Auto")]
			Auto,
			[Description("Console Out")]
			ConsoleOut,
			[Description("Standard Out")]
			StandardOut
		}

		private const uint SHIFT_JIS_CP = 932u;

		private static readonly bool? EnableConsoleArgOverride;

		private const string ENABLE_CONSOLE_ARG = "--enable-console";

		public static readonly ConfigEntry<bool> ConfigConsoleEnabled;

		public static readonly ConfigEntry<bool> ConfigPreventClose;

		public static readonly ConfigEntry<bool> ConfigConsoleShiftJis;

		public static readonly ConfigEntry<ConsoleOutRedirectType> ConfigConsoleOutRedirectType;

		internal static IConsoleDriver Driver { get; set; }

		public static bool ConsoleActive => Driver?.ConsoleActive ?? false;

		public static TextWriter StandardOutStream => Driver?.StandardOut;

		public static TextWriter ConsoleStream => Driver?.ConsoleOut;

		public static bool ConsoleEnabled => EnableConsoleArgOverride ?? ConfigConsoleEnabled.Value;

		static ConsoleManager()
		{
			ConfigConsoleEnabled = ConfigFile.CoreConfig.Bind("Logging.Console", "Enabled", defaultValue: false, "Enables showing a console for log output.");
			ConfigPreventClose = ConfigFile.CoreConfig.Bind("Logging.Console", "PreventClose", defaultValue: false, "If enabled, will prevent closing the console (either by deleting the close button or in other platform-specific way).");
			ConfigConsoleShiftJis = ConfigFile.CoreConfig.Bind("Logging.Console", "ShiftJisEncoding", defaultValue: false, "If true, console is set to the Shift-JIS encoding, otherwise UTF-8 encoding.");
			ConfigConsoleOutRedirectType = ConfigFile.CoreConfig.Bind("Logging.Console", "StandardOutType", ConsoleOutRedirectType.Auto, new StringBuilder().AppendLine("Hints console manager on what handle to assign as StandardOut. Possible values:").AppendLine("Auto - lets BepInEx decide how to redirect console output").AppendLine("ConsoleOut - prefer redirecting to console output; if possible, closes original standard output")
				.AppendLine("StandardOut - prefer redirecting to standard output; if possible, closes console out")
				.ToString());
			try
			{
				string[] commandLineArgs = Environment.GetCommandLineArgs();
				for (int i = 0; i < commandLineArgs.Length; i++)
				{
					if (commandLineArgs[i] == "--enable-console" && i + 1 < commandLineArgs.Length && bool.TryParse(commandLineArgs[i + 1], out var result))
					{
						EnableConsoleArgOverride = result;
					}
				}
			}
			catch (Exception)
			{
			}
		}

		public static void Initialize(bool alreadyActive)
		{
			if (PlatformHelper.Is((Platform)8))
			{
				Driver = new LinuxConsoleDriver();
			}
			else if (PlatformHelper.Is((Platform)37))
			{
				Driver = new WindowsConsoleDriver();
			}
			Driver.Initialize(alreadyActive);
		}

		private static void DriverCheck()
		{
			if (Driver == null)
			{
				throw new InvalidOperationException("Driver has not been initialized");
			}
		}

		public static void CreateConsole()
		{
			if (!ConsoleActive)
			{
				DriverCheck();
				uint codepage = (ConfigConsoleShiftJis.Value ? 932u : ((uint)Encoding.UTF8.CodePage));
				Driver.CreateConsole(codepage);
				if (ConfigPreventClose.Value)
				{
					Driver.PreventClose();
				}
			}
		}

		public static void DetachConsole()
		{
			if (ConsoleActive)
			{
				DriverCheck();
				Driver.DetachConsole();
			}
		}

		public static void SetConsoleTitle(string title)
		{
			DriverCheck();
			Driver.SetConsoleTitle(title);
		}

		public static void SetConsoleColor(ConsoleColor color)
		{
			DriverCheck();
			Driver.SetConsoleColor(color);
		}
	}
	internal interface IConsoleDriver
	{
		TextWriter StandardOut { get; }

		TextWriter ConsoleOut { get; }

		bool ConsoleActive { get; }

		bool ConsoleIsExternal { get; }

		void PreventClose();

		void Initialize(bool alreadyActive);

		void CreateConsole(uint codepage);

		void DetachConsole();

		void SetConsoleColor(ConsoleColor color);

		void SetConsoleTitle(string title);
	}
	internal class WindowsConsoleDriver : IConsoleDriver
	{
		private static readonly ConstructorInfo FileStreamCtor = new ConstructorInfo[2]
		{
			AccessTools.Constructor(typeof(FileStream), new Type[2]
			{
				typeof(SafeFileHandle),
				typeof(FileAccess)
			}, false),
			AccessTools.Constructor(typeof(FileStream), new Type[2]
			{
				typeof(IntPtr),
				typeof(FileAccess)
			}, false)
		}.FirstOrDefault((ConstructorInfo m) => (object)m != null);

		public TextWriter StandardOut { get; private set; }

		public TextWriter ConsoleOut { get; private set; }

		public bool ConsoleActive { get; private set; }

		public bool ConsoleIsExternal => true;

		public void PreventClose()
		{
			ConsoleWindow.PreventClose();
		}

		public void Initialize(bool alreadyActive)
		{
			ConsoleActive = alreadyActive;
			StandardOut = Console.Out;
		}

		private static FileStream OpenFileStream(IntPtr handle)
		{
			SafeFileHandle safeFileHandle = new SafeFileHandle(handle, ownsHandle: false);
			object[] args = AccessTools.ActualParameters((MethodBase)FileStreamCtor, new object[3]
			{
				safeFileHandle,
				safeFileHandle.DangerousGetHandle(),
				FileAccess.Write
			});
			return (FileStream)Activator.CreateInstance(typeof(FileStream), args);
		}

		public void CreateConsole(uint codepage)
		{
			ConsoleWindow.Attach();
			ConsoleEncoding.ConsoleCodePage = codepage;
			IntPtr outHandle = GetOutHandle();
			if (outHandle == IntPtr.Zero)
			{
				StandardOut = TextWriter.Null;
				ConsoleOut = TextWriter.Null;
				return;
			}
			FileStream stream = OpenFileStream(outHandle);
			StandardOut = new StreamWriter(stream, Utility.UTF8NoBom)
			{
				AutoFlush = true
			};
			FileStream stream2 = OpenFileStream(ConsoleWindow.ConsoleOutHandle);
			ConsoleOut = new StreamWriter(stream2, ConsoleEncoding.OutputEncoding)
			{
				AutoFlush = true
			};
			ConsoleActive = true;
		}

		private IntPtr GetOutHandle()
		{
			switch (ConsoleManager.ConfigConsoleOutRedirectType.Value)
			{
			case ConsoleManager.ConsoleOutRedirectType.ConsoleOut:
				return ConsoleWindow.ConsoleOutHandle;
			case ConsoleManager.ConsoleOutRedirectType.StandardOut:
				return ConsoleWindow.OriginalStdoutHandle;
			default:
				if (!(ConsoleWindow.OriginalStdoutHandle != IntPtr.Zero))
				{
					return ConsoleWindow.ConsoleOutHandle;
				}
				return ConsoleWindow.OriginalStdoutHandle;
			}
		}

		public void DetachConsole()
		{
			ConsoleWindow.Detach();
			ConsoleOut.Close();
			ConsoleOut = null;
			ConsoleActive = false;
		}

		public void SetConsoleColor(ConsoleColor color)
		{
			SafeConsole.ForegroundColor = color;
			Kon.ForegroundColor = color;
		}

		public void SetConsoleTitle(string title)
		{
			ConsoleWindow.Title = title;
		}
	}
	public class PluginInfo : ICacheable
	{
		public BepInPlugin Metadata { get; internal set; }

		public IEnumerable<BepInProcess> Processes { get; internal set; }

		public IEnumerable<BepInDependency> Dependencies { get; internal set; }

		public IEnumerable<BepInIncompatibility> Incompatibilities { get; internal set; }

		public string Location { get; internal set; }

		public BaseUnityPlugin Instance { get; internal set; }

		internal string TypeName { get; set; }

		internal Version TargettedBepInExVersion { get; set; }

		void ICacheable.Save(BinaryWriter bw)
		{
			bw.Write(TypeName);
			bw.Write(Metadata.GUID);
			bw.Write(Metadata.Name);
			bw.Write(Metadata.Version.ToString());
			List<BepInProcess> list = Processes.ToList();
			bw.Write(list.Count);
			foreach (BepInProcess item in list)
			{
				bw.Write(item.ProcessName);
			}
			List<BepInDependency> list2 = Dependencies.ToList();
			bw.Write(list2.Count);
			foreach (BepInDependency item2 in list2)
			{
				((ICacheable)item2).Save(bw);
			}
			List<BepInIncompatibility> list3 = Incompatibilities.ToList();
			bw.Write(list3.Count);
			foreach (BepInIncompatibility item3 in list3)
			{
				((ICacheable)item3).Save(bw);
			}
			bw.Write(TargettedBepInExVersion.ToString(4));
		}

		void ICacheable.Load(BinaryReader br)
		{
			TypeName = br.ReadString();
			Metadata = new BepInPlugin(br.ReadString(), br.ReadString(), br.ReadString());
			int num = br.ReadInt32();
			List<BepInProcess> list = new List<BepInProcess>(num);
			for (int i = 0; i < num; i++)
			{
				list.Add(new BepInProcess(br.ReadString()));
			}
			Processes = list;
			int num2 = br.ReadInt32();
			List<BepInDependency> list2 = new List<BepInDependency>(num2);
			for (int j = 0; j < num2; j++)
			{
				BepInDependency bepInDependency = new BepInDependency("");
				((ICacheable)bepInDependency).Load(br);
				list2.Add(bepInDependency);
			}
			Dependencies = list2;
			int num3 = br.ReadInt32();
			List<BepInIncompatibility> list3 = new List<BepInIncompatibility>(num3);
			for (int k = 0; k < num3; k++)
			{
				BepInIncompatibility bepInIncompatibility = new BepInIncompatibility("");
				((ICacheable)bepInIncompatibility).Load(br);
				list3.Add(bepInIncompatibility);
			}
			Incompatibilities = list3;
			TargettedBepInExVersion = new Version(br.ReadString());
		}

		public override string ToString()
		{
			return $"{Metadata?.Name} {Metadata?.Version}";
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
	public class BepInPlugin : Attribute
	{
		public string GUID { get; protected set; }

		public string Name { get; protected set; }

		public Version Version { get; protected set; }

		public BepInPlugin(string GUID, string Name, string Version)
		{
			this.GUID = GUID;
			this.Name = Name;
			try
			{
				this.Version = new Version(Version);
			}
			catch
			{
				this.Version = null;
			}
		}

		internal static BepInPlugin FromCecilType(TypeDefinition td)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			CustomAttribute val = MetadataHelper.GetCustomAttributes<BepInPlugin>(td, inherit: false).FirstOrDefault();
			if (val == null)
			{
				return null;
			}
			CustomAttributeArgument val2 = val.ConstructorArguments[0];
			string gUID = (string)((CustomAttributeArgument)(ref val2)).Value;
			val2 = val.ConstructorArguments[1];
			string name = (string)((CustomAttributeArgument)(ref val2)).Value;
			val2 = val.ConstructorArguments[2];
			return new BepInPlugin(gUID, name, (string)((CustomAttributeArgument)(ref val2)).Value);
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class BepInDependency : Attribute, ICacheable
	{
		[Flags]
		public enum DependencyFlags
		{
			HardDependency = 1,
			SoftDependency = 2
		}

		public string DependencyGUID { get; protected set; }

		public DependencyFlags Flags { get; protected set; }

		public Version MinimumVersion { get; protected set; }

		public BepInDependency(string DependencyGUID, DependencyFlags Flags = DependencyFlags.HardDependency)
		{
			this.DependencyGUID = DependencyGUID;
			this.Flags = Flags;
			MinimumVersion = new Version();
		}

		public BepInDependency(string DependencyGUID, string MinimumDependencyVersion)
			: this(DependencyGUID)
		{
			MinimumVersion = new Version(MinimumDependencyVersion);
		}

		internal static IEnumerable<BepInDependency> FromCecilType(TypeDefinition td)
		{
			return MetadataHelper.GetCustomAttributes<BepInDependency>(td, inherit: true).Select(delegate(CustomAttribute customAttribute)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				string dependencyGUID = (string)((CustomAttributeArgument)(ref val)).Value;
				val = customAttribute.ConstructorArguments[1];
				object value = ((CustomAttributeArgument)(ref val)).Value;
				return (value is string minimumDependencyVersion) ? new BepInDependency(dependencyGUID, minimumDependencyVersion) : new BepInDependency(dependencyGUID, (DependencyFlags)value);
			}).ToList();
		}

		void ICacheable.Save(BinaryWriter bw)
		{
			bw.Write(DependencyGUID);
			bw.Write((int)Flags);
			bw.Write(MinimumVersion.ToString());
		}

		void ICacheable.Load(BinaryReader br)
		{
			DependencyGUID = br.ReadString();
			Flags = (DependencyFlags)br.ReadInt32();
			MinimumVersion = new Version(br.ReadString());
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class BepInIncompatibility : Attribute, ICacheable
	{
		public string IncompatibilityGUID { get; protected set; }

		public BepInIncompatibility(string IncompatibilityGUID)
		{
			this.IncompatibilityGUID = IncompatibilityGUID;
		}

		internal static IEnumerable<BepInIncompatibility> FromCecilType(TypeDefinition td)
		{
			return MetadataHelper.GetCustomAttributes<BepInIncompatibility>(td, inherit: true).Select(delegate(CustomAttribute customAttribute)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				return new BepInIncompatibility((string)((CustomAttributeArgument)(ref val)).Value);
			}).ToList();
		}

		void ICacheable.Save(BinaryWriter bw)
		{
			bw.Write(IncompatibilityGUID);
		}

		void ICacheable.Load(BinaryReader br)
		{
			IncompatibilityGUID = br.ReadString();
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
	public class BepInProcess : Attribute
	{
		public string ProcessName { get; protected set; }

		public BepInProcess(string ProcessName)
		{
			this.ProcessName = ProcessName;
		}

		internal static List<BepInProcess> FromCecilType(TypeDefinition td)
		{
			return MetadataHelper.GetCustomAttributes<BepInProcess>(td, inherit: true).Select(delegate(CustomAttribute customAttribute)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				CustomAttributeArgument val = customAttribute.ConstructorArguments[0];
				return new BepInProcess((string)((CustomAttributeArgument)(ref val)).Value);
			}).ToList();
		}
	}
	public static class MetadataHelper
	{
		internal static IEnumerable<CustomAttribute> GetCustomAttributes<T>(TypeDefinition td, bool inherit) where T : Attribute
		{
			List<CustomAttribute> list = new List<CustomAttribute>();
			Type type = typeof(T);
			TypeDefinition val = td;
			do
			{
				list.AddRange(((IEnumerable<CustomAttribute>)val.CustomAttributes).Where((CustomAttribute ca) => ((MemberReference)ca.AttributeType).FullName == type.FullName));
				TypeReference baseType = val.BaseType;
				val = ((baseType != null) ? baseType.Resolve() : null);
			}
			while (inherit && ((val != null) ? ((MemberReference)val).FullName : null) != "System.Object");
			return list;
		}

		public static BepInPlugin GetMetadata(Type pluginType)
		{
			object[] customAttributes = pluginType.GetCustomAttributes(typeof(BepInPlugin), inherit: false);
			if (customAttributes.Length == 0)
			{
				return null;
			}
			return (BepInPlugin)customAttributes[0];
		}

		public static BepInPlugin GetMetadata(object plugin)
		{
			return GetMetadata(plugin.GetType());
		}

		public static T[] GetAttributes<T>(Type pluginType) where T : Attribute
		{
			return (T[])pluginType.GetCustomAttributes(typeof(T), inherit: true);
		}

		public static IEnumerable<T> GetAttributes<T>(object plugin) where T : Attribute
		{
			return GetAttributes<T>(plugin.GetType());
		}

		public static IEnumerable<BepInDependency> GetDependencies(Type plugin)
		{
			return plugin.GetCustomAttributes(typeof(BepInDependency), inherit: true).Cast<BepInDependency>();
		}
	}
	internal class BuildInfoAttribute : Attribute
	{
		public string Info { get; }

		public BuildInfoAttribute(string info)
		{
			Info = info;
		}
	}
	public abstract class BaseUnityPlugin : MonoBehaviour
	{
		public PluginInfo Info { get; }

		protected ManualLogSource Logger { get; }

		public ConfigFile Config { get; }

		protected BaseUnityPlugin()
		{
			BepInPlugin metadata = MetadataHelper.GetMetadata(this);
			if (metadata == null)
			{
				throw new InvalidOperationException("Can't create an instance of " + ((object)this).GetType().FullName + " because it inherits from BaseUnityPlugin and the BepInPlugin attribute is missing.");
			}
			if (!Chainloader.IsEditor && Chainloader.PluginInfos.TryGetValue(metadata.GUID, out var value))
			{
				Info = value;
			}
			else
			{
				Info = new PluginInfo
				{
					Metadata = metadata,
					Instance = this,
					Dependencies = MetadataHelper.GetDependencies(((object)this).GetType()),
					Processes = MetadataHelper.GetAttributes<BepInProcess>(((object)this).GetType()),
					Location = ((object)this).GetType().Assembly.Location
				};
			}
			Logger = BepInEx.Logging.Logger.CreateLogSource(metadata.Name);
			string text = (Chainloader.IsEditor ? "." : Paths.ConfigPath);
			Config = new ConfigFile(Utility.CombinePaths(text, metadata.GUID + ".cfg"), saveOnInit: false, metadata);
		}
	}
	public static class Paths
	{
		public static string[] DllSearchPaths { get; private set; }

		public static string BepInExAssemblyDirectory { get; private set; }

		public static string BepInExAssemblyPath { get; private set; }

		public static string BepInExRootPath { get; private set; }

		public static string ExecutablePath { get; private set; }

		public static string GameRootPath { get; private set; }

		public static string ManagedPath { get; private set; }

		public static string ConfigPath { get; private set; }

		public static string BepInExConfigPath { get; private set; }

		public static string CachePath { get; private set; }

		public static string PatcherPluginPath { get; private set; }

		public static string PluginPath { get; private set; }

		public static string ProcessName { get; private set; }

		internal static void SetExecutablePath(string executablePath, string bepinRootPath = null, string managedPath = null, string[] dllSearchPath = null)
		{
			ExecutablePath = executablePath;
			ProcessName = Path.GetFileNameWithoutExtension(executablePath);
			GameRootPath = (PlatformHelper.Is((Platform)73) ? Utility.ParentDirectory(executablePath, 4) : Path.GetDirectoryName(executablePath));
			ManagedPath = managedPath ?? Utility.CombinePaths(GameRootPath, ProcessName + "_Data", "Managed");
			BepInExRootPath = bepinRootPath ?? Path.Combine(GameRootPath, "BepInEx");
			ConfigPath = Path.Combine(BepInExRootPath, "config");
			BepInExConfigPath = Path.Combine(ConfigPath, "BepInEx.cfg");
			PluginPath = Path.Combine(BepInExRootPath, "plugins");
			PatcherPluginPath = Path.Combine(BepInExRootPath, "patchers");
			BepInExAssemblyDirectory = Path.Combine(BepInExRootPath, "core");
			BepInExAssemblyPath = Path.Combine(BepInExAssemblyDirectory, Assembly.GetExecutingAssembly().GetName().Name + ".dll");
			CachePath = Path.Combine(BepInExRootPath, "cache");
			DllSearchPaths = (dllSearchPath ?? new string[0]).Concat(new string[1] { ManagedPath }).Distinct().ToArray();
		}

		internal static void SetManagedPath(string managedPath)
		{
			if (managedPath != null)
			{
				ManagedPath = managedPath;
			}
		}

		internal static void SetPluginPath(string pluginPath)
		{
			PluginPath = Utility.CombinePaths(BepInExRootPath, pluginPath);
		}
	}
	public sealed class ThreadingHelper : MonoBehaviour, ISynchronizeInvoke
	{
		private sealed class InvokeResult : IAsyncResult
		{
			internal bool ExceptionThrown;

			public bool IsCompleted { get; private set; }

			public WaitHandle AsyncWaitHandle { get; }

			public object AsyncState { get; private set; }

			public bool CompletedSynchronously { get; private set; }

			public InvokeResult()
			{
				AsyncWaitHandle = new EventWaitHandle(initialState: false, EventResetMode.ManualReset);
			}

			public void Finish(object result, bool completedSynchronously)
			{
				AsyncState = result;
				CompletedSynchronously = completedSynchronously;
				IsCompleted = true;
				((EventWaitHandle)AsyncWaitHandle).Set();
			}
		}

		private readonly object _invokeLock = new object();

		private Action _invokeList;

		private Thread _mainThread;

		public static ThreadingHelper Instance { get; private set; }

		public static ISynchronizeInvoke SynchronizingObject => Instance;

		public bool InvokeRequired
		{
			get
			{
				if (_mainThread != null)
				{
					return _mainThread != Thread.CurrentThread;
				}
				return true;
			}
		}

		internal static void Initialize()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			GameObject val = new GameObject("BepInEx_ThreadingHelper");
			if (Chainloader.ConfigHideBepInExGOs.Value)
			{
				((Object)val).hideFlags = (HideFlags)61;
			}
			Object.DontDestroyOnLoad((Object)(object)val);
			Instance = val.AddComponent<ThreadingHelper>();
		}

		public void StartSyncInvoke(Action action)
		{
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}
			lock (_invokeLock)
			{
				_invokeList = (Action)Delegate.Combine(_invokeList, action);
			}
		}

		private void Update()
		{
			if (_mainThread == null)
			{
				_mainThread = Thread.CurrentThread;
			}
			if (_invokeList == null)
			{
				return;
			}
			Action invokeList;
			lock (_invokeLock)
			{
				invokeList = _invokeList;
				_invokeList = null;
			}
			foreach (Action item in invokeList.GetInvocationList().Cast<Action>())
			{
				try
				{
					item();
				}
				catch (Exception ex)
				{
					LogInvocationException(ex);
				}
			}
		}

		public void StartAsyncInvoke(Func<Action> action)
		{
			if (!ThreadPool.QueueUserWorkItem(DoWork))
			{
				throw new NotSupportedException("Failed to queue the action on ThreadPool");
			}
			void DoWork(object _)
			{
				try
				{
					Action action2 = action();
					if (action2 != null)
					{
						StartSyncInvoke(action2);
					}
				}
				catch (Exception ex)
				{
					LogInvocationException(ex);
				}
			}
		}

		private static void LogInvocationException(Exception ex)
		{
			Logger.Log(LogLevel.Error, ex);
			if (ex.InnerException != null)
			{
				Logger.Log(LogLevel.Error, "INNER: " + ex.InnerException);
			}
		}

		IAsyncResult ISynchronizeInvoke.BeginInvoke(Delegate method, object[] args)
		{
			InvokeResult result = new InvokeResult();
			if (!InvokeRequired)
			{
				result.Finish(Invoke(), completedSynchronously: true);
			}
			else
			{
				StartSyncInvoke(delegate
				{
					result.Finish(Invoke(), completedSynchronously: false);
				});
			}
			return result;
			object Invoke()
			{
				try
				{
					return method.DynamicInvoke(args);
				}
				catch (Exception result2)
				{
					result.ExceptionThrown = true;
					return result2;
				}
			}
		}

		object ISynchronizeInvoke.EndInvoke(IAsyncResult result)
		{
			InvokeResult invokeResult = (InvokeResult)result;
			invokeResult.AsyncWaitHandle.WaitOne();
			if (invokeResult.ExceptionThrown)
			{
				throw (Exception)invokeResult.AsyncState;
			}
			return invokeResult.AsyncState;
		}

		object ISynchronizeInvoke.Invoke(Delegate method, object[] args)
		{
			IAsyncResult result = ((ISynchronizeInvoke)this).BeginInvoke(method, args);
			return ((ISynchronizeInvoke)this).EndInvoke(result);
		}
	}
	public static class ThreadingExtensions
	{
		public static IEnumerable<TOut> RunParallel<TIn, TOut>(this IEnumerable<TIn> data, Func<TIn, TOut> work, int workerCount = -1)
		{
			foreach (TOut item in data.ToList().RunParallel(work))
			{
				yield return item;
			}
		}

		public static IEnumerable<TOut> RunParallel<TIn, TOut>(this IList<TIn> data, Func<TIn, TOut> work, int workerCount = -1)
		{
			if (workerCount < 0)
			{
				workerCount = Mathf.Max(2, Environment.ProcessorCount);
			}
			else if (workerCount == 0)
			{
				throw new ArgumentException("Need at least 1 worker", "workerCount");
			}
			int perThreadCount = Mathf.CeilToInt((float)data.Count / (float)workerCount);
			int doneCount = 0;
			object lockObj = new object();
			ManualResetEvent are = new ManualResetEvent(initialState: false);
			IEnumerable<TOut> doneItems = null;
			Exception exceptionThrown = null;
			for (int i = 0; i < workerCount; i++)
			{
				int first = i * perThreadCount;
				int last = Mathf.Min(first + perThreadCount, data.Count);
				ThreadPool.QueueUserWorkItem(delegate
				{
					List<TOut> list = new List<TOut>(perThreadCount);
					try
					{
						for (int j = first; j < last; j++)
						{
							if (exceptionThrown != null)
							{
								break;
							}
							list.Add(work(data[j]));
						}
					}
					catch (Exception ex)
					{
						exceptionThrown = ex;
					}
					lock (lockObj)
					{
						IEnumerable<TOut> enumerable2;
						if (doneItems != null)
						{
							enumerable2 = list.Concat(doneItems);
						}
						else
						{
							IEnumerable<TOut> enumerable3 = list;
							enumerable2 = enumerable3;
						}
						doneItems = enumerable2;
						int num = doneCount;
						doneCount = num + 1;
						are.Set();
					}
				});
			}
			bool isDone;
			do
			{
				are.WaitOne();
				IEnumerable<TOut> enumerable;
				lock (lockObj)
				{
					enumerable = doneItems;
					doneItems = null;
					isDone = doneCount == workerCount;
				}
				if (enumerable == null)
				{
					continue;
				}
				foreach (TOut item in enumerable)
				{
					yield return item;
				}
			}
			while (!isDone);
			if (exceptionThrown != null)
			{
				throw new TargetInvocationException("An exception was thrown inside one of the threads", exceptionThrown);
			}
		}
	}
	public static class Utility
	{
		private static bool? sreEnabled;

		public static bool CLRSupportsDynamicAssemblies => CheckSRE();

		public static Encoding UTF8NoBom { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);


		private static bool CheckSRE()
		{
			if (sreEnabled.HasValue)
			{
				return sreEnabled.Value;
			}
			try
			{
				new CustomAttributeBuilder(null, new object[0]);
			}
			catch (PlatformNotSupportedException)
			{
				sreEnabled = false;
				return sreEnabled.Value;
			}
			catch (ArgumentNullException)
			{
			}
			sreEnabled = true;
			return sreEnabled.Value;
		}

		public static bool TryDo(Action action, out Exception exception)
		{
			exception = null;
			try
			{
				action();
				return true;
			}
			catch (Exception ex)
			{
				exception = ex;
				return false;
			}
		}

		public static string CombinePaths(params string[] parts)
		{
			return parts.Aggregate(Path.Combine);
		}

		public static string ParentDirectory(string path, int levels = 1)
		{
			for (int i = 0; i < levels; i++)
			{
				path = Path.GetDirectoryName(path);
			}
			return path;
		}

		public static bool SafeParseBool(string input, bool defaultValue = false)
		{
			if (!bool.TryParse(input, out var result))
			{
				return defaultValue;
			}
			return result;
		}

		public static string ConvertToWWWFormat(string path)
		{
			return "file://" + path.Replace('\\', '/');
		}

		public static bool IsNullOrWhiteSpace(this string self)
		{
			return self?.All(char.IsWhiteSpace) ?? true;
		}

		public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector)
		{
			List<TNode> sorted_list = new List<TNode>();
			HashSet<TNode> visited = new HashSet<TNode>();
			HashSet<TNode> sorted = new HashSet<TNode>();
			foreach (TNode node in nodes)
			{
				Stack<TNode> stack2 = new Stack<TNode>();
				if (!Visit(node, stack2))
				{
					throw new Exception("Cyclic Dependency:\r\n" + stack2.Select((TNode x) => $" - {x}").Aggregate((string a, string b) => a + "\r\n" + b));
				}
			}
			return sorted_list;
			bool Visit(TNode node, Stack<TNode> stack)
			{
				if (visited.Contains(node))
				{
					if (!sorted.Contains(node))
					{
						return false;
					}
				}
				else
				{
					visited.Add(node);
					stack.Push(node);
					foreach (TNode item in dependencySelector(node))
					{
						if (!Visit(item, stack))
						{
							return false;
						}
					}
					sorted.Add(node);
					sorted_list.Add(node);
					stack.Pop();
				}
				return true;
			}
		}

		private static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class
		{
			assembly = null;
			List<string> list = new List<string>();
			list.Add(directory);
			list.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories));
			foreach (string item in list)
			{
				string text = Path.Combine(item, assemblyName.Name + ".dll");
				if (File.Exists(text))
				{
					try
					{
						assembly = loader(text);
					}
					catch (Exception)
					{
						continue;
					}
					return true;
				}
			}
			return false;
		}

		public static bool IsSubtypeOf(this TypeDefinition self, Type td)
		{
			if (((MemberReference)self).FullName == td.FullName)
			{
				return true;
			}
			if (((MemberReference)self).FullName != "System.Object")
			{
				TypeReference baseType = self.BaseType;
				return ((baseType == null) ? null : baseType.Resolve()?.IsSubtypeOf(td)).GetValueOrDefault();
			}
			return false;
		}

		public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly)
		{
			return TryResolveDllAssembly(assemblyName, directory, (Func<string, Assembly>)Assembly.LoadFile, out assembly);
		}

		public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly)
		{
			return TryResolveDllAssembly(assemblyName, directory, (Func<string, AssemblyDefinition>)((string s) => AssemblyDefinition.ReadAssembly(s, readerParameters)), out assembly);
		}

		public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read)
		{
			try
			{
				fileStream = new FileStream(path, mode, access, share);
				return true;
			}
			catch (IOException)
			{
				fileStream = null;
				return false;
			}
		}

		public static bool TryParseAssemblyName(string fullName, out AssemblyName assemblyName)
		{
			try
			{
				assemblyName = new AssemblyName(fullName);
				return true;
			}
			catch (Exception)
			{
				assemblyName = null;
				return false;
			}
		}

		public static IEnumerable<string> GetUniqueFilesInDirectories(IEnumerable<string> directories, string pattern = "*")
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
			foreach (string directory in directories)
			{
				string[] files = Directory.GetFiles(directory, pattern);
				foreach (string text in files)
				{
					string fileName = Path.GetFileName(text);
					if (!dictionary.ContainsKey(fileName))
					{
						dictionary[fileName] = text;
					}
				}
			}
			return dictionary.Values;
		}
	}
}
namespace BepInEx.Logging
{
	public class DiskLogListener : ILogListener, IDisposable
	{
		public LogLevel DisplayedLogLevel { get; set; }

		public TextWriter LogWriter { get; protected set; }

		public Timer FlushTimer { get; protected set; }

		public bool WriteFromUnityLog { get; set; }

		public DiskLogListener(string localPath, LogLevel displayedLogLevel = LogLevel.Info, bool appendLog = false, bool includeUnityLog = false)
		{
			WriteFromUnityLog = includeUnityLog;
			DisplayedLogLevel = displayedLogLevel;
			int num = 1;
			FileStream fileStream;
			while (!Utility.TryOpenFileStream(Path.Combine(Paths.BepInExRootPath, localPath), appendLog ? FileMode.Append : FileMode.Create, out fileStream, FileAccess.Write))
			{
				if (num == 5)
				{
					Logger.LogError("Couldn't open a log file for writing. Skipping log file creation");
					return;
				}
				Logger.LogWarning("Couldn't open log file '" + localPath + "' for writing, trying another...");
				localPath = $"LogOutput.log.{num++}";
			}
			LogWriter = TextWriter.Synchronized(new StreamWriter(fileStream, Utility.UTF8NoBom));
			FlushTimer = new Timer(delegate
			{
				LogWriter?.Flush();
			}, null, 2000, 2000);
		}

		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			if ((WriteFromUnityLog || !(eventArgs.Source is UnityLogSource)) && (eventArgs.Level & DisplayedLogLevel) != 0)
			{
				LogWriter.WriteLine(eventArgs.ToString());
			}
		}

		public void Dispose()
		{
			FlushTimer?.Dispose();
			LogWriter?.Flush();
			LogWriter?.Dispose();
		}

		~DiskLogListener()
		{
			Dispose();
		}
	}
	internal class HarmonyLogSource : ILogSource, IDisposable
	{
		private static readonly ConfigEntry<LogChannel> LogChannels = ConfigFile.CoreConfig.Bind<LogChannel>("Harmony.Logger", "LogChannels", (LogChannel)24, "Specifies which Harmony log channels to listen to.\nNOTE: IL channel dumps the whole patch methods, use only when needed!");

		private static readonly Dictionary<LogChannel, LogLevel> LevelMap = new Dictionary<LogChannel, LogLevel>
		{
			[(LogChannel)2] = LogLevel.Info,
			[(LogChannel)8] = LogLevel.Warning,
			[(LogChannel)16] = LogLevel.Error,
			[(LogChannel)4] = LogLevel.Debug
		};

		public string SourceName { get; } = "HarmonyX";


		public event EventHandler<LogEventArgs> LogEvent;

		public HarmonyLogSource()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			Logger.ChannelFilter = LogChannels.Value;
			Logger.MessageReceived += HandleHarmonyMessage;
		}

		private void HandleHarmonyMessage(object sender, LogEventArgs e)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if (LevelMap.TryGetValue(e.LogChannel, out var value))
			{
				this.LogEvent?.Invoke(this, new LogEventArgs(e.Message, value, this));
			}
		}

		public void Dispose()
		{
			Logger.MessageReceived -= HandleHarmonyMessage;
		}
	}
	public class LogEventArgs : EventArgs
	{
		public object Data { get; protected set; }

		public LogLevel Level { get; protected set; }

		public ILogSource Source { get; protected set; }

		public LogEventArgs(object data, LogLevel level, ILogSource source)
		{
			Data = data;
			Level = level;
			Source = source;
		}

		public override string ToString()
		{
			return $"[{Level,-7}:{Source.SourceName,10}] {Data}";
		}

		public string ToStringLine()
		{
			return ToString() + Environment.NewLine;
		}
	}
	public static class Logger
	{
		private class LogSourceCollection : List<ILogSource>, ICollection<ILogSource>, IEnumerable<ILogSource>, IEnumerable
		{
			void ICollection<ILogSource>.Add(ILogSource item)
			{
				if (item == null)
				{
					throw new ArgumentNullException("item", "Log sources cannot be null when added to the source list.");
				}
				item.LogEvent += InternalLogEvent;
				Add(item);
			}

			void ICollection<ILogSource>.Clear()
			{
				ILogSource[] array = ToArray();
				foreach (ILogSource item in array)
				{
					((ICollection<ILogSource>)this).Remove(item);
				}
			}

			bool ICollection<ILogSource>.Remove(ILogSource item)
			{
				if (item == null)
				{
					return false;
				}
				if (!Contains(item))
				{
					return false;
				}
				item.LogEvent -= InternalLogEvent;
				Remove(item);
				return true;
			}
		}

		private static readonly ManualLogSource InternalLogSource = CreateLogSource("BepInEx");

		private static bool internalLogsInitialized;

		public static ICollection<ILogListener> Listeners { get; } = new List<ILogListener>();


		public static ICollection<ILogSource> Sources { get; } = new LogSourceCollection();


		internal static void InitializeInternalLoggers()
		{
			if (!internalLogsInitialized)
			{
				Sources.Add(new HarmonyLogSource());
				internalLogsInitialized = true;
			}
		}

		internal static void InternalLogEvent(object sender, LogEventArgs eventArgs)
		{
			foreach (ILogListener listener in Listeners)
			{
				listener?.LogEvent(sender, eventArgs);
			}
		}

		internal static void Log(LogLevel level, object data)
		{
			InternalLogSource.Log(level, data);
		}

		internal static void LogFatal(object data)
		{
			Log(LogLevel.Fatal, data);
		}

		internal static void LogError(object data)
		{
			Log(LogLevel.Error, data);
		}

		internal static void LogWarning(object data)
		{
			Log(LogLevel.Warning, data);
		}

		internal static void LogMessage(object data)
		{
			Log(LogLevel.Message, data);
		}

		internal static void LogInfo(object data)
		{
			Log(LogLevel.Info, data);
		}

		internal static void LogDebug(object data)
		{
			Log(LogLevel.Debug, data);
		}

		public static ManualLogSource CreateLogSource(string sourceName)
		{
			ManualLogSource manualLogSource = new ManualLogSource(sourceName);
			Sources.Add(manualLogSource);
			return manualLogSource;
		}
	}
	[Flags]
	public enum LogLevel
	{
		None = 0,
		Fatal = 1,
		Error = 2,
		Warning = 4,
		Message = 8,
		Info = 0x10,
		Debug = 0x20,
		All = 0x3F
	}
	public static class LogLevelExtensions
	{
		public static LogLevel GetHighestLevel(this LogLevel levels)
		{
			Array values = Enum.GetValues(typeof(LogLevel));
			Array.Sort(values);
			foreach (LogLevel item in values)
			{
				if ((levels & item) != 0)
				{
					return item;
				}
			}
			return LogLevel.None;
		}

		public static ConsoleColor GetConsoleColor(this LogLevel level)
		{
			level = level.GetHighestLevel();
			return level switch
			{
				LogLevel.Fatal => ConsoleColor.Red, 
				LogLevel.Error => ConsoleColor.DarkRed, 
				LogLevel.Warning => ConsoleColor.Yellow, 
				LogLevel.Message => ConsoleColor.White, 
				LogLevel.Debug => ConsoleColor.DarkGray, 
				_ => ConsoleColor.Gray, 
			};
		}
	}
	public interface ILogListener : IDisposable
	{
		void LogEvent(object sender, LogEventArgs eventArgs);
	}
	public interface ILogSource : IDisposable
	{
		string SourceName { get; }

		event EventHandler<LogEventArgs> LogEvent;
	}
	public class ManualLogSource : ILogSource, IDisposable
	{
		public string SourceName { get; }

		public event EventHandler<LogEventArgs> LogEvent;

		public ManualLogSource(string sourceName)
		{
			SourceName = sourceName;
		}

		public void Log(LogLevel level, object data)
		{
			this.LogEvent?.Invoke(this, new LogEventArgs(data, level, this));
		}

		public void LogFatal(object data)
		{
			Log(LogLevel.Fatal, data);
		}

		public void LogError(object data)
		{
			Log(LogLevel.Error, data);
		}

		public void LogWarning(object data)
		{
			Log(LogLevel.Warning, data);
		}

		public void LogMessage(object data)
		{
			Log(LogLevel.Message, data);
		}

		public void LogInfo(object data)
		{
			Log(LogLevel.Info, data);
		}

		public void LogDebug(object data)
		{
			Log(LogLevel.Debug, data);
		}

		public void Dispose()
		{
		}
	}
	public class TraceLogSource : TraceListener
	{
		private static TraceLogSource traceListener;

		public static bool IsListening { get; protected set; }

		protected ManualLogSource LogSource { get; }

		public static ILogSource CreateSource()
		{
			if (traceListener == null)
			{
				traceListener = new TraceLogSource();
				Trace.Listeners.Add(traceListener);
				IsListening = true;
			}
			return traceListener.LogSource;
		}

		protected TraceLogSource()
		{
			LogSource = new ManualLogSource("Trace");
		}

		public override void Write(string message)
		{
			LogSource.LogInfo(message);
		}

		public override void WriteLine(string message)
		{
			LogSource.LogInfo(message);
		}

		public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
		{
			TraceEvent(eventCache, source, eventType, id, string.Format(format, args));
		}

		public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
		{
			LogSource.Log(eventType switch
			{
				TraceEventType.Critical => LogLevel.Fatal, 
				TraceEventType.Error => LogLevel.Error, 
				TraceEventType.Warning => LogLevel.Warning, 
				TraceEventType.Information => LogLevel.Info, 
				_ => LogLevel.Debug, 
			}, (message ?? "").Trim());
		}
	}
	public class ConsoleLogListener : ILogListener, IDisposable
	{
		private static readonly ConfigEntry<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind("Logging.Console", "LogLevels", LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, "Which log levels to show in the console output.");

		internal bool WriteUnityLogs { get; set; } = true;


		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			if ((WriteUnityLogs || !(sender is UnityLogSource)) && (eventArgs.Level & ConfigConsoleDisplayedLevel.Value) != 0)
			{
				ConsoleManager.SetConsoleColor(eventArgs.Level.GetConsoleColor());
				ConsoleManager.ConsoleStream?.Write(eventArgs.ToStringLine());
				ConsoleManager.SetConsoleColor(ConsoleColor.Gray);
			}
		}

		public void Dispose()
		{
		}
	}
	public class UnityLogListener : ILogListener, IDisposable
	{
		internal static readonly Action<string> WriteStringToUnityLog;

		private ConfigEntry<bool> LogConsoleToUnity = ConfigFile.CoreConfig.Bind("Logging", "LogConsoleToUnityLog", defaultValue: false, new StringBuilder().AppendLine("If enabled, writes Standard Output messages to Unity log").AppendLine("NOTE: By default, Unity does so automatically. Only use this option if no console messages are visible in Unity log").ToString());

		static UnityLogListener()
		{
			MethodInfo[] methods = typeof(UnityLogWriter).GetMethods(BindingFlags.Static | BindingFlags.Public);
			foreach (MethodInfo methodInfo in methods)
			{
				try
				{
					methodInfo.Invoke(null, new object[1] { "" });
				}
				catch
				{
					continue;
				}
				WriteStringToUnityLog = (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), methodInfo);
				break;
			}
			if (WriteStringToUnityLog == null)
			{
				Logger.LogError("Unable to start Unity log writer");
			}
		}

		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			if (!(eventArgs.Source is UnityLogSource) && (LogConsoleToUnity.Value || eventArgs.Source.SourceName != "Console"))
			{
				WriteStringToUnityLog?.Invoke(eventArgs.ToStringLine());
			}
		}

		public void Dispose()
		{
		}
	}
	public class UnityLogSource : ILogSource, IDisposable
	{
		private bool disposed;

		public string SourceName { get; } = "Unity Log";


		public event EventHandler<LogEventArgs> LogEvent;

		private static event EventHandler<LogEventArgs> InternalUnityLogMessage;

		public UnityLogSource()
		{
			InternalUnityLogMessage += UnityLogMessageHandler;
		}

		private void UnityLogMessageHandler(object sender, LogEventArgs eventArgs)
		{
			LogEventArgs e = new LogEventArgs(eventArgs.Data, eventArgs.Level, this);
			this.LogEvent?.Invoke(this, e);
		}

		public void Dispose()
		{
			if (!disposed)
			{
				InternalUnityLogMessage -= UnityLogMessageHandler;
				disposed = true;
			}
		}

		static UnityLogSource()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			LogCallback val = new LogCallback(OnUnityLogMessageReceived);
			EventInfo @event = typeof(Application).GetEvent("logMessageReceived", BindingFlags.Static | BindingFlags.Public);
			if ((object)@event != null)
			{
				@event.AddEventHandler(null, (Delegate?)(object)val);
				return;
			}
			typeof(Application).GetMethod("RegisterLogCallback", BindingFlags.Static | BindingFlags.Public).Invoke(null, new object[1] { val });
		}

		private static void OnUnityLogMessageReceived(string message, string stackTrace, LogType type)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected I4, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			LogLevel level;
			switch ((int)type)
			{
			case 0:
			case 1:
			case 4:
				level = LogLevel.Error;
				break;
			case 2:
				level = LogLevel.Warning;
				break;
			default:
				level = LogLevel.Info;
				break;
			}
			if ((int)type == 4)
			{
				message = message + "\nStack trace:\n" + stackTrace;
			}
			UnityLogSource.InternalUnityLogMessage?.Invoke(null, new LogEventArgs(message, level, null));
		}
	}
}
namespace BepInEx.Bootstrap
{
	public static class Chainloader
	{
		private static readonly List<BaseUnityPlugin> _plugins = new List<BaseUnityPlugin>();

		private static bool? isEditor;

		private static bool _loaded = false;

		private static bool _initialized = false;

		private static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;

		private static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;

		internal static readonly ConfigEntry<bool> ConfigHideBepInExGOs = ConfigFile.CoreConfig.Bind("Chainloader", "HideManagerGameObject", defaultValue: false, new StringBuilder().AppendLine("If enabled, hides BepInEx Manager GameObject from Unity.").AppendLine("This can fix loading issues in some games that attempt to prevent BepInEx from being loaded.").AppendLine("Use this only if you know what this option means, as it can affect functionality of some older plugins.")
			.ToString());

		private static readonly ConfigEntry<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Bind("Logging", "UnityLogListening", defaultValue: true, "Enables showing unity log messages in the BepInEx logging system.");

		private static readonly ConfigEntry<bool> ConfigDiskWriteUnityLog = ConfigFile.CoreConfig.Bind("Logging.Disk", "WriteUnityLog", defaultValue: false, "Include unity log messages in log file output.");

		private static readonly ConfigEntry<bool> ConfigDiskAppend = ConfigFile.CoreConfig.Bind("Logging.Disk", "AppendLog", defaultValue: false, "Appends to the log file instead of overwriting, on game startup.");

		private static readonly ConfigEntry<bool> ConfigDiskLogging = ConfigFile.CoreConfig.Bind("Logging.Disk", "Enabled", defaultValue: true, "Enables writing log messages to disk.");

		private static readonly ConfigEntry<LogLevel> ConfigDiskConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind("Logging.Disk", "LogLevels", LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, "Which log leves are saved to the disk log output.");

		public static Dictionary<string, PluginInfo> PluginInfos { get; } = new Dictionary<string, PluginInfo>();


		private static string UnityVersion
		{
			[MethodImpl(MethodImplOptions.NoInlining)]
			get
			{
				return Application.unityVersion;
			}
		}

		private static bool IsHeadless
		{
			get
			{
				MethodInfo methodInfo = AccessTools.PropertyGetter(typeof(Application), "isBatchMode");
				if ((object)methodInfo != null)
				{
					return (bool)methodInfo.Invoke(null, null);
				}
				return SystemInfo.graphicsDeviceID == 0;
			}
		}

		internal static bool IsEditor
		{
			[MethodImpl(MethodImplOptions.NoInlining)]
			get
			{
				bool? flag = isEditor;
				if (!flag.HasValue)
				{
					bool? flag2 = (isEditor = Application.isEditor);
					return flag2.GetValueOrDefault();
				}
				return flag.GetValueOrDefault();
			}
		}

		[Obsolete("Use PluginInfos instead")]
		public static List<BaseUnityPlugin> Plugins
		{
			get
			{
				lock (_plugins)
				{
					_plugins.RemoveAll((BaseUnityPlugin x) => (Object)(object)x == (Object)null);
					return _plugins.ToList();
				}
			}
		}

		public static List<string> DependencyErrors { get; } = new List<string>();


		public static GameObject ManagerObject { get; private set; }

		private static Regex allowedGuidRegex { get; } = new Regex("^[a-zA-Z0-9\\._\\-]+$");


		public static void Initialize(string gameExePath, bool startConsole = true, ICollection<LogEventArgs> preloaderLogEvents = null)
		{
			if (!_initialized)
			{
				ThreadingHelper.Initialize();
				if (gameExePath != null)
				{
					Paths.SetExecutablePath(gameExePath);
				}
				if (ConsoleManager.ConsoleEnabled && startConsole)
				{
					ConsoleManager.CreateConsole();
					Logger.Listeners.Add(new ConsoleLogListener());
				}
				Logger.InitializeInternalLoggers();
				if (ConfigDiskLogging.Value)
				{
					Logger.Listeners.Add(new DiskLogListener("LogOutput.log", ConfigDiskConsoleDisplayedLevel.Value, ConfigDiskAppend.Value, ConfigDiskWriteUnityLog.Value));
				}
				if (!TraceLogSource.IsListening)
				{
					Logger.Sources.Add(TraceLogSource.CreateSource());
				}
				ReplayPreloaderLogs(preloaderLogEvents);
				if (ConfigUnityLogging.Value)
				{
					Logger.Sources.Add(new UnityLogSource());
				}
				if (!IsHeadless)
				{
					Logger.Listeners.Add(new UnityLogListener());
				}
				else if (Logger.Listeners.FirstOrDefault((ILogListener l) => l is ConsoleLogListener) is ConsoleLogListener consoleLogListener)
				{
					consoleLogListener.WriteUnityLogs = false;
				}
				if (PlatformHelper.Is((Platform)8))
				{
					Logger.LogInfo("Detected Unity version: v" + UnityVersion);
				}
				Logger.LogMessage("Chainloader ready");
				_initialized = true;
			}
		}

		private static void ReplayPreloaderLogs(ICollection<LogEventArgs> preloaderLogEvents)
		{
			if (preloaderLogEvents == null)
			{
				return;
			}
			UnityLogListener item = new UnityLogListener();
			Logger.Listeners.Add(item);
			ILogListener logListener = Logger.Listeners.FirstOrDefault((ILogListener logger) => logger is ConsoleLogListener);
			if (logListener != null)
			{
				Logger.Listeners.Remove(logListener);
			}
			ManualLogSource manualLogSource = Logger.CreateLogSource("Preloader");
			foreach (LogEventArgs preloaderLogEvent in preloaderLogEvents)
			{
				Logger.InternalLogEvent(manualLogSource, preloaderLogEvent);
			}
			Logger.Sources.Remove(manualLogSource);
			Logger.Listeners.Remove(item);
			if (logListener != null)
			{
				Logger.Listeners.Add(logListener);
			}
		}

		public static PluginInfo ToPluginInfo(TypeDefinition type)
		{
			if (type.IsInterface || type.IsAbstract)
			{
				return null;
			}
			try
			{
				if (!type.IsSubtypeOf(typeof(BaseUnityPlugin)))
				{
					return null;
				}
			}
			catch (AssemblyResolutionException)
			{
				return null;
			}
			BepInPlugin bepInPlugin = BepInPlugin.FromCecilType(type);
			if (bepInPlugin == null)
			{
				Logger.LogWarning("Skipping over type [" + ((MemberReference)type).FullName + "] as no metadata attribute is specified");
				return null;
			}
			if (string.IsNullOrEmpty(bepInPlugin.GUID) || !allowedGuidRegex.IsMatch(bepInPlugin.GUID))
			{
				Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its GUID [" + bepInPlugin.GUID + "] is of an illegal format.");
				return null;
			}
			if (bepInPlugin.Version == null)
			{
				Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its version is invalid.");
				return null;
			}
			if (bepInPlugin.Name == null)
			{
				Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its name is null.");
				return null;
			}
			List<BepInProcess> processes = BepInProcess.FromCecilType(type);
			IEnumerable<BepInDependency> dependencies = BepInDependency.FromCecilType(type);
			IEnumerable<BepInIncompatibility> incompatibilities = BepInIncompatibility.FromCecilType(type);
			AssemblyNameReference? obj = ((IEnumerable<AssemblyNameReference>)((MemberReference)type).Module.AssemblyReferences).FirstOrDefault((Func<AssemblyNameReference, bool>)((AssemblyNameReference reference) => reference.Name == "BepInEx"));
			Version targettedBepInExVersion = ((obj != null) ? obj.Version : null) ?? new Version();
			return new PluginInfo
			{
				Metadata = bepInPlugin,
				Processes = processes,
				Dependencies = dependencies,
				Incompatibilities = incompatibilities,
				TypeName = ((MemberReference)type).FullName,
				TargettedBepInExVersion = targettedBepInExVersion
			};
		}

		private static bool HasBepinPlugins(AssemblyDefinition ass)
		{
			if (((IEnumerable<AssemblyNameReference>)ass.MainModule.AssemblyReferences).All((AssemblyNameReference r) => r.Name != CurrentAssemblyName))
			{
				return false;
			}
			if (ass.MainModule.GetTypeReferences().All((TypeReference r) => ((MemberReference)r).FullName != typeof(BepInPlugin).FullName))
			{
				return false;
			}
			return true;
		}

		private static bool PluginTargetsWrongBepin(PluginInfo pluginInfo)
		{
			Version targettedBepInExVersion = pluginInfo.TargettedBepInExVersion;
			if (targettedBepInExVersion.Major != CurrentAssemblyVersion.Major)
			{
				return true;
			}
			if (targettedBepInExVersion.Minor > CurrentAssemblyVersion.Minor)
			{
				return true;
			}
			if (targettedBepInExVersion.Minor < CurrentAssemblyVersion.Minor)
			{
				return false;
			}
			return targettedBepInExVersion.Build > CurrentAssemblyVersion.Build;
		}

		public static void Start()
		{
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			if (_loaded)
			{
				return;
			}
			if (!_initialized)
			{
				throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
			}
			if (!Directory.Exists(Paths.PluginPath))
			{
				Directory.CreateDirectory(Paths.PluginPath);
			}
			if (!Directory.Exists(Paths.PatcherPluginPath))
			{
				Directory.CreateDirectory(Paths.PatcherPluginPath);
			}
			try
			{
				PropertyInfo property = typeof(Application).GetProperty("productName", BindingFlags.Static | BindingFlags.Public);
				if (ConsoleManager.ConsoleActive)
				{
					ConsoleManager.SetConsoleTitle($"{CurrentAssemblyName} {CurrentAssemblyVersion} - {property?.GetValue(null, null) ?? Paths.ProcessName}");
				}
				Logger.LogMessage("Chainloader started");
				ManagerObject = new GameObject("BepInEx_Manager");
				if (ConfigHideBepInExGOs.Value)
				{
					((Object)ManagerObject).hideFlags = (HideFlags)61;
				}
				Object.DontDestroyOnLoad((Object)(object)ManagerObject);
				Dictionary<string, List<PluginInfo>> dictionary = TypeLoader.FindPluginTypes(Paths.PluginPath, ToPluginInfo, HasBepinPlugins, "chainloader");
				foreach (KeyValuePair<string, List<PluginInfo>> item in dictionary)
				{
					foreach (PluginInfo item2 in item.Value)
					{
						item2.Location = item.Key;
					}
				}
				List<PluginInfo> list = dictionary.SelectMany((KeyValuePair<string, List<PluginInfo>> p) => p.Value).ToList();
				Dictionary<string, Assembly> dictionary2 = new Dictionary<string, Assembly>();
				Logger.LogInfo(string.Format("{0} plugin{1} to load", list.Count, (PluginInfos.Count == 1) ? "" : "s"));
				SortedDictionary<string, IEnumerable<string>> dependencyDict = new SortedDictionary<string, IEnumerable<string>>(StringComparer.InvariantCultureIgnoreCase);
				Dictionary<string, PluginInfo> pluginsByGUID = new Dictionary<string, PluginInfo>();
				foreach (IGrouping<string, PluginInfo> item3 in from info in list
					group info by info.Metadata.GUID)
				{
					PluginInfo pluginInfo = null;
					foreach (PluginInfo item4 in item3.OrderByDescending((PluginInfo x) => x.Metadata.Version))
					{
						if (pluginInfo != null)
						{
							Logger.LogWarning($"Skipping [{item4}] because a newer version exists ({pluginInfo})");
							continue;
						}
						List<BepInProcess> list2 = item4.Processes.ToList();
						if (list2.Count != 0 && list2.All((BepInProcess x) => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase)))
						{
							Logger.LogWarning(string.Format("Skipping [{0}] because of process filters ({1})", item4, string.Join(", ", item4.Processes.Select((BepInProcess p) => p.ProcessName).ToArray())));
							continue;
						}
						pluginInfo = item4;
						dependencyDict[item4.Metadata.GUID] = item4.Dependencies.Select((BepInDependency d) => d.DependencyGUID);
						pluginsByGUID[item4.Metadata.GUID] = item4;
					}
				}
				foreach (PluginInfo item5 in pluginsByGUID.Values.ToList())
				{
					if (item5.Incompatibilities.Any((BepInIncompatibility incompatibility) => pluginsByGUID.ContainsKey(incompatibility.IncompatibilityGUID)))
					{
						pluginsByGUID.Remove(item5.Metadata.GUID);
						dependencyDict.Remove(item5.Metadata.GUID);
						string[] value = (from x in item5.Incompatibilities
							select x.IncompatibilityGUID into x
							where pluginsByGUID.ContainsKey(x)
							select x).ToArray();
						string text = string.Format("Could not load [{0}] because it is incompatible with: {1}", item5, string.Join(", ", value));
						DependencyErrors.Add(text);
						Logger.LogError(text);
					}
					else if (PluginTargetsWrongBepin(item5))
					{
						string text2 = $"Plugin [{item5}] targets a wrong version of BepInEx ({item5.TargettedBepInExVersion}) and might not work until you update";
						DependencyErrors.Add(text2);
						Logger.LogWarning(text2);
					}
				}
				string[] emptyDependencies = new string[0];
				IEnumerable<string> value5;
				List<string> list3 = Utility.TopologicalSort(dependencyDict.Keys, (string x) => (!dependencyDict.TryGetValue(x, out value5)) ? emptyDependencies : value5).ToList();
				HashSet<string> hashSet = new HashSet<string>();
				Dictionary<string, Version> dictionary3 = new Dictionary<string, Version>();
				foreach (string item6 in list3)
				{
					if (!pluginsByGUID.TryGetValue(item6, out var value2))
					{
						continue;
					}
					bool flag = false;
					List<BepInDependency> list4 = new List<BepInDependency>();
					foreach (BepInDependency dependency in value2.Dependencies)
					{
						if (!dictionary3.TryGetValue(dependency.DependencyGUID, out var value3) || value3 < dependency.MinimumVersion)
						{
							if (IsHardDependency(dependency))
							{
								list4.Add(dependency);
							}
						}
						else if (hashSet.Contains(dependency.DependencyGUID) && IsHardDependency(dependency))
						{
							flag = true;
							break;
						}
					}
					dictionary3.Add(item6, value2.Metadata.Version);
					if (flag)
					{
						string text3 = $"Skipping [{value2}] because it has a dependency that was not loaded. See previous errors for details.";
						DependencyErrors.Add(text3);
						Logger.LogWarning(text3);
						continue;
					}
					if (list4.Count != 0)
					{
						string text4 = string.Format("Could not load [{0}] because it has missing dependencies: {1}", value2, string.Join(", ", list4.Select((BepInDependency s) => (!IsEmptyVersion(s.MinimumVersion)) ? $"{s.DependencyGUID} (v{s.MinimumVersion} or newer)" : s.DependencyGUID).ToArray()));
						DependencyErrors.Add(text4);
						Logger.LogError(text4);
						hashSet.Add(item6);
						continue;
					}
					try
					{
						Logger.LogInfo($"Loading [{value2}]");
						if (!dictionary2.TryGetValue(value2.Location, out var value4))
						{
							value4 = (dictionary2[value2.Location] = Assembly.LoadFile(value2.Location));
						}
						PluginInfos[item6] = value2;
						value2.Instance = (BaseUnityPlugin)(object)ManagerObject.AddComponent(value4.GetType(value2.TypeName));
						_plugins.Add(value2.Instance);
					}
					catch (Exception ex)
					{
						hashSet.Add(item6);
						PluginInfos.Remove(item6);
						Logger.LogError($"Error loading [{value2}] : {ex.Message}");
						if (ex is ReflectionTypeLoadException ex2)
						{
							Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(ex2));
						}
						else
						{
							Logger.LogDebug(ex);
						}
					}
				}
			}
			catch (Exception ex3)
			{
				try
				{
					ConsoleManager.CreateConsole();
				}
				catch
				{
				}
				Logger.LogFatal("Error occurred starting the game");
				Logger.LogFatal(ex3.ToString());
			}
			Logger.LogMessage("Chainloader startup complete");
			_loaded = true;
			static bool IsEmptyVersion(Version v)
			{
				if (v.Major == 0 && v.Minor == 0 && v.Build <= 0)
				{
					return v.Revision <= 0;
				}
				return false;
			}
			static bool IsHardDependency(BepInDependency dep)
			{
				return (dep.Flags & BepInDependency.DependencyFlags.HardDependency) != 0;
			}
		}
	}
	public interface ICacheable
	{
		void Save(BinaryWriter bw);

		void Load(BinaryReader br);
	}
	public class CachedAssembly<T> where T : ICacheable
	{
		public List<T> CacheItems { get; set; }

		public long Timestamp { get; set; }
	}
	public static class TypeLoader
	{
		public static readonly DefaultAssemblyResolver Resolver;

		public static readonly ReaderParameters ReaderParameters;

		[CompilerGenerated]
		private static AssemblyResolveEventHandler m_AssemblyResolve;

		private static readonly ConfigEntry<bool> EnableAssemblyCache;

		public static event AssemblyResolveEventHandler AssemblyResolve
		{
			[CompilerGenerated]
			add
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Expected O, but got Unknown
				AssemblyResolveEventHandler val = TypeLoader.m_AssemblyResolve;
				AssemblyResolveEventHandler val2;
				do
				{
					val2 = val;
					AssemblyResolveEventHandler value2 = (AssemblyResolveEventHandler)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref TypeLoader.m_AssemblyResolve, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Expected O, but got Unknown
				AssemblyResolveEventHandler val = TypeLoader.m_AssemblyResolve;
				AssemblyResolveEventHandler val2;
				do
				{
					val2 = val;
					AssemblyResolveEventHandler value2 = (AssemblyResolveEventHandler)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref TypeLoader.m_AssemblyResolve, value2, val2);
				}
				while (val != val2);
			}
		}

		static TypeLoader()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			EnableAssemblyCache = ConfigFile.CoreConfig.Bind("Caching", "EnableAssemblyCache", defaultValue: true, "Enable/disable assembly metadata cache\nEnabling this will speed up discovery of plugins and patchers by caching the metadata of all types BepInEx discovers.");
			Resolver = new DefaultAssemblyResolver();
			ReaderParameters = new ReaderParameters
			{
				AssemblyResolver = (IAssemblyResolver)(object)Resolver
			};
			((BaseAssemblyResolver)Resolver).ResolveFailure += (AssemblyResolveEventHandler)delegate(object sender, AssemblyNameReference reference)
			{
				if (!Utility.TryParseAssemblyName(reference.FullName, out var assemblyName))
				{
					AssemblyResolveEventHandler assemblyResolve = TypeLoader.AssemblyResolve;
					if (assemblyResolve == null)
					{
						return null;
					}
					return assemblyResolve.Invoke(sender, reference);
				}
				foreach (string item in new string[3]
				{
					Paths.BepInExAssemblyDirectory,
					Paths.PluginPath,
					Paths.PatcherPluginPath
				}.Concat(Paths.DllSearchPaths))
				{
					if (Utility.TryResolveDllAssembly(assemblyName, item, ReaderParameters, out var assembly))
					{
						return assembly;
					}
				}
				AssemblyResolveEventHandler assemblyResolve2 = TypeLoader.AssemblyResolve;
				return (assemblyResolve2 == null) ? null : assemblyResolve2.Invoke(sender, reference);
			};
		}

		public static Dictionary<string, List<T>> FindPluginTypes<T>(string directory, Func<TypeDefinition, T> typeSelector, Func<AssemblyDefinition, bool> assemblyFilter = null, string cacheName = null) where T : ICacheable, new()
		{
			Dictionary<string, List<T>> dictionary = new Dictionary<string, List<T>>();
			Dictionary<string, CachedAssembly<T>> dictionary2 = null;
			if (cacheName != null)
			{
				dictionary2 = LoadAssemblyCache<T>(cacheName);
			}
			string[] files = Directory.GetFiles(Path.GetFullPath(directory), "*.dll", SearchOption.AllDirectories);
			foreach (string text in files)
			{
				try
				{
					if (dictionary2 != null && dictionary2.TryGetValue(text, out var value) && File.GetLastWriteTimeUtc(text).Ticks == value.Timestamp)
					{
						dictionary[text] = value.CacheItems;
						continue;
					}
					AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text, ReaderParameters);
					if (assemblyFilter != null && !assemblyFilter(val))
					{
						dictionary[text] = new List<T>();
						val.Dispose();
						continue;
					}
					List<T> value2 = (from t in ((IEnumerable<TypeDefinition>)val.MainModule.Types).Select(typeSelector)
						where t != null
						select t).ToList();
					dictionary[text] = value2;
					val.Dispose();
				}
				catch (BadImageFormatException ex)
				{
					Logger.LogDebug("Skipping loading " + text + " because it's not a valid .NET assembly. Full error: " + ex.Message);
				}
				catch (Exception ex2)
				{
					Logger.LogError(ex2.ToString());
				}
			}
			if (cacheName != null)
			{
				SaveAssemblyCache(cacheName, dictionary);
			}
			return dictionary;
		}

		public static Dictionary<string, CachedAssembly<T>> LoadAssemblyCache<T>(string cacheName) where T : ICacheable, new()
		{
			if (!EnableAssemblyCache.Value)
			{
				return null;
			}
			Dictionary<string, CachedAssembly<T>> dictionary = new Dictionary<string, CachedAssembly<T>>();
			try
			{
				string path = Path.Combine(Paths.CachePath, cacheName + "_typeloader.dat");
				if (!File.Exists(path))
				{
					return null;
				}
				using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path));
				int num = binaryReader.ReadInt32();
				for (int i = 0; i < num; i++)
				{
					string key = binaryReader.ReadString();
					long timestamp = binaryReader.ReadInt64();
					int num2 = binaryReader.ReadInt32();
					List<T> list = new List<T>();
					for (int j = 0; j < num2; j++)
					{
						T item = new T();
						item.Load(binaryReader);
						list.Add(item);
					}
					dictionary[key] = new CachedAssembly<T>
					{
						Timestamp = timestamp,
						CacheItems = list
					};
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning("Failed to load cache \"" + cacheName + "\"; skipping loading cache. Reason: " + ex.Message + ".");
			}
			return dictionary;
		}

		public static void SaveAssemblyCache<T>(string cacheName, Dictionary<string, List<T>> entries) where T : ICacheable
		{
			if (!EnableAssemblyCache.Value)
			{
				return;
			}
			try
			{
				if (!Directory.Exists(Paths.CachePath))
				{
					Directory.CreateDirectory(Paths.CachePath);
				}
				using BinaryWriter binaryWriter = new BinaryWriter(File.OpenWrite(Path.Combine(Paths.CachePath, cacheName + "_typeloader.dat")));
				binaryWriter.Write(entries.Count);
				foreach (KeyValuePair<string, List<T>> entry in entries)
				{
					binaryWriter.Write(entry.Key);
					binaryWriter.Write(File.GetLastWriteTimeUtc(entry.Key).Ticks);
					binaryWriter.Write(entry.Value.Count);
					foreach (T item in entry.Value)
					{
						item.Save(binaryWriter);
					}
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning("Failed to save cache \"" + cacheName + "\"; skipping saving cache. Reason: " + ex.Message + ".");
			}
		}

		public static string TypeLoadExceptionToString(ReflectionTypeLoadException ex)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Exception[] loaderExceptions = ex.LoaderExceptions;
			foreach (Exception ex2 in loaderExceptions)
			{
				stringBuilder.AppendLine(ex2.Message);
				if (ex2 is FileNotFoundException ex3)
				{
					if (!string.IsNullOrEmpty(ex3.FusionLog))
					{
						stringBuilder.AppendLine("Fusion Log:");
						stringBuilder.AppendLine(ex3.FusionLog);
					}
				}
				else if (ex2 is FileLoadException ex4 && !string.IsNullOrEmpty(ex4.FusionLog))
				{
					stringBuilder.AppendLine("Fusion Log:");
					stringBuilder.AppendLine(ex4.FusionLog);
				}
				stringBuilder.AppendLine();
			}
			return stringBuilder.ToString();
		}
	}
}
namespace BepInEx.ConsoleUtil
{
	internal class Kon
	{
		private struct CONSOLE_SCREEN_BUFFER_INFO
		{
			internal COORD dwSize;

			internal COORD dwCursorPosition;

			internal short wAttributes;

			internal SMALL_RECT srWindow;

			internal COORD dwMaximumWindowSize;
		}

		private struct COORD
		{
			internal short X;

			internal short Y;
		}

		private struct SMALL_RECT
		{
			internal short Left;

			internal short Top;

			internal short Right;

			internal short Bottom;
		}

		private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);

		internal static IntPtr conOut = IntPtr.Zero;

		public static ConsoleColor ForegroundColor
		{
			get
			{
				return GetConsoleColor(isBackground: false);
			}
			set
			{
				SetConsoleColor(isBackground: false, value);
			}
		}

		public static ConsoleColor BackgroundColor
		{
			get
			{
				return GetConsoleColor(isBackground: true);
			}
			set
			{
				SetConsoleColor(isBackground: true, value);
			}
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, short attributes);

		[DllImport("kernel32.dll", SetLastError = true)]
		private static extern IntPtr GetStdHandle(int nStdHandle);

		private static short ConsoleColorToColorAttribute(short color, bool isBackground)
		{
			if (((uint)color & 0xFFFFFFF0u) != 0)
			{
				throw new ArgumentException("Arg_InvalidConsoleColor");
			}
			if (isBackground)
			{
				color <<= 4;
			}
			return color;
		}

		private static CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(bool throwOnNoConsole, out bool succeeded)
		{
			succeeded = false;
			if (!(conOut == INVALID_HANDLE_VALUE))
			{
				if (!GetConsoleScreenBufferInfo(conOut, out var lpConsoleScreenBufferInfo))
				{
					bool consoleScreenBufferInfo = GetConsoleScreenBufferInfo(GetStdHandle(-12), out lpConsoleScreenBufferInfo);
					if (!consoleScreenBufferInfo)
					{
						consoleScreenBufferInfo = GetConsoleScreenBufferInfo(GetStdHandle(-10), out lpConsoleScreenBufferInfo);
					}
					if (!consoleScreenBufferInfo && Marshal.GetLastWin32Error() == 6 && !throwOnNoConsole)
					{
						return default(CONSOLE_SCREEN_BUFFER_INFO);
					}
				}
				succeeded = true;
				return lpConsoleScreenBufferInfo;
			}
			if (!throwOnNoConsole)
			{
				return default(CONSOLE_SCREEN_BUFFER_INFO);
			}
			throw new Exception("IO.IO_NoConsole");
		}

		private static void SetConsoleColor(bool isBackground, ConsoleColor c)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			((CodeAccessPermission)new UIPermission((UIPermissionWindow)2)).Demand();
			short num = ConsoleColorToColorAttribute((short)c, isBackground);
			bool succeeded;
			CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole: false, out succeeded);
			if (succeeded)
			{
				short wAttributes = bufferInfo.wAttributes;
				wAttributes &= (short)(isBackground ? (-241) : (-16));
				wAttributes = (short)((ushort)wAttributes | (ushort)num);
				SetConsoleTextAttribute(conOut, wAttributes);
			}
		}

		private static ConsoleColor GetConsoleColor(bool isBackground)
		{
			bool succeeded;
			CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole: false, out succeeded);
			if (!succeeded)
			{
				if (!isBackground)
				{
					return ConsoleColor.Gray;
				}
				return ConsoleColor.Black;
			}
			return ColorAttributeToConsoleCo

FrozenDevv-ModPack-1.1.0/BepInEx/core/BepInEx.Harmony.dll

Decompiled 7 months ago
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("BepInEx.Harmony")]
[assembly: AssemblyDescription("Harmony wrapper for BepInEx")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BepInEx.Harmony")]
[assembly: AssemblyCopyright("Copyright © Bepis 2019")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("54161cfe-ff42-4dde-b161-3a49545db5cd")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyVersion("2.0.0.0")]
namespace BepInEx.Harmony;

[AttributeUsage(AttributeTargets.Method)]
[Obsolete("Use HarmonyLib.ParameterByRefAttribute directly", true)]
public class ParameterByRefAttribute : ParameterByRefAttribute
{
	public int[] ParameterIndices => ((ParameterByRefAttribute)this).ParameterIndices;

	public ParameterByRefAttribute(params int[] parameterIndices)
		: base(parameterIndices)
	{
	}
}
public static class HarmonyExtensions
{
	[Obsolete("Use HarmonyLib.Harmony.PatchAll directly", true)]
	public static void PatchAll(this Harmony harmonyInstance, Type type)
	{
		HarmonyWrapper.PatchAll(type, harmonyInstance);
	}
}
public class HarmonyWrapper
{
	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll or HarmonyLib.Harmony.PatchAll", true)]
	public static Harmony PatchAll(Type type, Harmony harmonyInstance = null)
	{
		if (harmonyInstance == null)
		{
			return Harmony.CreateAndPatchAll(type, (string)null);
		}
		harmonyInstance.PatchAll(type);
		return harmonyInstance;
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll", true)]
	public static Harmony PatchAll(Type type, string harmonyInstanceId)
	{
		return Harmony.CreateAndPatchAll(type, harmonyInstanceId);
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll or HarmonyLib.Harmony.PatchAll", true)]
	public static Harmony PatchAll(Assembly assembly, Harmony harmonyInstance = null)
	{
		return assembly.GetTypes().Aggregate(harmonyInstance, (Harmony current, Type type) => PatchAll(type, current));
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll", true)]
	public static Harmony PatchAll(Assembly assembly, string harmonyInstanceId)
	{
		return Harmony.CreateAndPatchAll(assembly, harmonyInstanceId);
	}

	[Obsolete("Use HarmonyLib.Harmony.PatchAll with no arguments", true)]
	public static Harmony PatchAll(Harmony harmonyInstance = null)
	{
		return PatchAll(Assembly.GetCallingAssembly(), harmonyInstance);
	}

	[Obsolete("Use HarmonyLib.Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), ...)", true)]
	public static Harmony PatchAll(string harmonyInstanceId)
	{
		return PatchAll(Assembly.GetCallingAssembly(), harmonyInstanceId);
	}

	[Obsolete("Use HarmonyLib.Transpilers.EmitDelegate instead", true)]
	public static CodeInstruction EmitDelegate<T>(T action) where T : Delegate
	{
		return Transpilers.EmitDelegate<T>(action);
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/core/BepInEx.Preloader.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Preloader.Patching;
using BepInEx.Preloader.RuntimeFixes;
using HarmonyLib;
using HarmonyXInterop;
using Mono.Cecil;
using Mono.Cecil.Cil;
using MonoMod.RuntimeDetour;
using MonoMod.RuntimeDetour.Platforms;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("BepInEx.Preloader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BepInEx.Preloader")]
[assembly: AssemblyCopyright("Copyright ©  2019")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("f7abbe07-c02f-4f7c-bf6e-c6656bf588ca")]
[assembly: AssemblyFileVersion("5.4.21.0")]
[assembly: AssemblyVersion("5.4.21.0")]
namespace BepInEx.Preloader
{
	public static class EnvVars
	{
		public static string DOORSTOP_INVOKE_DLL_PATH { get; private set; }

		public static string DOORSTOP_MANAGED_FOLDER_DIR { get; private set; }

		public static string DOORSTOP_PROCESS_PATH { get; private set; }

		public static string[] DOORSTOP_DLL_SEARCH_DIRS { get; private set; }

		internal static void LoadVars()
		{
			DOORSTOP_INVOKE_DLL_PATH = Environment.GetEnvironmentVariable("DOORSTOP_INVOKE_DLL_PATH");
			DOORSTOP_MANAGED_FOLDER_DIR = Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR");
			DOORSTOP_PROCESS_PATH = Environment.GetEnvironmentVariable("DOORSTOP_PROCESS_PATH");
			DOORSTOP_DLL_SEARCH_DIRS = Environment.GetEnvironmentVariable("DOORSTOP_DLL_SEARCH_DIRS")?.Split(new char[1] { Path.PathSeparator }) ?? new string[0];
		}
	}
	internal static class PreloaderRunner
	{
		private static readonly string[] CriticalAssemblies = new string[7] { "Mono.Cecil.dll", "Mono.Cecil.Mdb.dll", "Mono.Cecil.Pdb.dll", "Mono.Cecil.Rocks.dll", "MonoMod.Utils.dll", "MonoMod.RuntimeDetour.dll", "0Harmony.dll" };

		private static void LoadCriticalAssemblies()
		{
			string[] criticalAssemblies = CriticalAssemblies;
			foreach (string path in criticalAssemblies)
			{
				try
				{
					Assembly.LoadFile(Path.Combine(Paths.BepInExAssemblyDirectory, path));
				}
				catch (Exception)
				{
				}
			}
		}

		public static void PreloaderPreMain()
		{
			PlatformUtils.SetPlatform();
			string text = Utility.ParentDirectory(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH), 2);
			Paths.SetExecutablePath(EnvVars.DOORSTOP_PROCESS_PATH, text, EnvVars.DOORSTOP_MANAGED_FOLDER_DIR, EnvVars.DOORSTOP_DLL_SEARCH_DIRS);
			LoadCriticalAssemblies();
			AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
			AppDomain.CurrentDomain.AssemblyResolve -= Entrypoint.ResolveCurrentDirectory;
			PreloaderMain();
		}

		private static void PreloaderMain()
		{
			if (Preloader.ConfigApplyRuntimePatches.Value)
			{
				XTermFix.Apply();
				ConsoleSetOutFix.Apply();
			}
			Preloader.Run();
		}

		private static Assembly LocalResolve(object sender, ResolveEventArgs args)
		{
			AssemblyName assemblyName = default(AssemblyName);
			if (!Utility.TryParseAssemblyName(args.Name, ref assemblyName))
			{
				return null;
			}
			AssemblyName assemblyName2 = default(AssemblyName);
			var source = (from a in AppDomain.CurrentDomain.GetAssemblies()
				select new
				{
					assembly = a,
					name = (Utility.TryParseAssemblyName(a.FullName, ref assemblyName2) ? assemblyName2 : null)
				} into a
				where a.name != null && a.name.Name == assemblyName.Name
				orderby a.name.Version descending
				select a).ToList();
			Assembly assembly = (source.FirstOrDefault(a => a.name.Version == assemblyName.Version) ?? source.FirstOrDefault())?.assembly;
			if ((object)assembly != null)
			{
				return assembly;
			}
			if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, ref assembly) || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, ref assembly) || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, ref assembly))
			{
				return assembly;
			}
			return null;
		}
	}
	internal static class Entrypoint
	{
		private static string preloaderPath;

		public static void Main()
		{
			string text = $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log";
			try
			{
				EnvVars.LoadVars();
				text = Path.Combine(Path.GetDirectoryName(EnvVars.DOORSTOP_PROCESS_PATH) ?? ".", text);
				preloaderPath = Path.GetDirectoryName(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH));
				AppDomain.CurrentDomain.AssemblyResolve += ResolveCurrentDirectory;
				typeof(Entrypoint).Assembly.GetType("BepInEx.Preloader.PreloaderRunner")?.GetMethod("PreloaderPreMain")?.Invoke(null, null);
			}
			catch (Exception ex)
			{
				File.WriteAllText(text, ex.ToString());
			}
			finally
			{
				AppDomain.CurrentDomain.AssemblyResolve -= ResolveCurrentDirectory;
			}
		}

		internal static Assembly ResolveCurrentDirectory(object sender, ResolveEventArgs args)
		{
			AssemblyName assemblyName = new AssemblyName(args.Name);
			try
			{
				return Assembly.LoadFile(Path.Combine(preloaderPath, assemblyName.Name + ".dll"));
			}
			catch (Exception)
			{
				return null;
			}
		}
	}
	internal static class PlatformUtils
	{
		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct utsname_osx
		{
			private const int osx_utslen = 256;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string sysname;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string nodename;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string release;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string version;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string machine;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct utsname_linux
		{
			private const int linux_utslen = 65;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string sysname;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string nodename;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string release;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string version;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string machine;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)]
			public string domainname;
		}

		[DllImport("libc.so.6", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "uname")]
		private static extern IntPtr uname_linux(ref utsname_linux utsname);

		[DllImport("/usr/lib/libSystem.dylib", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "uname")]
		private static extern IntPtr uname_osx(ref utsname_osx utsname);

		public static void SetPlatform()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: 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)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			Platform val = (Platform)17;
			PropertyInfo property = typeof(Environment).GetProperty("Platform", BindingFlags.Static | BindingFlags.NonPublic);
			string text = (((object)property == null) ? Environment.OSVersion.Platform.ToString() : property.GetValue(null, new object[0]).ToString());
			text = text.ToLowerInvariant();
			if (text.Contains("win"))
			{
				val = (Platform)37;
			}
			else if (text.Contains("mac") || text.Contains("osx"))
			{
				val = (Platform)73;
			}
			else if (text.Contains("lin") || text.Contains("unix"))
			{
				val = (Platform)137;
			}
			if (Is(val, (Platform)137) && Directory.Exists("/data") && File.Exists("/system/build.prop"))
			{
				val = (Platform)393;
			}
			else if (Is(val, (Platform)8) && Directory.Exists("/System/Library/AccessibilityBundles"))
			{
				val = (Platform)585;
			}
			MethodInfo methodInfo = typeof(Environment).GetProperty("Is64BitOperatingSystem")?.GetGetMethod();
			val = (Platform)(((object)methodInfo == null) ? (val | ((IntPtr.Size >= 8) ? 2 : 0)) : (val | (((bool)methodInfo.Invoke(null, new object[0])) ? 2 : 0)));
			if ((Is(val, (Platform)73) || Is(val, (Platform)137)) && (object)Type.GetType("Mono.Runtime") != null)
			{
				IntPtr intPtr;
				string machine;
				if (Is(val, (Platform)73))
				{
					utsname_osx utsname = default(utsname_osx);
					intPtr = uname_osx(ref utsname);
					machine = utsname.machine;
				}
				else
				{
					utsname_linux utsname2 = default(utsname_linux);
					intPtr = uname_linux(ref utsname2);
					machine = utsname2.machine;
				}
				if (intPtr == IntPtr.Zero && (machine.StartsWith("aarch") || machine.StartsWith("arm")))
				{
					val = (Platform)(val | 0x10000);
				}
			}
			else
			{
				typeof(object).Module.GetPEKind(out var _, out var machine2);
				if (machine2 == ImageFileMachine.ARM)
				{
					val = (Platform)(val | 0x10000);
				}
			}
			PlatformHelper.Current = val;
		}

		private static bool Is(Platform current, Platform expected)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return (Platform)(current & expected) == expected;
		}
	}
	internal static class Preloader
	{
		private enum MonoModBackend
		{
			[Description("Auto")]
			auto,
			[Description("DynamicMethod")]
			dynamicmethod,
			[Description("MethodBuilder")]
			methodbuilder,
			[Description("Cecil")]
			cecil
		}

		private static readonly ConfigEntry<string> ConfigEntrypointAssembly = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Assembly", IsPostUnity2017 ? "UnityEngine.CoreModule.dll" : "UnityEngine.dll", "The local filename of the assembly to target.");

		private static readonly ConfigEntry<string> ConfigEntrypointType = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Type", "Application", "The name of the type in the entrypoint assembly to search for the entrypoint method.");

		private static readonly ConfigEntry<string> ConfigEntrypointMethod = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Method", ".cctor", "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from.");

		internal static readonly ConfigEntry<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Bind<bool>("Preloader", "ApplyRuntimePatches", true, "Enables or disables runtime patches.\nThis should always be true, unless you cannot start the game due to a Harmony related issue (such as running .NET Standard runtime) or you know what you're doing.");

		private static readonly ConfigEntry<MonoModBackend> HarmonyBackend = ConfigFile.CoreConfig.Bind<MonoModBackend>("Preloader", "HarmonyBackend", MonoModBackend.auto, "Specifies which MonoMod backend to use for Harmony patches. Auto uses the best available backend.\nThis setting should only be used for development purposes (e.g. debugging in dnSpy). Other code might override this setting.");

		private static PreloaderConsoleListener PreloaderLog { get; set; }

		public static bool IsPostUnity2017 { get; } = File.Exists(Path.Combine(Paths.ManagedPath, "UnityEngine.CoreModule.dll"));


		public static void Run()
		{
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				InitializeHarmony();
				HarmonyInteropFix.Apply();
				ConsoleManager.Initialize(false);
				AllocateConsole();
				Exception ex = default(Exception);
				Utility.TryDo((Action)delegate
				{
					if (ConfigApplyRuntimePatches.Value)
					{
						UnityPatches.Apply();
					}
				}, ref ex);
				Logger.InitializeInternalLoggers();
				Logger.Sources.Add(TraceLogSource.CreateSource());
				PreloaderLog = new PreloaderConsoleListener();
				Logger.Listeners.Add((ILogListener)(object)PreloaderLog);
				Version version = typeof(Paths).Assembly.GetName().Version;
				string text = $"BepInEx {version} - {Paths.ProcessName}";
				if (ConsoleManager.ConsoleActive)
				{
					ConsoleManager.SetConsoleTitle(text);
				}
				Logger.LogMessage((object)$"{text} ({File.GetLastWriteTime(Paths.ExecutablePath)})");
				object[] customAttributes = typeof(BuildInfoAttribute).Assembly.GetCustomAttributes(typeof(BuildInfoAttribute), inherit: false);
				if (customAttributes.Length != 0)
				{
					Logger.LogMessage((object)((BuildInfoAttribute)customAttributes[0]).Info);
				}
				Logger.LogInfo((object)("Running under Unity v" + GetUnityVersion()));
				Logger.LogInfo((object)$"CLR runtime version: {Environment.Version}");
				Logger.LogInfo((object)$"Supports SRE: {Utility.CLRSupportsDynamicAssemblies}");
				Logger.LogInfo((object)$"System platform: {PlatformHelper.Current}");
				if (ex != null)
				{
					Logger.LogWarning((object)("Failed to apply runtime patches for Mono. See more info in the output log. Error message: " + ex.Message));
				}
				Logger.LogMessage((object)"Preloader started");
				AssemblyPatcher.AddPatcher(new PatcherPlugin
				{
					TargetDLLs = () => new string[1] { ConfigEntrypointAssembly.Value },
					Patcher = PatchEntrypoint,
					TypeName = "BepInEx.Chainloader"
				});
				Logger.Log((LogLevel)16, (object)$"Loaded 1 patcher method from [BepInEx.Preloader {version}]");
				AssemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath);
				Logger.LogInfo((object)string.Format("{0} patcher plugin{1} loaded", AssemblyPatcher.PatcherPlugins.Count, (AssemblyPatcher.PatcherPlugins.Count == 1) ? "" : "s"));
				AssemblyPatcher.PatchAndLoad(Paths.DllSearchPaths);
				AssemblyPatcher.DisposePatchers();
				Logger.LogMessage((object)"Preloader finished");
				Logger.Listeners.Remove((ILogListener)(object)PreloaderLog);
				PreloaderLog.Dispose();
			}
			catch (Exception ex2)
			{
				try
				{
					Logger.LogFatal((object)"Could not run preloader!");
					Logger.LogFatal((object)ex2);
					if (!ConsoleManager.ConsoleActive)
					{
						AllocateConsole();
						Console.Write(PreloaderLog);
					}
				}
				catch
				{
				}
				string text2 = string.Empty;
				try
				{
					text2 = string.Join("\r\n", PreloaderConsoleListener.LogEvents.Select((LogEventArgs x) => ((object)x).ToString()).ToArray());
					text2 += "\r\n";
					PreloaderLog?.Dispose();
					PreloaderLog = null;
				}
				catch
				{
				}
				File.WriteAllText(Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"), text2 + ex2);
			}
		}

		public static void PatchEntrypoint(ref AssemblyDefinition assembly)
		{
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0309: Unknown result type (might be due to invalid IL or missing references)
			if (((IEnumerable<AssemblyNameReference>)assembly.MainModule.AssemblyReferences).Any((AssemblyNameReference x) => x.Name.Contains("BepInEx")))
			{
				throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!");
			}
			string entrypointType = ConfigEntrypointType.Value;
			string entrypointMethod = ConfigEntrypointMethod.Value;
			bool flag = Utility.IsNullOrWhiteSpace(entrypointMethod) || entrypointMethod == ".cctor";
			TypeDefinition val = ((IEnumerable<TypeDefinition>)assembly.MainModule.Types).FirstOrDefault((Func<TypeDefinition, bool>)((TypeDefinition x) => ((MemberReference)x).Name == entrypointType));
			if (val == null)
			{
				throw new Exception("The entrypoint type is invalid! Please check your config/BepInEx.cfg file");
			}
			AssemblyDefinition val2 = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath);
			try
			{
				MethodDefinition val3 = ((IEnumerable<MethodDefinition>)((IEnumerable<TypeDefinition>)val2.MainModule.Types).First((TypeDefinition x) => ((MemberReference)x).Name == "Chainloader").Methods).First((MethodDefinition x) => ((MemberReference)x).Name == "Initialize");
				MethodDefinition val4 = ((IEnumerable<MethodDefinition>)((IEnumerable<TypeDefinition>)val2.MainModule.Types).First((TypeDefinition x) => ((MemberReference)x).Name == "Chainloader").Methods).First((MethodDefinition x) => ((MemberReference)x).Name == "Start");
				MethodReference val5 = assembly.MainModule.ImportReference((MethodReference)(object)val3);
				MethodReference val6 = assembly.MainModule.ImportReference((MethodReference)(object)val4);
				List<MethodDefinition> list = new List<MethodDefinition>();
				if (flag)
				{
					MethodDefinition val7 = ((IEnumerable<MethodDefinition>)val.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => m.IsConstructor && m.IsStatic));
					if (val7 == null)
					{
						val7 = new MethodDefinition(".cctor", (MethodAttributes)6289, assembly.MainModule.ImportReference(typeof(void)));
						val.Methods.Add(val7);
						ILProcessor iLProcessor = val7.Body.GetILProcessor();
						iLProcessor.Append(iLProcessor.Create(OpCodes.Ret));
					}
					list.Add(val7);
				}
				else
				{
					list.AddRange(((IEnumerable<MethodDefinition>)val.Methods).Where((MethodDefinition x) => ((MemberReference)x).Name == entrypointMethod));
				}
				if (!list.Any())
				{
					throw new Exception("The entrypoint method is invalid! Please check your config.ini");
				}
				foreach (MethodDefinition item in list)
				{
					ILProcessor iLProcessor2 = item.Body.GetILProcessor();
					Instruction val8 = ((IEnumerable<Instruction>)iLProcessor2.Body.Instructions).First();
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Ldnull));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Ldc_I4_0));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, assembly.MainModule.ImportReference((MethodBase)AccessTools.PropertyGetter(typeof(PreloaderConsoleListener), "LogEvents"))));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, val5));
					iLProcessor2.InsertBefore(val8, iLProcessor2.Create(OpCodes.Call, val6));
				}
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}

		public static void AllocateConsole()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (!ConsoleManager.ConsoleEnabled)
			{
				return;
			}
			try
			{
				ConsoleManager.CreateConsole();
				Logger.Listeners.Add((ILogListener)new ConsoleLogListener());
			}
			catch (Exception ex)
			{
				Logger.LogError((object)"Failed to allocate console!");
				Logger.LogError((object)ex);
			}
		}

		public static string GetUnityVersion()
		{
			if (PlatformHelper.Is((Platform)37))
			{
				return FileVersionInfo.GetVersionInfo(Paths.ExecutablePath).FileVersion;
			}
			return "Unknown (" + (IsPostUnity2017 ? "post" : "pre") + "-2017)";
		}

		private static void InitializeHarmony()
		{
			switch (HarmonyBackend.Value)
			{
			case MonoModBackend.dynamicmethod:
			case MonoModBackend.methodbuilder:
			case MonoModBackend.cecil:
				Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", HarmonyBackend.Value.ToString());
				break;
			default:
				throw new ArgumentOutOfRangeException("HarmonyBackend", HarmonyBackend.Value, "Unknown backend");
			case MonoModBackend.auto:
				break;
			}
		}
	}
	public class PreloaderConsoleListener : ILogListener, IDisposable
	{
		private static readonly ConfigEntry<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind<LogLevel>("Logging.Console", "LogLevels", (LogLevel)31, "Which log levels to show in the console output.");

		public static List<LogEventArgs> LogEvents { get; } = new List<LogEventArgs>();


		public void LogEvent(object sender, LogEventArgs eventArgs)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			if ((eventArgs.Level & ConfigConsoleDisplayedLevel.Value) != 0)
			{
				LogEvents.Add(eventArgs);
			}
		}

		public void Dispose()
		{
		}
	}
}
namespace BepInEx.Preloader.RuntimeFixes
{
	internal static class ConsoleSetOutFix
	{
		private static LoggedTextWriter loggedTextWriter;

		internal static ManualLogSource ConsoleLogSource = Logger.CreateLogSource("Console");

		public static void Apply()
		{
			loggedTextWriter = new LoggedTextWriter
			{
				Parent = Console.Out
			};
			Console.SetOut(loggedTextWriter);
			Harmony.CreateAndPatchAll(typeof(ConsoleSetOutFix), (string)null);
		}

		[HarmonyPatch(typeof(Console), "SetOut")]
		[HarmonyPrefix]
		private static bool OnSetOut(TextWriter newOut)
		{
			loggedTextWriter.Parent = newOut;
			return false;
		}
	}
	internal class LoggedTextWriter : TextWriter
	{
		public override Encoding Encoding { get; } = Encoding.UTF8;


		public TextWriter Parent { get; set; }

		public override void Flush()
		{
			Parent.Flush();
		}

		public override void Write(string value)
		{
			ConsoleSetOutFix.ConsoleLogSource.LogInfo((object)value);
			Parent.Write(value);
		}

		public override void WriteLine(string value)
		{
			ConsoleSetOutFix.ConsoleLogSource.LogInfo((object)value);
			Parent.WriteLine(value);
		}
	}
	internal static class HarmonyInteropFix
	{
		public static void Apply()
		{
			HarmonyInterop.Initialize(Paths.CachePath);
			Harmony.CreateAndPatchAll(typeof(HarmonyInteropFix), "org.bepinex.fixes.harmonyinterop");
		}

		[HarmonyReversePatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPatch(typeof(Assembly), "LoadFile", new Type[] { typeof(string) })]
		private static Assembly LoadFile(string path)
		{
			return null;
		}

		[HarmonyPatch(typeof(Assembly), "LoadFile", new Type[] { typeof(string) })]
		[HarmonyPatch(typeof(Assembly), "LoadFrom", new Type[] { typeof(string) })]
		[HarmonyPrefix]
		private static bool OnAssemblyLoad(ref Assembly __result, string __0)
		{
			HarmonyInterop.TryShim(__0, Paths.GameRootPath, (Action<string>)Logger.LogWarning, TypeLoader.ReaderParameters);
			__result = LoadFile(__0);
			return true;
		}
	}
	internal static class TraceFix
	{
		private static Type TraceImplType;

		private static object ListenersSyncRoot;

		private static TraceListenerCollection Listeners;

		private static PropertyInfo prop_AutoFlush;

		private static bool AutoFlush => (bool)prop_AutoFlush.GetValue(null, null);

		public static void ApplyFix()
		{
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			TraceImplType = AppDomain.CurrentDomain.GetAssemblies().First((Assembly x) => x.GetName().Name == "System").GetTypes()
				.FirstOrDefault((Type x) => x.Name == "TraceImpl");
			if ((object)TraceImplType != null)
			{
				ListenersSyncRoot = AccessTools.Property(TraceImplType, "ListenersSyncRoot").GetValue(null, null);
				Listeners = (TraceListenerCollection)AccessTools.Property(TraceImplType, "Listeners").GetValue(null, null);
				prop_AutoFlush = AccessTools.Property(TraceImplType, "AutoFlush");
				new Harmony("com.bepis.bepinex.tracefix").Patch((MethodBase)typeof(Trace).GetMethod("DoTrace", BindingFlags.Static | BindingFlags.NonPublic), new HarmonyMethod(typeof(TraceFix).GetMethod("DoTraceReplacement", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool DoTraceReplacement(string kind, Assembly report, string message)
		{
			string source = string.Empty;
			try
			{
				source = report.GetName().Name;
			}
			catch (MethodAccessException)
			{
			}
			TraceEventType eventType = (TraceEventType)Enum.Parse(typeof(TraceEventType), kind);
			lock (ListenersSyncRoot)
			{
				foreach (TraceListener listener in Listeners)
				{
					listener.TraceEvent(new TraceEventCache(), source, eventType, 0, message);
					if (AutoFlush)
					{
						listener.Flush();
					}
				}
			}
			return false;
		}
	}
	internal static class UnityPatches
	{
		private static Harmony HarmonyInstance { get; set; }

		public static Dictionary<string, string> AssemblyLocations { get; } = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);


		public static void Apply()
		{
			HarmonyInstance = Harmony.CreateAndPatchAll(typeof(UnityPatches), (string)null);
			try
			{
				TraceFix.ApplyFix();
			}
			catch
			{
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		public static void GetLocation(ref string __result, Assembly __instance)
		{
			if (AssemblyLocations.TryGetValue(__instance.FullName, out var value))
			{
				__result = value;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		public static void GetCodeBase(ref string __result, Assembly __instance)
		{
			if (AssemblyLocations.TryGetValue(__instance.FullName, out var value))
			{
				__result = "file://" + value.Replace('\\', '/');
			}
		}
	}
	internal static class XTermFix
	{
		public static int intOffset;

		public static void Apply()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Expected O, but got Unknown
			if (!PlatformHelper.Is((Platform)37) && (object)typeof(Console).Assembly.GetType("System.ConsoleDriver") != null && (object)AccessTools.Method("System.TermInfoReader:DetermineVersion", (Type[])null, (Type[])null) == null)
			{
				DetourHelper.Native = (IDetourNativePlatform)new DetourNativeX86Platform();
				Harmony val = new Harmony("com.bepinex.xtermfix");
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:ReadHeader", (Type[])null, (Type[])null), new HarmonyMethod(typeof(XTermFix), "ReadHeaderPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:Get", new Type[1] { AccessTools.TypeByName("System.TermInfoNumbers") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoNumbersTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:Get", new Type[1] { AccessTools.TypeByName("System.TermInfoStrings") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoStringsTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:GetStringBytes", new Type[1] { AccessTools.TypeByName("System.TermInfoStrings") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoStringsTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				DetourHelper.Native = null;
			}
		}

		public static int GetInt32(byte[] buffer, int offset)
		{
			byte num = buffer[offset];
			int num2 = buffer[offset + 1];
			int num3 = buffer[offset + 2];
			int num4 = buffer[offset + 3];
			return num | (num2 << 8) | (num3 << 16) | (num4 << 24);
		}

		public static short GetInt16(byte[] buffer, int offset)
		{
			byte num = buffer[offset];
			int num2 = buffer[offset + 1];
			return (short)(num | (num2 << 8));
		}

		public static int GetInteger(byte[] buffer, int offset)
		{
			if (intOffset != 2)
			{
				return GetInt32(buffer, offset);
			}
			return GetInt16(buffer, offset);
		}

		public static void DetermineVersion(short magic)
		{
			switch (magic)
			{
			case 282:
				intOffset = 2;
				break;
			case 542:
				intOffset = 4;
				break;
			default:
				throw new Exception($"Unknown xterm header format: {magic}");
			}
		}

		public static bool ReadHeaderPrefix(byte[] buffer, ref int position, ref short ___boolSize, ref short ___numSize, ref short ___strOffsets)
		{
			short @int = GetInt16(buffer, position);
			position += 2;
			DetermineVersion(@int);
			position += 2;
			___boolSize = GetInt16(buffer, position);
			position += 2;
			___numSize = GetInt16(buffer, position);
			position += 2;
			___strOffsets = GetInt16(buffer, position);
			position += 2;
			position += 2;
			return false;
		}

		public static IEnumerable<CodeInstruction> GetTermInfoNumbersTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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 = instructions.ToList();
			list[31] = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(XTermFix), "intOffset"));
			list[36] = new CodeInstruction(OpCodes.Nop, (object)null);
			list[39] = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(XTermFix), "GetInteger", (Type[])null, (Type[])null));
			return list;
		}

		public static IEnumerable<CodeInstruction> GetTermInfoStringsTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			List<CodeInstruction> list = instructions.ToList();
			list[32] = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(XTermFix), "intOffset"));
			return list;
		}
	}
}
namespace BepInEx.Preloader.Patching
{
	public delegate void AssemblyPatcherDelegate(ref AssemblyDefinition assembly);
	public static class AssemblyPatcher
	{
		private const BindingFlags ALL = BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private static readonly string DumpedAssembliesPath = Utility.CombinePaths(new string[3]
		{
			Paths.BepInExRootPath,
			"DumpedAssemblies",
			Paths.ProcessName
		});

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

		private static readonly ConfigEntry<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "DumpAssemblies", false, "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers.");

		private static readonly ConfigEntry<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "LoadDumpedAssemblies", false, "If enabled, BepInEx will load patched assemblies from BepInEx/DumpedAssemblies instead of memory.\nThis can be used to be able to load patched assemblies into debuggers like dnSpy.\nIf set to true, will override DumpAssemblies.");

		private static readonly ConfigEntry<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "BreakBeforeLoadAssemblies", false, "If enabled, BepInEx will call Debugger.Break() once before loading patched assemblies.\nThis can be used with debuggers like dnSpy to install breakpoints into patched assemblies before they are loaded.");

		public static List<PatcherPlugin> PatcherPlugins { get; } = new List<PatcherPlugin>();


		private static IEnumerable<PatcherPlugin> PatcherPluginsSafe => PatcherPlugins.ToList();

		public static void AddPatcher(PatcherPlugin patcher)
		{
			PatcherPlugins.Add(patcher);
		}

		private static T CreateDelegate<T>(MethodInfo method) where T : class
		{
			if ((object)method == null)
			{
				return null;
			}
			return Delegate.CreateDelegate(typeof(T), method) as T;
		}

		private static PatcherPlugin ToPatcherPlugin(TypeDefinition type)
		{
			if (type.IsInterface || (type.IsAbstract && !type.IsSealed))
			{
				return null;
			}
			MethodDefinition val = ((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name.Equals("get_TargetDLLs", StringComparison.InvariantCultureIgnoreCase) && m.IsPublic && m.IsStatic));
			if (val == null || ((MemberReference)((MethodReference)val).ReturnType).FullName != "System.Collections.Generic.IEnumerable`1<System.String>")
			{
				return null;
			}
			if (((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name.Equals("Patch") && m.IsPublic && m.IsStatic && ((MemberReference)((MethodReference)m).ReturnType).FullName == "System.Void" && ((MethodReference)m).Parameters.Count == 1 && (((MemberReference)((ParameterReference)((MethodReference)m).Parameters[0]).ParameterType).FullName == "Mono.Cecil.AssemblyDefinition&" || ((MemberReference)((ParameterReference)((MethodReference)m).Parameters[0]).ParameterType).FullName == "Mono.Cecil.AssemblyDefinition"))) == null)
			{
				return null;
			}
			return new PatcherPlugin
			{
				TypeName = ((MemberReference)type).FullName
			};
		}

		public static void AddPatchersFromDirectory(string directory)
		{
			if (!Directory.Exists(directory))
			{
				return;
			}
			SortedDictionary<string, PatcherPlugin> sortedDictionary = new SortedDictionary<string, PatcherPlugin>();
			foreach (KeyValuePair<string, List<PatcherPlugin>> item in TypeLoader.FindPluginTypes<PatcherPlugin>(directory, (Func<TypeDefinition, PatcherPlugin>)ToPatcherPlugin, (Func<AssemblyDefinition, bool>)null, (string)null))
			{
				string key = item.Key;
				List<PatcherPlugin> value = item.Value;
				if (value.Count == 0)
				{
					continue;
				}
				Assembly assembly = Assembly.LoadFile(key);
				foreach (PatcherPlugin item2 in value)
				{
					try
					{
						Type type = assembly.GetType(item2.TypeName);
						MethodInfo[] methods = type.GetMethods(BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
						item2.Initializer = CreateDelegate<Action>(methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Initialize", StringComparison.InvariantCultureIgnoreCase) && m.GetParameters().Length == 0 && (object)m.ReturnType == typeof(void)));
						item2.Finalizer = CreateDelegate<Action>(methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Finish", StringComparison.InvariantCultureIgnoreCase) && m.GetParameters().Length == 0 && (object)m.ReturnType == typeof(void)));
						item2.TargetDLLs = CreateDelegate<Func<IEnumerable<string>>>(type.GetProperty("TargetDLLs", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod());
						MethodInfo patcher = methods.FirstOrDefault((MethodInfo m) => m.Name.Equals("Patch", StringComparison.CurrentCultureIgnoreCase) && (object)m.ReturnType == typeof(void) && m.GetParameters().Length == 1 && ((object)m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition) || (object)m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition).MakeByRefType()));
						item2.Patcher = delegate(ref AssemblyDefinition pAss)
						{
							//IL_001e: Unknown result type (might be due to invalid IL or missing references)
							//IL_0024: Expected O, but got Unknown
							object[] array = new object[1] { pAss };
							patcher.Invoke(null, array);
							pAss = (AssemblyDefinition)array[0];
						};
						sortedDictionary.Add(assembly.GetName().Name + "/" + type.FullName, item2);
					}
					catch (Exception ex)
					{
						Logger.LogError((object)("Failed to load patcher [" + item2.TypeName + "]: " + ex.Message));
						if (ex is ReflectionTypeLoadException ex2)
						{
							Logger.LogDebug((object)TypeLoader.TypeLoadExceptionToString(ex2));
						}
						else
						{
							Logger.LogDebug((object)ex.ToString());
						}
					}
				}
				AssemblyName name = assembly.GetName();
				Logger.Log((LogLevel)(value.Any() ? 16 : 32), (object)string.Format("Loaded {0} patcher method{1} from [{2} {3}]", value.Count, (value.Count == 1) ? "" : "s", name.Name, name.Version));
			}
			foreach (KeyValuePair<string, PatcherPlugin> item3 in sortedDictionary)
			{
				AddPatcher(item3.Value);
			}
		}

		private static void InitializePatchers()
		{
			foreach (PatcherPlugin item in PatcherPluginsSafe)
			{
				try
				{
					item.Initializer?.Invoke();
				}
				catch (Exception arg)
				{
					Logger.LogError((object)$"Failed to run Initializer of {item.TypeName}: {arg}");
				}
			}
		}

		private static void FinalizePatching()
		{
			foreach (PatcherPlugin item in PatcherPluginsSafe)
			{
				try
				{
					item.Finalizer?.Invoke();
				}
				catch (Exception arg)
				{
					Logger.LogError((object)$"Failed to run Finalizer of {item.TypeName}: {arg}");
				}
			}
		}

		public static void DisposePatchers()
		{
			PatcherPlugins.Clear();
		}

		private static string GetAssemblyName(string fullName)
		{
			AssemblyName assemblyName = default(AssemblyName);
			if (!Utility.TryParseAssemblyName(fullName, ref assemblyName))
			{
				return fullName;
			}
			return assemblyName.Name;
		}

		public static void PatchAndLoad(params string[] directories)
		{
			Dictionary<string, AssemblyDefinition> dictionary = new Dictionary<string, AssemblyDefinition>(StringComparer.InvariantCultureIgnoreCase);
			foreach (string uniqueFilesInDirectory in Utility.GetUniqueFilesInDirectories((IEnumerable<string>)directories, "*.dll"))
			{
				AssemblyDefinition val;
				try
				{
					val = AssemblyDefinition.ReadAssembly(uniqueFilesInDirectory);
				}
				catch (BadImageFormatException)
				{
					continue;
				}
				if (((AssemblyNameReference)val.Name).Name == "System" || ((AssemblyNameReference)val.Name).Name == "mscorlib")
				{
					val.Dispose();
					continue;
				}
				if (UnityPatches.AssemblyLocations.ContainsKey(val.FullName))
				{
					Logger.LogWarning((object)("Tried to load duplicate assembly " + Path.GetFileName(uniqueFilesInDirectory) + " from Managed folder! Skipping..."));
					continue;
				}
				dictionary.Add(Path.GetFileName(uniqueFilesInDirectory), val);
				UnityPatches.AssemblyLocations.Add(val.FullName, Path.GetFullPath(uniqueFilesInDirectory));
			}
			InitializePatchers();
			HashSet<string> patchedAssemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
			Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
			HashSet<string> hashSet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
			foreach (PatcherPlugin item in PatcherPluginsSafe)
			{
				foreach (string item2 in item.TargetDLLs())
				{
					if (!dictionary.TryGetValue(item2, out var value) || hashSet.Contains(item2))
					{
						continue;
					}
					Logger.LogInfo((object)("Patching [" + ((AssemblyNameReference)value.Name).Name + "] with [" + item.TypeName + "]"));
					try
					{
						item.Patcher?.Invoke(ref value);
					}
					catch (Exception arg)
					{
						Logger.LogError((object)$"Failed to run [{item.TypeName}] when patching [{((AssemblyNameReference)value.Name).Name}]. This assembly will not be patched. Error: {arg}");
						patchedAssemblies.Remove(item2);
						hashSet.Add(item2);
						continue;
					}
					dictionary[item2] = value;
					patchedAssemblies.Add(item2);
					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
					for (int i = 0; i < assemblies.Length; i++)
					{
						string assemblyName = GetAssemblyName(assemblies[i].FullName);
						if (!dictionary2.ContainsKey(assemblyName))
						{
							dictionary2[assemblyName] = item.TypeName;
						}
					}
				}
			}
			HashSet<string> patchedAssemblyNames = new HashSet<string>(from kv in dictionary
				where patchedAssemblies.Contains(kv.Key)
				select ((AssemblyNameReference)kv.Value.Name).Name, StringComparer.InvariantCultureIgnoreCase);
			List<KeyValuePair<string, string>> list = dictionary2.Where((KeyValuePair<string, string> kv) => patchedAssemblyNames.Contains(kv.Key)).ToList();
			if (list.Count != 0)
			{
				Logger.LogWarning((object)new StringBuilder().AppendLine("The following assemblies have been loaded too early and will not be patched by preloader:").AppendLine(string.Join(Environment.NewLine, list.Select((KeyValuePair<string, string> kv) => "* [" + kv.Key + "] (first loaded by [" + kv.Value + "])").ToArray())).AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.")
					.ToString());
			}
			DumpedAssemblyPaths.Clear();
			if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value)
			{
				if (!Directory.Exists(DumpedAssembliesPath))
				{
					Directory.CreateDirectory(DumpedAssembliesPath);
				}
				FileStream fileStream = default(FileStream);
				foreach (KeyValuePair<string, AssemblyDefinition> item3 in dictionary)
				{
					string key = item3.Key;
					string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(key);
					string extension = Path.GetExtension(key);
					AssemblyDefinition value2 = item3.Value;
					if (!patchedAssemblies.Contains(key))
					{
						continue;
					}
					int num = 0;
					string text2;
					while (true)
					{
						string text = ((num > 0) ? $"_{num}" : "");
						text2 = Path.Combine(DumpedAssembliesPath, fileNameWithoutExtension + text + extension);
						if (Utility.TryOpenFileStream(text2, FileMode.Create, ref fileStream, FileAccess.ReadWrite, FileShare.Read))
						{
							break;
						}
						num++;
					}
					value2.Write((Stream)fileStream);
					fileStream.Dispose();
					DumpedAssemblyPaths[key] = text2;
				}
			}
			if (ConfigBreakBeforeLoadAssemblies.Value)
			{
				Logger.LogInfo((object)("BepInEx is about load the following assemblies:\n" + string.Join("\n", patchedAssemblies.ToArray())));
				Logger.LogInfo((object)("The assemblies were dumped into " + DumpedAssembliesPath));
				Logger.LogInfo((object)"Load any assemblies into the debugger, set breakpoints and continue execution.");
				Debugger.Break();
			}
			foreach (KeyValuePair<string, AssemblyDefinition> item4 in dictionary)
			{
				string key2 = item4.Key;
				AssemblyDefinition value3 = item4.Value;
				if (patchedAssemblies.Contains(key2))
				{
					Load(value3, key2);
				}
				value3.Dispose();
			}
			FinalizePatching();
		}

		public static void Load(AssemblyDefinition assembly, string filename)
		{
			if (ConfigLoadDumpedAssemblies.Value && DumpedAssemblyPaths.TryGetValue(filename, out var value))
			{
				Assembly.LoadFile(value);
				return;
			}
			using MemoryStream memoryStream = new MemoryStream();
			assembly.Write((Stream)memoryStream);
			Assembly.Load(memoryStream.ToArray());
		}
	}
	public class PatcherPlugin : ICacheable
	{
		public Func<IEnumerable<string>> TargetDLLs { get; set; }

		public Action Initializer { get; set; }

		public Action Finalizer { get; set; }

		public AssemblyPatcherDelegate Patcher { get; set; }

		public string TypeName { get; set; } = string.Empty;


		public void Save(BinaryWriter bw)
		{
			bw.Write(TypeName);
		}

		public void Load(BinaryReader br)
		{
			TypeName = br.ReadString();
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/core/HarmonyXInterop.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using HarmonyLib;
using HarmonyLib.Public.Patching;
using HarmonyLib.Tools;
using Mono.Cecil;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("HarmonyXInterop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HarmonyXInterop")]
[assembly: AssemblyCopyright("Copyright ©  2020")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("160F7FE0-288D-435C-9E7E-497D3E0DE3A6")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace HarmonyXInterop;

internal static class DMDUtil
{
	public static MethodInfo GenerateWith<T>(this DynamicMethodDefinition dmd, object context = null) where T : DMDGenerator<T>, new()
	{
		return DMDGenerator<T>.Generate(dmd, context);
	}
}
public static class HarmonyInterop
{
	private const string BACKUP_PATH = "BepInEx_Shim_Backup";

	private static Version maxAvailableShimVersion;

	private static readonly SortedDictionary<Version, string> Assemblies = new SortedDictionary<Version, string>();

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

	private static readonly Func<MethodBase, PatchInfo, MethodInfo> UpdateWrapper = AccessTools.MethodDelegate<Func<MethodBase, PatchInfo, MethodInfo>>(AccessTools.Method(typeof(HarmonyManipulator).Assembly.GetType("HarmonyLib.PatchFunctions"), "UpdateWrapper", (Type[])null, (Type[])null), (object)null, true);

	private static readonly Action<LogChannel, Func<string>, bool> HarmonyLog = AccessTools.MethodDelegate<Action<LogChannel, Func<string>, bool>>(AccessTools.Method(typeof(Logger), "Log", (Type[])null, (Type[])null), (object)null, true);

	private static readonly Action<LogChannel, string, bool> HarmonyLogText = AccessTools.MethodDelegate<Action<LogChannel, string, bool>>(AccessTools.Method(typeof(Logger), "LogText", (Type[])null, (Type[])null), (object)null, true);

	private static readonly Dictionary<string, long> shimCache = new Dictionary<string, long>();

	private static BinaryWriter cacheWriter;

	public static void Log(int channel, Func<string> message)
	{
		HarmonyLog((LogChannel)channel, message, arg3: false);
	}

	public static void LogText(int channel, string message)
	{
		HarmonyLogText((LogChannel)channel, message, arg3: false);
	}

	public static void Initialize(string cachePath)
	{
		Directory.CreateDirectory(cachePath);
		string path = Path.Combine(cachePath, "harmony_interop_cache.dat");
		string[] files = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "0Harmony*.dll", SearchOption.AllDirectories);
		for (int i = 0; i < files.Length; i++)
		{
			AssemblyDefinition val = AssemblyDefinition.ReadAssembly(files[i]);
			try
			{
				if (((AssemblyNameReference)val.Name).Name != "0Harmony")
				{
					Assemblies.Add(((AssemblyNameReference)val.Name).Version, ((AssemblyNameReference)val.Name).Name);
					InteropAssemblyNames.Add(((AssemblyNameReference)val.Name).Name);
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}
		maxAvailableShimVersion = Assemblies.LastOrDefault().Key;
		if (File.Exists(path))
		{
			try
			{
				using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path));
				while (true)
				{
					string key = binaryReader.ReadString();
					long value = binaryReader.ReadInt64();
					shimCache[key] = value;
				}
			}
			catch (Exception)
			{
			}
		}
		try
		{
			cacheWriter = new BinaryWriter(File.Create(path));
			foreach (KeyValuePair<string, long> item in shimCache)
			{
				cacheWriter.Write(item.Key);
				cacheWriter.Write(item.Value);
			}
			cacheWriter.Flush();
		}
		catch (IOException)
		{
		}
	}

	public static byte[] TryShim(string path, string gameRootDirectory, Action<string> logMessage = null, ReaderParameters readerParameters = null)
	{
		HashSet<string> hashSet = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
		List<string> deps;
		byte[] result = TryShimInternal(path, gameRootDirectory, logMessage, readerParameters, out deps);
		foreach (string item in deps)
		{
			hashSet.Add(item);
		}
		while (hashSet.Count != 0)
		{
			string text = hashSet.First();
			TryShimInternal(text, gameRootDirectory, logMessage, readerParameters, out deps);
			foreach (string item2 in deps)
			{
				hashSet.Add(item2);
			}
			hashSet.Remove(text);
		}
		return result;
	}

	private static bool NeedsShimming(string path, out long lastWriteTime, Action<string> logMessage = null)
	{
		lastWriteTime = 0L;
		try
		{
			if (!File.Exists(path))
			{
				return false;
			}
		}
		catch (Exception arg)
		{
			logMessage?.Invoke($"Failed to read path {path}: {arg}");
			return false;
		}
		lastWriteTime = File.GetLastWriteTimeUtc(path).Ticks;
		if (shimCache.TryGetValue(path, out var value))
		{
			return value != lastWriteTime;
		}
		return true;
	}

	private static byte[] TryShimInternal(string path, string gameRootDirectory, Action<string> logMessage, ReaderParameters readerParameters, out List<string> deps)
	{
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		deps = new List<string>();
		if (!NeedsShimming(path, out var lastWriteTime, logMessage))
		{
			return null;
		}
		byte[] result = null;
		try
		{
			string dir = Path.GetDirectoryName(path);
			byte[] array;
			try
			{
				array = File.ReadAllBytes(path);
			}
			catch (Exception)
			{
				return null;
			}
			using MemoryStream memoryStream = new MemoryStream(array);
			AssemblyDefinition val = AssemblyDefinition.ReadAssembly((Stream)memoryStream, (ReaderParameters)(((object)readerParameters) ?? ((object)new ReaderParameters())));
			try
			{
				deps.AddRange(from a in (IEnumerable<AssemblyNameReference>)val.MainModule.AssemblyReferences
					select Path.Combine(dir, a.Name + ".dll") into p
					where NeedsShimming(p, out var _, logMessage)
					select p);
				AssemblyNameReference harmonyRef = ((IEnumerable<AssemblyNameReference>)val.MainModule.AssemblyReferences).FirstOrDefault((Func<AssemblyNameReference, bool>)((AssemblyNameReference a) => a.Name.StartsWith("0Harmony") && !InteropAssemblyNames.Contains(a.Name)));
				if (harmonyRef != null)
				{
					KeyValuePair<Version, string> keyValuePair = Assemblies.LastOrDefault((KeyValuePair<Version, string> kv) => VersionMatches(kv.Key, harmonyRef.Version));
					if (keyValuePair.Value != null)
					{
						logMessage?.Invoke("Shimming " + path + " to use older version of Harmony (" + keyValuePair.Value + "). Please update the plugin if possible.");
						harmonyRef.Name = keyValuePair.Value;
						using MemoryStream memoryStream2 = new MemoryStream();
						val.Write((Stream)memoryStream2);
						try
						{
							string path2 = Path.Combine(gameRootDirectory, "BepInEx_Shim_Backup");
							string directoryName = Path.GetDirectoryName(Path.GetFullPath(path).Substring(gameRootDirectory.Length + 1));
							string text = Path.Combine(path2, directoryName);
							Directory.CreateDirectory(text);
							File.WriteAllBytes(Path.Combine(text, Path.GetFileName(path)), array);
							File.WriteAllBytes(path, memoryStream2.ToArray());
							lastWriteTime = File.GetLastWriteTimeUtc(path).Ticks;
						}
						catch (IOException)
						{
							lastWriteTime = 0L;
						}
						result = memoryStream2.ToArray();
					}
				}
				shimCache[path] = lastWriteTime;
				if (cacheWriter != null)
				{
					cacheWriter.Write(path);
					cacheWriter.Write(lastWriteTime);
					cacheWriter.Flush();
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}
		catch (Exception arg)
		{
			logMessage?.Invoke($"Failed to shim {path}: {arg}");
		}
		return result;
		static bool VersionMatches(Version cmpV, Version refV)
		{
			if (maxAvailableShimVersion != null && refV <= maxAvailableShimVersion && cmpV.Major == refV.Major && cmpV.Minor == refV.Minor)
			{
				return cmpV <= refV;
			}
			return false;
		}
	}

	public static void ApplyPatch(MethodBase target, PatchInfoWrapper add, PatchInfoWrapper remove)
	{
		PatchInfo val = PatchManager.ToPatchInfo(target);
		lock (val)
		{
			val.prefixes = Sync(add.prefixes, remove.prefixes, val.prefixes);
			val.postfixes = Sync(add.postfixes, remove.postfixes, val.postfixes);
			val.transpilers = Sync(WrapTranspilers(add.transpilers), WrapTranspilers(remove.transpilers), val.transpilers);
			val.finalizers = Sync(add.finalizers, remove.finalizers, val.finalizers);
		}
		UpdateWrapper(target, val);
		static PatchMethod[] WrapTranspilers(PatchMethod[] transpilers)
		{
			return transpilers.Select((PatchMethod p) => new PatchMethod
			{
				after = p.after,
				before = p.before,
				method = TranspilerInterop.WrapInterop(p.method),
				owner = p.owner,
				priority = p.priority
			}).ToArray();
		}
	}

	private static Patch[] Sync(PatchMethod[] add, PatchMethod[] remove, Patch[] current)
	{
		if (add.Length == 0 && remove.Length == 0)
		{
			return current;
		}
		current = current.Where((Patch p) => !remove.Any((PatchMethod r) => (object)r.method == p.PatchMethod && r.owner == p.owner)).ToArray();
		int initialIndex = current.Length;
		return current.Concat(add.Where((PatchMethod method) => method != null).Select((Func<PatchMethod, int, Patch>)((PatchMethod method, int i) => new Patch(method.ToHarmonyMethod(), i + initialIndex, method.owner)))).ToArray();
	}
}
public class PatchInfoWrapper
{
	public PatchMethod[] finalizers;

	public PatchMethod[] postfixes;

	public PatchMethod[] prefixes;

	public PatchMethod[] transpilers;
}
public class PatchMethod
{
	public string[] after;

	public string[] before;

	public MethodInfo method;

	public string owner;

	public int priority = -1;

	public HarmonyMethod ToHarmonyMethod()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: 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_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		return new HarmonyMethod
		{
			after = after,
			before = before,
			method = method,
			priority = priority
		};
	}
}
public class PatchMethodComparer : IEqualityComparer<PatchMethod>
{
	public static PatchMethodComparer Instance { get; } = new PatchMethodComparer();


	public bool Equals(PatchMethod x, PatchMethod y)
	{
		if (x == y)
		{
			return true;
		}
		if (x == null)
		{
			return false;
		}
		if (y == null)
		{
			return false;
		}
		if ((object)x.GetType() != y.GetType())
		{
			return false;
		}
		if (object.Equals(x.method, y.method))
		{
			return x.owner == y.owner;
		}
		return false;
	}

	public int GetHashCode(PatchMethod obj)
	{
		return ((((object)obj.method != null) ? obj.method.GetHashCode() : 0) * 397) ^ ((obj.owner != null) ? obj.owner.GetHashCode() : 0);
	}
}
internal static class TranspilerInterop
{
	private static readonly Dictionary<OpCode, OpCode> AllJumpCodes = new Dictionary<OpCode, OpCode>
	{
		{
			OpCodes.Beq_S,
			OpCodes.Beq
		},
		{
			OpCodes.Bge_S,
			OpCodes.Bge
		},
		{
			OpCodes.Bge_Un_S,
			OpCodes.Bge_Un
		},
		{
			OpCodes.Bgt_S,
			OpCodes.Bgt
		},
		{
			OpCodes.Bgt_Un_S,
			OpCodes.Bgt_Un
		},
		{
			OpCodes.Ble_S,
			OpCodes.Ble
		},
		{
			OpCodes.Ble_Un_S,
			OpCodes.Ble_Un
		},
		{
			OpCodes.Blt_S,
			OpCodes.Blt
		},
		{
			OpCodes.Blt_Un_S,
			OpCodes.Blt_Un
		},
		{
			OpCodes.Bne_Un_S,
			OpCodes.Bne_Un
		},
		{
			OpCodes.Brfalse_S,
			OpCodes.Brfalse
		},
		{
			OpCodes.Brtrue_S,
			OpCodes.Brtrue
		},
		{
			OpCodes.Br_S,
			OpCodes.Br
		},
		{
			OpCodes.Leave_S,
			OpCodes.Leave
		}
	};

	private static readonly Dictionary<MethodInfo, MethodInfo> Wrappers = new Dictionary<MethodInfo, MethodInfo>();

	private static readonly MethodInfo ResolveToken = AccessTools.Method(typeof(MethodBase), "GetMethodFromHandle", new Type[1] { typeof(RuntimeMethodHandle) }, (Type[])null);

	private static readonly MethodInfo ApplyTranspilerMethod = AccessTools.Method(typeof(TranspilerInterop), "ApplyTranspiler", (Type[])null, (Type[])null);

	public static MethodInfo WrapInterop(MethodInfo transpiler)
	{
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Expected O, but got Unknown
		lock (Wrappers)
		{
			if (Wrappers.TryGetValue(transpiler, out var value))
			{
				return value;
			}
		}
		DynamicMethodDefinition val = new DynamicMethodDefinition("TranspilerWrapper<" + Extensions.GetID((MethodBase)transpiler, (string)null, (string)null, true, false, true) + ">", typeof(IEnumerable<CodeInstruction>), new Type[3]
		{
			typeof(IEnumerable<CodeInstruction>),
			typeof(ILGenerator),
			typeof(MethodBase)
		});
		try
		{
			ILGenerator iLGenerator = val.GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldtoken, transpiler);
			iLGenerator.Emit(OpCodes.Call, ResolveToken);
			iLGenerator.Emit(OpCodes.Castclass, typeof(MethodInfo));
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Ldarg_2);
			iLGenerator.Emit(OpCodes.Call, ApplyTranspilerMethod);
			iLGenerator.Emit(OpCodes.Ret);
			MethodInfo methodInfo = val.GenerateWith<DMDCecilGenerator>((object)null);
			lock (Wrappers)
			{
				Wrappers[transpiler] = methodInfo;
			}
			return methodInfo;
		}
		finally
		{
			((IDisposable)val)?.Dispose();
		}
	}

	private static IEnumerable<CodeInstruction> ApplyTranspiler(MethodInfo transpiler, IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase method)
	{
		Dictionary<object, Dictionary<string, object>> unassignedValues;
		IEnumerable enumerable = ConvertToGeneralInstructions(transpiler, instructions, out unassignedValues);
		List<object> originalInstructions = null;
		if (unassignedValues != null)
		{
			originalInstructions = instructions.Cast<object>().ToList();
		}
		List<object> transpilerCallParameters = GetTranspilerCallParameters(generator, transpiler, method, enumerable);
		if (transpiler.Invoke(null, transpilerCallParameters.ToArray()) is IEnumerable enumerable2)
		{
			enumerable = enumerable2;
		}
		if (unassignedValues != null)
		{
			enumerable = ConvertToOurInstructions(enumerable, typeof(CodeInstruction), originalInstructions, unassignedValues);
		}
		return (enumerable as List<CodeInstruction>) ?? enumerable.Cast<CodeInstruction>().ToList();
	}

	private static OpCode ReplaceShortJumps(OpCode opcode)
	{
		using (IEnumerator<KeyValuePair<OpCode, OpCode>> enumerator = AllJumpCodes.Where((KeyValuePair<OpCode, OpCode> pair) => opcode == pair.Key).GetEnumerator())
		{
			if (enumerator.MoveNext())
			{
				return enumerator.Current.Value;
			}
		}
		return opcode;
	}

	private static object ConvertInstruction(Type type, object instruction, out Dictionary<string, object> unassigned)
	{
		Dictionary<string, object> nonExisting = new Dictionary<string, object>();
		object result = AccessTools.MakeDeepCopy(instruction, type, (Func<string, Traverse, Traverse, object>)delegate(string namePath, Traverse trvSrc, Traverse trvDest)
		{
			object value = trvSrc.GetValue();
			if (trvDest.FieldExists())
			{
				if (!(namePath == "opcode"))
				{
					return value;
				}
				return ReplaceShortJumps((OpCode)value);
			}
			nonExisting[namePath] = value;
			return null;
		}, "");
		unassigned = nonExisting;
		return result;
	}

	private static bool ShouldAddExceptionInfo(object op, int opIndex, List<object> originalInstructions, List<object> newInstructions, Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		int num = originalInstructions.IndexOf(op);
		if (num == -1)
		{
			return false;
		}
		if (!unassignedValues.TryGetValue(op, out var unassigned))
		{
			return false;
		}
		if (!unassigned.TryGetValue("blocks", out var blocksObject))
		{
			return false;
		}
		List<ExceptionBlock> blocks = blocksObject as List<ExceptionBlock>;
		if (newInstructions.Count((object instr) => instr == op) <= 1)
		{
			return true;
		}
		ExceptionBlock val = ((IEnumerable<ExceptionBlock>)blocks).FirstOrDefault((Func<ExceptionBlock, bool>)((ExceptionBlock block) => (int)block.blockType != 5));
		ExceptionBlock val2 = ((IEnumerable<ExceptionBlock>)blocks).FirstOrDefault((Func<ExceptionBlock, bool>)((ExceptionBlock block) => (int)block.blockType == 5));
		if (val != null && val2 == null)
		{
			object obj = originalInstructions.Skip(num + 1).FirstOrDefault(delegate(object instr)
			{
				if (!unassignedValues.TryGetValue(instr, out unassigned))
				{
					return false;
				}
				if (!unassigned.TryGetValue("blocks", out blocksObject))
				{
					return false;
				}
				blocks = blocksObject as List<ExceptionBlock>;
				return blocks.Any();
			});
			if (obj != null)
			{
				int num2 = num + 1;
				int num3 = num2 + originalInstructions.Skip(num2).ToList().IndexOf(obj) - 1;
				IEnumerable<object> first = originalInstructions.GetRange(num2, num3 - num2).Intersect(newInstructions);
				obj = newInstructions.Skip(opIndex + 1).FirstOrDefault(delegate(object instr)
				{
					if (!unassignedValues.TryGetValue(instr, out unassigned))
					{
						return false;
					}
					if (!unassigned.TryGetValue("blocks", out blocksObject))
					{
						return false;
					}
					blocks = blocksObject as List<ExceptionBlock>;
					return blocks.Any();
				});
				if (obj != null)
				{
					num2 = opIndex + 1;
					num3 = num2 + newInstructions.Skip(opIndex + 1).ToList().IndexOf(obj) - 1;
					List<object> range = newInstructions.GetRange(num2, num3 - num2);
					return !first.Except(range).ToList().Any();
				}
			}
		}
		if (val == null && val2 != null)
		{
			object obj2 = originalInstructions.GetRange(0, num).LastOrDefault(delegate(object instr)
			{
				if (!unassignedValues.TryGetValue(instr, out unassigned))
				{
					return false;
				}
				if (!unassigned.TryGetValue("blocks", out blocksObject))
				{
					return false;
				}
				blocks = blocksObject as List<ExceptionBlock>;
				return blocks.Any();
			});
			if (obj2 == null)
			{
				return true;
			}
			int num4 = originalInstructions.GetRange(0, num).LastIndexOf(obj2);
			int num5 = num;
			IEnumerable<object> first2 = originalInstructions.GetRange(num4, num5 - num4).Intersect(newInstructions);
			obj2 = newInstructions.GetRange(0, opIndex).LastOrDefault(delegate(object instr)
			{
				if (!unassignedValues.TryGetValue(instr, out unassigned))
				{
					return false;
				}
				if (!unassigned.TryGetValue("blocks", out blocksObject))
				{
					return false;
				}
				blocks = blocksObject as List<ExceptionBlock>;
				return blocks.Any();
			});
			if (obj2 == null)
			{
				return true;
			}
			num4 = newInstructions.GetRange(0, opIndex).LastIndexOf(obj2);
			num5 = opIndex;
			List<object> range2 = newInstructions.GetRange(num4, num5 - num4);
			return !first2.Except(range2).Any();
		}
		return true;
	}

	private static IEnumerable ConvertInstructionsAndUnassignedValues(Type type, IEnumerable enumerable, out Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		Assembly assembly = type.GetGenericTypeDefinition().Assembly;
		Type? type2 = assembly.GetType(typeof(List<>).FullName);
		Type type3 = type.GetGenericArguments()[0];
		Type type4 = type2.MakeGenericType(type3);
		object obj = Activator.CreateInstance(assembly.GetType(type4.FullName));
		MethodInfo method = obj.GetType().GetMethod("Add");
		unassignedValues = new Dictionary<object, Dictionary<string, object>>();
		foreach (object item in enumerable)
		{
			Dictionary<string, object> unassigned;
			object obj2 = ConvertInstruction(type3, item, out unassigned);
			unassignedValues.Add(obj2, unassigned);
			method.Invoke(obj, new object[1] { obj2 });
		}
		return obj as IEnumerable;
	}

	private static IEnumerable ConvertToOurInstructions(IEnumerable instructions, Type codeInstructionType, List<object> originalInstructions, Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		List<object> newInstructions = instructions.Cast<object>().ToList();
		int index = -1;
		foreach (object item in newInstructions)
		{
			index++;
			object obj = AccessTools.MakeDeepCopy(item, codeInstructionType, (Func<string, Traverse, Traverse, object>)null, "");
			if (unassignedValues.TryGetValue(item, out var value))
			{
				bool addExceptionInfo = ShouldAddExceptionInfo(item, index, originalInstructions, newInstructions, unassignedValues);
				Traverse val = Traverse.Create(obj);
				foreach (KeyValuePair<string, object> item2 in value.Where((KeyValuePair<string, object> field) => addExceptionInfo || field.Key != "blocks"))
				{
					val.Field(item2.Key).SetValue(item2.Value);
				}
			}
			yield return obj;
		}
	}

	private static bool IsCodeInstructionsParameter(Type type)
	{
		if (type.IsGenericType)
		{
			return type.GetGenericTypeDefinition().Name.StartsWith("IEnumerable", StringComparison.Ordinal);
		}
		return false;
	}

	private static IEnumerable ConvertToGeneralInstructions(MethodInfo transpiler, IEnumerable enumerable, out Dictionary<object, Dictionary<string, object>> unassignedValues)
	{
		Type type = (from p in transpiler.GetParameters()
			select p.ParameterType).FirstOrDefault((Type t) => IsCodeInstructionsParameter(t));
		if ((object)type == null)
		{
			unassignedValues = new Dictionary<object, Dictionary<string, object>>();
			return enumerable;
		}
		if ((object)type != typeof(IEnumerable<CodeInstruction>))
		{
			return ConvertInstructionsAndUnassignedValues(type, enumerable, out unassignedValues);
		}
		unassignedValues = null;
		return (enumerable as IList<CodeInstruction>) ?? ((enumerable as IEnumerable<CodeInstruction>) ?? enumerable.Cast<CodeInstruction>()).ToList();
	}

	private static List<object> GetTranspilerCallParameters(ILGenerator generator, MethodInfo transpiler, MethodBase method, IEnumerable instructions)
	{
		List<object> parameter = new List<object>();
		CollectionExtensions.Do<Type>(from param in transpiler.GetParameters()
			select param.ParameterType, (Action<Type>)delegate(Type type)
		{
			if (type.IsAssignableFrom(typeof(ILGenerator)))
			{
				parameter.Add(generator);
			}
			else if (type.IsAssignableFrom(typeof(MethodBase)))
			{
				parameter.Add(method);
			}
			else if (IsCodeInstructionsParameter(type))
			{
				parameter.Add(instructions);
			}
		});
		return parameter;
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/core/Mono.Cecil.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using Mono.Collections.Generic;
using Mono.Security.Cryptography;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil")]
[assembly: Guid("fd225bb4-fa53-44b2-a6db-85f5e48dcb54")]
[assembly: InternalsVisibleTo("Mono.Cecil.Pdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: InternalsVisibleTo("Mono.Cecil.Mdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: InternalsVisibleTo("Mono.Cecil.Rocks, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: InternalsVisibleTo("Mono.Cecil.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")]
[assembly: AssemblyVersion("0.10.4.0")]
internal static class Consts
{
	public const string AssemblyName = "Mono.Cecil";

	public const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf";
}
namespace Mono
{
	internal static class Disposable
	{
		public static Disposable<T> Owned<T>(T value) where T : class, IDisposable
		{
			return new Disposable<T>(value, owned: true);
		}

		public static Disposable<T> NotOwned<T>(T value) where T : class, IDisposable
		{
			return new Disposable<T>(value, owned: false);
		}
	}
	internal struct Disposable<T> : IDisposable where T : class, IDisposable
	{
		internal readonly T value;

		private readonly bool owned;

		public Disposable(T value, bool owned)
		{
			this.value = value;
			this.owned = owned;
		}

		public void Dispose()
		{
			if (value != null && owned)
			{
				value.Dispose();
			}
		}
	}
	internal static class Empty<T>
	{
		public static readonly T[] Array = new T[0];
	}
	internal class ArgumentNullOrEmptyException : ArgumentException
	{
		public ArgumentNullOrEmptyException(string paramName)
			: base("Argument null or empty", paramName)
		{
		}
	}
	internal class MergeSort<T>
	{
		private readonly T[] elements;

		private readonly T[] buffer;

		private readonly IComparer<T> comparer;

		private MergeSort(T[] elements, IComparer<T> comparer)
		{
			this.elements = elements;
			buffer = new T[elements.Length];
			Array.Copy(this.elements, buffer, elements.Length);
			this.comparer = comparer;
		}

		public static void Sort(T[] source, IComparer<T> comparer)
		{
			Sort(source, 0, source.Length, comparer);
		}

		public static void Sort(T[] source, int start, int length, IComparer<T> comparer)
		{
			new MergeSort<T>(source, comparer).Sort(start, length);
		}

		private void Sort(int start, int length)
		{
			TopDownSplitMerge(buffer, elements, start, length);
		}

		private void TopDownSplitMerge(T[] a, T[] b, int start, int end)
		{
			if (end - start >= 2)
			{
				int num = (end + start) / 2;
				TopDownSplitMerge(b, a, start, num);
				TopDownSplitMerge(b, a, num, end);
				TopDownMerge(a, b, start, num, end);
			}
		}

		private void TopDownMerge(T[] a, T[] b, int start, int middle, int end)
		{
			int num = start;
			int num2 = middle;
			for (int i = start; i < end; i++)
			{
				if (num < middle && (num2 >= end || comparer.Compare(a[num], a[num2]) <= 0))
				{
					b[i] = a[num++];
				}
				else
				{
					b[i] = a[num2++];
				}
			}
		}
	}
	internal static class TypeExtensions
	{
		public static TypeCode GetTypeCode(this Type type)
		{
			return Type.GetTypeCode(type);
		}

		public static Assembly Assembly(this Type type)
		{
			return type.Assembly;
		}

		public static MethodBase DeclaringMethod(this Type type)
		{
			return type.DeclaringMethod;
		}

		public static Type[] GetGenericArguments(this Type type)
		{
			return type.GetGenericArguments();
		}

		public static bool IsGenericType(this Type type)
		{
			return type.IsGenericType;
		}

		public static bool IsGenericTypeDefinition(this Type type)
		{
			return type.IsGenericTypeDefinition;
		}

		public static bool IsValueType(this Type type)
		{
			return type.IsValueType;
		}
	}
}
namespace Mono.Security.Cryptography
{
	internal static class CryptoConvert
	{
		private static int ToInt32LE(byte[] bytes, int offset)
		{
			return (bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset];
		}

		private static uint ToUInt32LE(byte[] bytes, int offset)
		{
			return (uint)((bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]);
		}

		private static byte[] Trim(byte[] array)
		{
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i] != 0)
				{
					byte[] array2 = new byte[array.Length - i];
					Buffer.BlockCopy(array, i, array2, 0, array2.Length);
					return array2;
				}
			}
			return null;
		}

		private static RSA FromCapiPrivateKeyBlob(byte[] blob, int offset)
		{
			RSAParameters parameters = default(RSAParameters);
			try
			{
				if (blob[offset] != 7 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 843141970)
				{
					throw new CryptographicException("Invalid blob header");
				}
				int num = ToInt32LE(blob, offset + 12);
				byte[] array = new byte[4];
				Buffer.BlockCopy(blob, offset + 16, array, 0, 4);
				Array.Reverse((Array)array);
				parameters.Exponent = Trim(array);
				int num2 = offset + 20;
				int num3 = num >> 3;
				parameters.Modulus = new byte[num3];
				Buffer.BlockCopy(blob, num2, parameters.Modulus, 0, num3);
				Array.Reverse((Array)parameters.Modulus);
				num2 += num3;
				int num4 = num3 >> 1;
				parameters.P = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.P, 0, num4);
				Array.Reverse((Array)parameters.P);
				num2 += num4;
				parameters.Q = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.Q, 0, num4);
				Array.Reverse((Array)parameters.Q);
				num2 += num4;
				parameters.DP = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.DP, 0, num4);
				Array.Reverse((Array)parameters.DP);
				num2 += num4;
				parameters.DQ = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.DQ, 0, num4);
				Array.Reverse((Array)parameters.DQ);
				num2 += num4;
				parameters.InverseQ = new byte[num4];
				Buffer.BlockCopy(blob, num2, parameters.InverseQ, 0, num4);
				Array.Reverse((Array)parameters.InverseQ);
				num2 += num4;
				parameters.D = new byte[num3];
				if (num2 + num3 + offset <= blob.Length)
				{
					Buffer.BlockCopy(blob, num2, parameters.D, 0, num3);
					Array.Reverse((Array)parameters.D);
				}
			}
			catch (Exception inner)
			{
				throw new CryptographicException("Invalid blob.", inner);
			}
			RSA rSA = null;
			try
			{
				rSA = RSA.Create();
				rSA.ImportParameters(parameters);
			}
			catch (CryptographicException)
			{
				bool flag = false;
				try
				{
					rSA = new RSACryptoServiceProvider(new CspParameters
					{
						Flags = CspProviderFlags.UseMachineKeyStore
					});
					rSA.ImportParameters(parameters);
				}
				catch
				{
					flag = true;
				}
				if (flag)
				{
					throw;
				}
			}
			return rSA;
		}

		private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset)
		{
			try
			{
				if (blob[offset] != 6 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 826364754)
				{
					throw new CryptographicException("Invalid blob header");
				}
				int num = ToInt32LE(blob, offset + 12);
				RSAParameters parameters = new RSAParameters
				{
					Exponent = new byte[3]
				};
				parameters.Exponent[0] = blob[offset + 18];
				parameters.Exponent[1] = blob[offset + 17];
				parameters.Exponent[2] = blob[offset + 16];
				int srcOffset = offset + 20;
				int num2 = num >> 3;
				parameters.Modulus = new byte[num2];
				Buffer.BlockCopy(blob, srcOffset, parameters.Modulus, 0, num2);
				Array.Reverse((Array)parameters.Modulus);
				RSA rSA = null;
				try
				{
					rSA = RSA.Create();
					rSA.ImportParameters(parameters);
				}
				catch (CryptographicException)
				{
					rSA = new RSACryptoServiceProvider(new CspParameters
					{
						Flags = CspProviderFlags.UseMachineKeyStore
					});
					rSA.ImportParameters(parameters);
				}
				return rSA;
			}
			catch (Exception inner)
			{
				throw new CryptographicException("Invalid blob.", inner);
			}
		}

		public static RSA FromCapiKeyBlob(byte[] blob)
		{
			return FromCapiKeyBlob(blob, 0);
		}

		public static RSA FromCapiKeyBlob(byte[] blob, int offset)
		{
			if (blob == null)
			{
				throw new ArgumentNullException("blob");
			}
			if (offset >= blob.Length)
			{
				throw new ArgumentException("blob is too small.");
			}
			switch (blob[offset])
			{
			case 0:
				if (blob[offset + 12] == 6)
				{
					return FromCapiPublicKeyBlob(blob, offset + 12);
				}
				break;
			case 6:
				return FromCapiPublicKeyBlob(blob, offset);
			case 7:
				return FromCapiPrivateKeyBlob(blob, offset);
			}
			throw new CryptographicException("Unknown blob format.");
		}
	}
}
namespace Mono.Collections.Generic
{
	public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection
	{
		public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator
		{
			private Collection<T> collection;

			private T current;

			private int next;

			private readonly int version;

			public T Current => current;

			object IEnumerator.Current
			{
				get
				{
					CheckState();
					if (next <= 0)
					{
						throw new InvalidOperationException();
					}
					return current;
				}
			}

			internal Enumerator(Collection<T> collection)
			{
				this = default(Enumerator);
				this.collection = collection;
				version = collection.version;
			}

			public bool MoveNext()
			{
				CheckState();
				if (next < 0)
				{
					return false;
				}
				if (next < collection.size)
				{
					current = collection.items[next++];
					return true;
				}
				next = -1;
				return false;
			}

			public void Reset()
			{
				CheckState();
				next = 0;
			}

			private void CheckState()
			{
				if (collection == null)
				{
					throw new ObjectDisposedException(GetType().FullName);
				}
				if (version != collection.version)
				{
					throw new InvalidOperationException();
				}
			}

			public void Dispose()
			{
				collection = null;
			}
		}

		internal T[] items;

		internal int size;

		private int version;

		public int Count => size;

		public T this[int index]
		{
			get
			{
				if (index >= size)
				{
					throw new ArgumentOutOfRangeException();
				}
				return items[index];
			}
			set
			{
				CheckIndex(index);
				if (index == size)
				{
					throw new ArgumentOutOfRangeException();
				}
				OnSet(value, index);
				items[index] = value;
			}
		}

		public int Capacity
		{
			get
			{
				return items.Length;
			}
			set
			{
				if (value < 0 || value < size)
				{
					throw new ArgumentOutOfRangeException();
				}
				Resize(value);
			}
		}

		bool ICollection<T>.IsReadOnly => false;

		bool IList.IsFixedSize => false;

		bool IList.IsReadOnly => false;

		object IList.this[int index]
		{
			get
			{
				return this[index];
			}
			set
			{
				CheckIndex(index);
				try
				{
					this[index] = (T)value;
					return;
				}
				catch (InvalidCastException)
				{
				}
				catch (NullReferenceException)
				{
				}
				throw new ArgumentException();
			}
		}

		int ICollection.Count => Count;

		bool ICollection.IsSynchronized => false;

		object ICollection.SyncRoot => this;

		public Collection()
		{
			items = Empty<T>.Array;
		}

		public Collection(int capacity)
		{
			if (capacity < 0)
			{
				throw new ArgumentOutOfRangeException();
			}
			items = new T[capacity];
		}

		public Collection(ICollection<T> items)
		{
			if (items == null)
			{
				throw new ArgumentNullException("items");
			}
			this.items = new T[items.Count];
			items.CopyTo(this.items, 0);
			size = this.items.Length;
		}

		public void Add(T item)
		{
			if (size == items.Length)
			{
				Grow(1);
			}
			OnAdd(item, size);
			items[size++] = item;
			version++;
		}

		public bool Contains(T item)
		{
			return IndexOf(item) != -1;
		}

		public int IndexOf(T item)
		{
			return Array.IndexOf(items, item, 0, size);
		}

		public void Insert(int index, T item)
		{
			CheckIndex(index);
			if (size == items.Length)
			{
				Grow(1);
			}
			OnInsert(item, index);
			Shift(index, 1);
			items[index] = item;
			version++;
		}

		public void RemoveAt(int index)
		{
			if (index < 0 || index >= size)
			{
				throw new ArgumentOutOfRangeException();
			}
			T item = items[index];
			OnRemove(item, index);
			Shift(index, -1);
			version++;
		}

		public bool Remove(T item)
		{
			int num = IndexOf(item);
			if (num == -1)
			{
				return false;
			}
			OnRemove(item, num);
			Shift(num, -1);
			version++;
			return true;
		}

		public void Clear()
		{
			OnClear();
			Array.Clear(items, 0, size);
			size = 0;
			version++;
		}

		public void CopyTo(T[] array, int arrayIndex)
		{
			Array.Copy(items, 0, array, arrayIndex, size);
		}

		public T[] ToArray()
		{
			T[] array = new T[size];
			Array.Copy(items, 0, array, 0, size);
			return array;
		}

		private void CheckIndex(int index)
		{
			if (index < 0 || index > size)
			{
				throw new ArgumentOutOfRangeException();
			}
		}

		private void Shift(int start, int delta)
		{
			if (delta < 0)
			{
				start -= delta;
			}
			if (start < size)
			{
				Array.Copy(items, start, items, start + delta, size - start);
			}
			size += delta;
			if (delta < 0)
			{
				Array.Clear(items, size, -delta);
			}
		}

		protected virtual void OnAdd(T item, int index)
		{
		}

		protected virtual void OnInsert(T item, int index)
		{
		}

		protected virtual void OnSet(T item, int index)
		{
		}

		protected virtual void OnRemove(T item, int index)
		{
		}

		protected virtual void OnClear()
		{
		}

		internal virtual void Grow(int desired)
		{
			int num = size + desired;
			if (num > items.Length)
			{
				num = Math.Max(Math.Max(items.Length * 2, 4), num);
				Resize(num);
			}
		}

		protected void Resize(int new_size)
		{
			if (new_size != size)
			{
				if (new_size < size)
				{
					throw new ArgumentOutOfRangeException();
				}
				items = items.Resize(new_size);
			}
		}

		int IList.Add(object value)
		{
			try
			{
				Add((T)value);
				return size - 1;
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
			throw new ArgumentException();
		}

		void IList.Clear()
		{
			Clear();
		}

		bool IList.Contains(object value)
		{
			return ((IList)this).IndexOf(value) > -1;
		}

		int IList.IndexOf(object value)
		{
			try
			{
				return IndexOf((T)value);
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
			return -1;
		}

		void IList.Insert(int index, object value)
		{
			CheckIndex(index);
			try
			{
				Insert(index, (T)value);
				return;
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
			throw new ArgumentException();
		}

		void IList.Remove(object value)
		{
			try
			{
				Remove((T)value);
			}
			catch (InvalidCastException)
			{
			}
			catch (NullReferenceException)
			{
			}
		}

		void IList.RemoveAt(int index)
		{
			RemoveAt(index);
		}

		void ICollection.CopyTo(Array array, int index)
		{
			Array.Copy(items, 0, array, index, size);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return new Enumerator(this);
		}

		IEnumerator<T> IEnumerable<T>.GetEnumerator()
		{
			return new Enumerator(this);
		}
	}
	public sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection
	{
		private static ReadOnlyCollection<T> empty;

		public static ReadOnlyCollection<T> Empty => empty ?? (empty = new ReadOnlyCollection<T>());

		bool ICollection<T>.IsReadOnly => true;

		bool IList.IsFixedSize => true;

		bool IList.IsReadOnly => true;

		private ReadOnlyCollection()
		{
		}

		public ReadOnlyCollection(T[] array)
		{
			if (array == null)
			{
				throw new ArgumentNullException();
			}
			Initialize(array, array.Length);
		}

		public ReadOnlyCollection(Collection<T> collection)
		{
			if (collection == null)
			{
				throw new ArgumentNullException();
			}
			Initialize(collection.items, collection.size);
		}

		private void Initialize(T[] items, int size)
		{
			base.items = new T[size];
			Array.Copy(items, 0, base.items, 0, size);
			base.size = size;
		}

		internal override void Grow(int desired)
		{
			throw new InvalidOperationException();
		}

		protected override void OnAdd(T item, int index)
		{
			throw new InvalidOperationException();
		}

		protected override void OnClear()
		{
			throw new InvalidOperationException();
		}

		protected override void OnInsert(T item, int index)
		{
			throw new InvalidOperationException();
		}

		protected override void OnRemove(T item, int index)
		{
			throw new InvalidOperationException();
		}

		protected override void OnSet(T item, int index)
		{
			throw new InvalidOperationException();
		}
	}
}
namespace Mono.Cecil
{
	internal static class Mixin
	{
		public enum Argument
		{
			name,
			fileName,
			fullName,
			stream,
			type,
			method,
			field,
			parameters,
			module,
			modifierType,
			eventType,
			fieldType,
			declaringType,
			returnType,
			propertyType,
			interfaceType
		}

		public static Version ZeroVersion = new Version(0, 0, 0, 0);

		public const int NotResolvedMarker = -2;

		public const int NoDataMarker = -1;

		internal static object NoValue = new object();

		internal static object NotResolved = new object();

		public const string mscorlib = "mscorlib";

		public const string system_runtime = "System.Runtime";

		public const string system_private_corelib = "System.Private.CoreLib";

		public const string netstandard = "netstandard";

		public const int TableCount = 58;

		public const int CodedIndexCount = 14;

		public static bool IsNullOrEmpty<T>(this T[] self)
		{
			if (self != null)
			{
				return self.Length == 0;
			}
			return true;
		}

		public static bool IsNullOrEmpty<T>(this Collection<T> self)
		{
			if (self != null)
			{
				return self.size == 0;
			}
			return true;
		}

		public static T[] Resize<T>(this T[] self, int length)
		{
			Array.Resize(ref self, length);
			return self;
		}

		public static T[] Add<T>(this T[] self, T item)
		{
			if (self == null)
			{
				self = new T[1] { item };
				return self;
			}
			self = self.Resize(self.Length + 1);
			self[^1] = item;
			return self;
		}

		public static Version CheckVersion(Version version)
		{
			if (version == null)
			{
				return ZeroVersion;
			}
			if (version.Build == -1)
			{
				return new Version(version.Major, version.Minor, 0, 0);
			}
			if (version.Revision == -1)
			{
				return new Version(version.Major, version.Minor, version.Build, 0);
			}
			return version;
		}

		public static bool TryGetUniqueDocument(this MethodDebugInformation info, out Document document)
		{
			document = info.SequencePoints[0].Document;
			for (int i = 1; i < info.SequencePoints.Count; i++)
			{
				if (info.SequencePoints[i].Document != document)
				{
					return false;
				}
			}
			return true;
		}

		public static void ResolveConstant(this IConstantProvider self, ref object constant, ModuleDefinition module)
		{
			if (module == null)
			{
				constant = NoValue;
				return;
			}
			lock (module.SyncRoot)
			{
				if (constant != NotResolved)
				{
					return;
				}
				if (module.HasImage())
				{
					constant = module.Read(self, (IConstantProvider provider, MetadataReader reader) => reader.ReadConstant(provider));
				}
				else
				{
					constant = NoValue;
				}
			}
		}

		public static bool GetHasCustomAttributes(this ICustomAttributeProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.HasCustomAttributes(provider));
			}
			return false;
		}

		public static Collection<CustomAttribute> GetCustomAttributes(this ICustomAttributeProvider self, ref Collection<CustomAttribute> variable, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return variable = new Collection<CustomAttribute>();
			}
			return module.Read(ref variable, self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.ReadCustomAttributes(provider));
		}

		public static bool ContainsGenericParameter(this IGenericInstance self)
		{
			Collection<TypeReference> genericArguments = self.GenericArguments;
			for (int i = 0; i < genericArguments.Count; i++)
			{
				if (genericArguments[i].ContainsGenericParameter)
				{
					return true;
				}
			}
			return false;
		}

		public static void GenericInstanceFullName(this IGenericInstance self, StringBuilder builder)
		{
			builder.Append("<");
			Collection<TypeReference> genericArguments = self.GenericArguments;
			for (int i = 0; i < genericArguments.Count; i++)
			{
				if (i > 0)
				{
					builder.Append(",");
				}
				builder.Append(genericArguments[i].FullName);
			}
			builder.Append(">");
		}

		public static bool GetHasGenericParameters(this IGenericParameterProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (IGenericParameterProvider provider, MetadataReader reader) => reader.HasGenericParameters(provider));
			}
			return false;
		}

		public static Collection<GenericParameter> GetGenericParameters(this IGenericParameterProvider self, ref Collection<GenericParameter> collection, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return collection = new GenericParameterCollection(self);
			}
			return module.Read(ref collection, self, (IGenericParameterProvider provider, MetadataReader reader) => reader.ReadGenericParameters(provider));
		}

		public static bool GetHasMarshalInfo(this IMarshalInfoProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.HasMarshalInfo(provider));
			}
			return false;
		}

		public static MarshalInfo GetMarshalInfo(this IMarshalInfoProvider self, ref MarshalInfo variable, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return null;
			}
			return module.Read(ref variable, self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.ReadMarshalInfo(provider));
		}

		public static bool GetAttributes(this uint self, uint attributes)
		{
			return (self & attributes) != 0;
		}

		public static uint SetAttributes(this uint self, uint attributes, bool value)
		{
			if (value)
			{
				return self | attributes;
			}
			return self & ~attributes;
		}

		public static bool GetMaskedAttributes(this uint self, uint mask, uint attributes)
		{
			return (self & mask) == attributes;
		}

		public static uint SetMaskedAttributes(this uint self, uint mask, uint attributes, bool value)
		{
			if (value)
			{
				self &= ~mask;
				return self | attributes;
			}
			return self & ~(mask & attributes);
		}

		public static bool GetAttributes(this ushort self, ushort attributes)
		{
			return (self & attributes) != 0;
		}

		public static ushort SetAttributes(this ushort self, ushort attributes, bool value)
		{
			if (value)
			{
				return (ushort)(self | attributes);
			}
			return (ushort)(self & ~attributes);
		}

		public static bool GetMaskedAttributes(this ushort self, ushort mask, uint attributes)
		{
			return (self & mask) == attributes;
		}

		public static ushort SetMaskedAttributes(this ushort self, ushort mask, uint attributes, bool value)
		{
			if (value)
			{
				self = (ushort)(self & ~mask);
				return (ushort)(self | attributes);
			}
			return (ushort)(self & ~(mask & attributes));
		}

		public static bool HasImplicitThis(this IMethodSignature self)
		{
			if (self.HasThis)
			{
				return !self.ExplicitThis;
			}
			return false;
		}

		public static void MethodSignatureFullName(this IMethodSignature self, StringBuilder builder)
		{
			builder.Append("(");
			if (self.HasParameters)
			{
				Collection<ParameterDefinition> parameters = self.Parameters;
				for (int i = 0; i < parameters.Count; i++)
				{
					ParameterDefinition parameterDefinition = parameters[i];
					if (i > 0)
					{
						builder.Append(",");
					}
					if (parameterDefinition.ParameterType.IsSentinel)
					{
						builder.Append("...,");
					}
					builder.Append(parameterDefinition.ParameterType.FullName);
				}
			}
			builder.Append(")");
		}

		public static void CheckModule(ModuleDefinition module)
		{
			if (module == null)
			{
				throw new ArgumentNullException(Argument.module.ToString());
			}
		}

		public static bool TryGetAssemblyNameReference(this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
		{
			Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences;
			for (int i = 0; i < assemblyReferences.Count; i++)
			{
				AssemblyNameReference assemblyNameReference = assemblyReferences[i];
				if (Equals(name_reference, assemblyNameReference))
				{
					assembly_reference = assemblyNameReference;
					return true;
				}
			}
			assembly_reference = null;
			return false;
		}

		private static bool Equals(byte[] a, byte[] b)
		{
			if (a == b)
			{
				return true;
			}
			if (a == null)
			{
				return false;
			}
			if (a.Length != b.Length)
			{
				return false;
			}
			for (int i = 0; i < a.Length; i++)
			{
				if (a[i] != b[i])
				{
					return false;
				}
			}
			return true;
		}

		private static bool Equals<T>(T a, T b) where T : class, IEquatable<T>
		{
			if (a == b)
			{
				return true;
			}
			return a?.Equals(b) ?? false;
		}

		private static bool Equals(AssemblyNameReference a, AssemblyNameReference b)
		{
			if (a == b)
			{
				return true;
			}
			if (a.Name != b.Name)
			{
				return false;
			}
			if (!Equals(a.Version, b.Version))
			{
				return false;
			}
			if (a.Culture != b.Culture)
			{
				return false;
			}
			if (!Equals(a.PublicKeyToken, b.PublicKeyToken))
			{
				return false;
			}
			return true;
		}

		public static ParameterDefinition GetParameter(this Mono.Cecil.Cil.MethodBody self, int index)
		{
			MethodDefinition method = self.method;
			if (method.HasThis)
			{
				if (index == 0)
				{
					return self.ThisParameter;
				}
				index--;
			}
			Collection<ParameterDefinition> parameters = method.Parameters;
			if (index < 0 || index >= parameters.size)
			{
				return null;
			}
			return parameters[index];
		}

		public static VariableDefinition GetVariable(this Mono.Cecil.Cil.MethodBody self, int index)
		{
			Collection<VariableDefinition> variables = self.Variables;
			if (index < 0 || index >= variables.size)
			{
				return null;
			}
			return variables[index];
		}

		public static bool GetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics)
		{
			return (self.SemanticsAttributes & semantics) != 0;
		}

		public static void SetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics, bool value)
		{
			if (value)
			{
				self.SemanticsAttributes |= semantics;
			}
			else
			{
				self.SemanticsAttributes &= (MethodSemanticsAttributes)(ushort)(~(int)semantics);
			}
		}

		public static bool IsVarArg(this IMethodSignature self)
		{
			return self.CallingConvention == MethodCallingConvention.VarArg;
		}

		public static int GetSentinelPosition(this IMethodSignature self)
		{
			if (!self.HasParameters)
			{
				return -1;
			}
			Collection<ParameterDefinition> parameters = self.Parameters;
			for (int i = 0; i < parameters.Count; i++)
			{
				if (parameters[i].ParameterType.IsSentinel)
				{
					return i;
				}
			}
			return -1;
		}

		public static void CheckName(object name)
		{
			if (name == null)
			{
				throw new ArgumentNullException(Argument.name.ToString());
			}
		}

		public static void CheckName(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				throw new ArgumentNullOrEmptyException(Argument.name.ToString());
			}
		}

		public static void CheckFileName(string fileName)
		{
			if (string.IsNullOrEmpty(fileName))
			{
				throw new ArgumentNullOrEmptyException(Argument.fileName.ToString());
			}
		}

		public static void CheckFullName(string fullName)
		{
			if (string.IsNullOrEmpty(fullName))
			{
				throw new ArgumentNullOrEmptyException(Argument.fullName.ToString());
			}
		}

		public static void CheckStream(object stream)
		{
			if (stream == null)
			{
				throw new ArgumentNullException(Argument.stream.ToString());
			}
		}

		public static void CheckWriteSeek(Stream stream)
		{
			if (!stream.CanWrite || !stream.CanSeek)
			{
				throw new ArgumentException("Stream must be writable and seekable.");
			}
		}

		public static void CheckReadSeek(Stream stream)
		{
			if (!stream.CanRead || !stream.CanSeek)
			{
				throw new ArgumentException("Stream must be readable and seekable.");
			}
		}

		public static void CheckType(object type)
		{
			if (type == null)
			{
				throw new ArgumentNullException(Argument.type.ToString());
			}
		}

		public static void CheckType(object type, Argument argument)
		{
			if (type == null)
			{
				throw new ArgumentNullException(argument.ToString());
			}
		}

		public static void CheckField(object field)
		{
			if (field == null)
			{
				throw new ArgumentNullException(Argument.field.ToString());
			}
		}

		public static void CheckMethod(object method)
		{
			if (method == null)
			{
				throw new ArgumentNullException(Argument.method.ToString());
			}
		}

		public static void CheckParameters(object parameters)
		{
			if (parameters == null)
			{
				throw new ArgumentNullException(Argument.parameters.ToString());
			}
		}

		public static uint GetTimestamp()
		{
			return (uint)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
		}

		public static bool HasImage(this ModuleDefinition self)
		{
			return self?.HasImage ?? false;
		}

		public static string GetFileName(this Stream self)
		{
			if (!(self is FileStream fileStream))
			{
				return string.Empty;
			}
			return Path.GetFullPath(fileStream.Name);
		}

		public static void CopyTo(this Stream self, Stream target)
		{
			byte[] array = new byte[8192];
			int count;
			while ((count = self.Read(array, 0, array.Length)) > 0)
			{
				target.Write(array, 0, count);
			}
		}

		public static TargetRuntime ParseRuntime(this string self)
		{
			if (string.IsNullOrEmpty(self))
			{
				return TargetRuntime.Net_4_0;
			}
			switch (self[1])
			{
			case '1':
				if (self[3] != '0')
				{
					return TargetRuntime.Net_1_1;
				}
				return TargetRuntime.Net_1_0;
			case '2':
				return TargetRuntime.Net_2_0;
			default:
				return TargetRuntime.Net_4_0;
			}
		}

		public static string RuntimeVersionString(this TargetRuntime runtime)
		{
			return runtime switch
			{
				TargetRuntime.Net_1_0 => "v1.0.3705", 
				TargetRuntime.Net_1_1 => "v1.1.4322", 
				TargetRuntime.Net_2_0 => "v2.0.50727", 
				_ => "v4.0.30319", 
			};
		}

		public static bool IsWindowsMetadata(this ModuleDefinition module)
		{
			return module.MetadataKind != MetadataKind.Ecma335;
		}

		public static byte[] ReadAll(this Stream self)
		{
			MemoryStream memoryStream = new MemoryStream((int)self.Length);
			byte[] array = new byte[1024];
			int count;
			while ((count = self.Read(array, 0, array.Length)) != 0)
			{
				memoryStream.Write(array, 0, count);
			}
			return memoryStream.ToArray();
		}

		public static void Read(object o)
		{
		}

		public static bool GetHasSecurityDeclarations(this ISecurityDeclarationProvider self, ModuleDefinition module)
		{
			if (module.HasImage())
			{
				return module.Read(self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.HasSecurityDeclarations(provider));
			}
			return false;
		}

		public static Collection<SecurityDeclaration> GetSecurityDeclarations(this ISecurityDeclarationProvider self, ref Collection<SecurityDeclaration> variable, ModuleDefinition module)
		{
			if (!module.HasImage())
			{
				return variable = new Collection<SecurityDeclaration>();
			}
			return module.Read(ref variable, self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.ReadSecurityDeclarations(provider));
		}

		public static TypeReference GetEnumUnderlyingType(this TypeDefinition self)
		{
			Collection<FieldDefinition> fields = self.Fields;
			for (int i = 0; i < fields.Count; i++)
			{
				FieldDefinition fieldDefinition = fields[i];
				if (!fieldDefinition.IsStatic)
				{
					return fieldDefinition.FieldType;
				}
			}
			throw new ArgumentException();
		}

		public static TypeDefinition GetNestedType(this TypeDefinition self, string fullname)
		{
			if (!self.HasNestedTypes)
			{
				return null;
			}
			Collection<TypeDefinition> nestedTypes = self.NestedTypes;
			for (int i = 0; i < nestedTypes.Count; i++)
			{
				TypeDefinition typeDefinition = nestedTypes[i];
				if (typeDefinition.TypeFullName() == fullname)
				{
					return typeDefinition;
				}
			}
			return null;
		}

		public static bool IsPrimitive(this ElementType self)
		{
			switch (self)
			{
			case ElementType.Boolean:
			case ElementType.Char:
			case ElementType.I1:
			case ElementType.U1:
			case ElementType.I2:
			case ElementType.U2:
			case ElementType.I4:
			case ElementType.U4:
			case ElementType.I8:
			case ElementType.U8:
			case ElementType.R4:
			case ElementType.R8:
			case ElementType.I:
			case ElementType.U:
				return true;
			default:
				return false;
			}
		}

		public static string TypeFullName(this TypeReference self)
		{
			if (!string.IsNullOrEmpty(self.Namespace))
			{
				return self.Namespace + "." + self.Name;
			}
			return self.Name;
		}

		public static bool IsTypeOf(this TypeReference self, string @namespace, string name)
		{
			if (self.Name == name)
			{
				return self.Namespace == @namespace;
			}
			return false;
		}

		public static bool IsTypeSpecification(this TypeReference type)
		{
			switch (type.etype)
			{
			case ElementType.Ptr:
			case ElementType.ByRef:
			case ElementType.Var:
			case ElementType.Array:
			case ElementType.GenericInst:
			case ElementType.FnPtr:
			case ElementType.SzArray:
			case ElementType.MVar:
			case ElementType.CModReqD:
			case ElementType.CModOpt:
			case ElementType.Sentinel:
			case ElementType.Pinned:
				return true;
			default:
				return false;
			}
		}

		public static TypeDefinition CheckedResolve(this TypeReference self)
		{
			return self.Resolve() ?? throw new ResolutionException(self);
		}

		public static bool TryGetCoreLibraryReference(this ModuleDefinition module, out AssemblyNameReference reference)
		{
			Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences;
			for (int i = 0; i < assemblyReferences.Count; i++)
			{
				reference = assemblyReferences[i];
				if (IsCoreLibrary(reference))
				{
					return true;
				}
			}
			reference = null;
			return false;
		}

		public static bool IsCoreLibrary(this ModuleDefinition module)
		{
			if (module.Assembly == null)
			{
				return false;
			}
			if (!IsCoreLibrary(module.Assembly.Name))
			{
				return false;
			}
			if (module.HasImage && module.Read(module, (ModuleDefinition m, MetadataReader reader) => reader.image.GetTableLength(Table.AssemblyRef) > 0))
			{
				return false;
			}
			return true;
		}

		public static void KnownValueType(this TypeReference type)
		{
			if (!type.IsDefinition)
			{
				type.IsValueType = true;
			}
		}

		private static bool IsCoreLibrary(AssemblyNameReference reference)
		{
			string name = reference.Name;
			switch (name)
			{
			default:
				return name == "netstandard";
			case "mscorlib":
			case "System.Runtime":
			case "System.Private.CoreLib":
				return true;
			}
		}

		public static ImageDebugHeaderEntry GetCodeViewEntry(this ImageDebugHeader header)
		{
			return header.GetEntry(ImageDebugType.CodeView);
		}

		public static ImageDebugHeaderEntry GetDeterministicEntry(this ImageDebugHeader header)
		{
			return header.GetEntry(ImageDebugType.Deterministic);
		}

		public static ImageDebugHeader AddDeterministicEntry(this ImageDebugHeader header)
		{
			ImageDebugDirectory directory = default(ImageDebugDirectory);
			directory.Type = ImageDebugType.Deterministic;
			ImageDebugHeaderEntry imageDebugHeaderEntry = new ImageDebugHeaderEntry(directory, Empty<byte>.Array);
			if (header == null)
			{
				return new ImageDebugHeader(imageDebugHeaderEntry);
			}
			ImageDebugHeaderEntry[] array = new ImageDebugHeaderEntry[header.Entries.Length + 1];
			Array.Copy(header.Entries, array, header.Entries.Length);
			array[^1] = imageDebugHeaderEntry;
			return new ImageDebugHeader(array);
		}

		public static ImageDebugHeaderEntry GetEmbeddedPortablePdbEntry(this ImageDebugHeader header)
		{
			return header.GetEntry(ImageDebugType.EmbeddedPortablePdb);
		}

		private static ImageDebugHeaderEntry GetEntry(this ImageDebugHeader header, ImageDebugType type)
		{
			if (!header.HasEntries)
			{
				return null;
			}
			for (int i = 0; i < header.Entries.Length; i++)
			{
				ImageDebugHeaderEntry imageDebugHeaderEntry = header.Entries[i];
				if (imageDebugHeaderEntry.Directory.Type == type)
				{
					return imageDebugHeaderEntry;
				}
			}
			return null;
		}

		public static string GetPdbFileName(string assemblyFileName)
		{
			return Path.ChangeExtension(assemblyFileName, ".pdb");
		}

		public static string GetMdbFileName(string assemblyFileName)
		{
			return assemblyFileName + ".mdb";
		}

		public static bool IsPortablePdb(string fileName)
		{
			using FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
			return IsPortablePdb(stream);
		}

		public static bool IsPortablePdb(Stream stream)
		{
			if (stream.Length < 4)
			{
				return false;
			}
			long position = stream.Position;
			try
			{
				return new BinaryReader(stream).ReadUInt32() == 1112167234;
			}
			finally
			{
				stream.Position = position;
			}
		}

		public static uint ReadCompressedUInt32(this byte[] data, ref int position)
		{
			uint result;
			if ((data[position] & 0x80) == 0)
			{
				result = data[position];
				position++;
			}
			else if ((data[position] & 0x40) == 0)
			{
				result = (uint)((data[position] & -129) << 8);
				result |= data[position + 1];
				position += 2;
			}
			else
			{
				result = (uint)((data[position] & -193) << 24);
				result |= (uint)(data[position + 1] << 16);
				result |= (uint)(data[position + 2] << 8);
				result |= data[position + 3];
				position += 4;
			}
			return result;
		}

		public static MetadataToken GetMetadataToken(this CodedIndex self, uint data)
		{
			uint rid;
			TokenType type;
			switch (self)
			{
			case CodedIndex.TypeDefOrRef:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_006d;
				case 2u:
					goto IL_0078;
				default:
					goto end_IL_0001;
				}
				type = TokenType.TypeDef;
				goto IL_05b3;
			case CodedIndex.HasConstant:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_00ad;
				case 2u:
					goto IL_00b8;
				default:
					goto end_IL_0001;
				}
				type = TokenType.Field;
				goto IL_05b3;
			case CodedIndex.HasCustomAttribute:
				rid = data >> 5;
				switch (data & 0x1F)
				{
				case 0u:
					break;
				case 1u:
					goto IL_013a;
				case 2u:
					goto IL_0145;
				case 3u:
					goto IL_0150;
				case 4u:
					goto IL_015b;
				case 5u:
					goto IL_0166;
				case 6u:
					goto IL_0171;
				case 7u:
					goto IL_017c;
				case 8u:
					goto IL_0183;
				case 9u:
					goto IL_018e;
				case 10u:
					goto IL_0199;
				case 11u:
					goto IL_01a4;
				case 12u:
					goto IL_01af;
				case 13u:
					goto IL_01ba;
				case 14u:
					goto IL_01c5;
				case 15u:
					goto IL_01d0;
				case 16u:
					goto IL_01db;
				case 17u:
					goto IL_01e6;
				case 18u:
					goto IL_01f1;
				case 19u:
					goto IL_01fc;
				case 20u:
					goto IL_0207;
				case 21u:
					goto IL_0212;
				default:
					goto end_IL_0001;
				}
				type = TokenType.Method;
				goto IL_05b3;
			case CodedIndex.HasFieldMarshal:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Param;
				}
				else
				{
					type = TokenType.Field;
				}
				goto IL_05b3;
			}
			case CodedIndex.HasDeclSecurity:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_0271;
				case 2u:
					goto IL_027c;
				default:
					goto end_IL_0001;
				}
				type = TokenType.TypeDef;
				goto IL_05b3;
			case CodedIndex.MemberRefParent:
				rid = data >> 3;
				switch (data & 7)
				{
				case 0u:
					break;
				case 1u:
					goto IL_02b9;
				case 2u:
					goto IL_02c4;
				case 3u:
					goto IL_02cf;
				case 4u:
					goto IL_02da;
				default:
					goto end_IL_0001;
				}
				type = TokenType.TypeDef;
				goto IL_05b3;
			case CodedIndex.HasSemantics:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Property;
				}
				else
				{
					type = TokenType.Event;
				}
				goto IL_05b3;
			}
			case CodedIndex.MethodDefOrRef:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.MemberRef;
				}
				else
				{
					type = TokenType.Method;
				}
				goto IL_05b3;
			}
			case CodedIndex.MemberForwarded:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Method;
				}
				else
				{
					type = TokenType.Field;
				}
				goto IL_05b3;
			}
			case CodedIndex.Implementation:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_038d;
				case 2u:
					goto IL_0398;
				default:
					goto end_IL_0001;
				}
				type = TokenType.File;
				goto IL_05b3;
			case CodedIndex.CustomAttributeType:
			{
				rid = data >> 3;
				uint num = data & 7u;
				if (num != 2)
				{
					if (num != 3)
					{
						break;
					}
					type = TokenType.MemberRef;
				}
				else
				{
					type = TokenType.Method;
				}
				goto IL_05b3;
			}
			case CodedIndex.ResolutionScope:
				rid = data >> 2;
				switch (data & 3)
				{
				case 0u:
					break;
				case 1u:
					goto IL_03f8;
				case 2u:
					goto IL_0403;
				case 3u:
					goto IL_040e;
				default:
					goto end_IL_0001;
				}
				type = TokenType.Module;
				goto IL_05b3;
			case CodedIndex.TypeOrMethodDef:
			{
				rid = data >> 1;
				uint num = data & 1u;
				if (num != 0)
				{
					if (num != 1)
					{
						break;
					}
					type = TokenType.Method;
				}
				else
				{
					type = TokenType.TypeDef;
				}
				goto IL_05b3;
			}
			case CodedIndex.HasCustomDebugInformation:
				{
					rid = data >> 5;
					switch (data & 0x1F)
					{
					case 0u:
						break;
					case 1u:
						goto IL_04ce;
					case 2u:
						goto IL_04d9;
					case 3u:
						goto IL_04e4;
					case 4u:
						goto IL_04ef;
					case 5u:
						goto IL_04fa;
					case 6u:
						goto IL_0505;
					case 7u:
						goto IL_0510;
					case 8u:
						goto IL_0517;
					case 9u:
						goto IL_0522;
					case 10u:
						goto IL_052d;
					case 11u:
						goto IL_0535;
					case 12u:
						goto IL_053d;
					case 13u:
						goto IL_0545;
					case 14u:
						goto IL_054d;
					case 15u:
						goto IL_0555;
					case 16u:
						goto IL_055d;
					case 17u:
						goto IL_0565;
					case 18u:
						goto IL_056d;
					case 19u:
						goto IL_0575;
					case 20u:
						goto IL_057d;
					case 21u:
						goto IL_0585;
					case 22u:
						goto IL_058d;
					case 23u:
						goto IL_0595;
					case 24u:
						goto IL_059d;
					case 25u:
						goto IL_05a5;
					case 26u:
						goto IL_05ad;
					default:
						goto end_IL_0001;
					}
					type = TokenType.Method;
					goto IL_05b3;
				}
				IL_05ad:
				type = TokenType.ImportScope;
				goto IL_05b3;
				IL_05a5:
				type = TokenType.LocalConstant;
				goto IL_05b3;
				IL_059d:
				type = TokenType.LocalVariable;
				goto IL_05b3;
				IL_0595:
				type = TokenType.LocalScope;
				goto IL_05b3;
				IL_058d:
				type = TokenType.Document;
				goto IL_05b3;
				IL_0585:
				type = TokenType.MethodSpec;
				goto IL_05b3;
				IL_057d:
				type = TokenType.GenericParamConstraint;
				goto IL_05b3;
				IL_0575:
				type = TokenType.GenericParam;
				goto IL_05b3;
				IL_056d:
				type = TokenType.ManifestResource;
				goto IL_05b3;
				IL_0565:
				type = TokenType.ExportedType;
				goto IL_05b3;
				IL_055d:
				type = TokenType.File;
				goto IL_05b3;
				IL_0555:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_054d:
				type = TokenType.Assembly;
				goto IL_05b3;
				IL_0545:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_053d:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_0535:
				type = TokenType.Signature;
				goto IL_05b3;
				IL_052d:
				type = TokenType.Event;
				goto IL_05b3;
				IL_0522:
				type = TokenType.Property;
				goto IL_05b3;
				IL_0517:
				type = TokenType.Permission;
				goto IL_05b3;
				IL_0510:
				type = TokenType.Module;
				goto IL_05b3;
				IL_0505:
				type = TokenType.MemberRef;
				goto IL_05b3;
				IL_04fa:
				type = TokenType.InterfaceImpl;
				goto IL_05b3;
				IL_04ef:
				type = TokenType.Param;
				goto IL_05b3;
				IL_04e4:
				type = TokenType.TypeDef;
				goto IL_05b3;
				IL_04d9:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_04ce:
				type = TokenType.Field;
				goto IL_05b3;
				IL_01db:
				type = TokenType.File;
				goto IL_05b3;
				IL_01d0:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_01ba:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_01c5:
				type = TokenType.Assembly;
				goto IL_05b3;
				IL_040e:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_0403:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_03f8:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_01af:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_01a4:
				type = TokenType.Signature;
				goto IL_05b3;
				IL_018e:
				type = TokenType.Property;
				goto IL_05b3;
				IL_0199:
				type = TokenType.Event;
				goto IL_05b3;
				IL_0398:
				type = TokenType.ExportedType;
				goto IL_05b3;
				IL_038d:
				type = TokenType.AssemblyRef;
				goto IL_05b3;
				IL_0183:
				type = TokenType.Permission;
				goto IL_05b3;
				IL_017c:
				type = TokenType.Module;
				goto IL_05b3;
				IL_0166:
				type = TokenType.InterfaceImpl;
				goto IL_05b3;
				IL_0171:
				type = TokenType.MemberRef;
				goto IL_05b3;
				IL_015b:
				type = TokenType.Param;
				goto IL_05b3;
				IL_0145:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_0150:
				type = TokenType.TypeDef;
				goto IL_05b3;
				IL_013a:
				type = TokenType.Field;
				goto IL_05b3;
				IL_006d:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_02da:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_02cf:
				type = TokenType.Method;
				goto IL_05b3;
				IL_02c4:
				type = TokenType.ModuleRef;
				goto IL_05b3;
				IL_02b9:
				type = TokenType.TypeRef;
				goto IL_05b3;
				IL_00b8:
				type = TokenType.Property;
				goto IL_05b3;
				IL_027c:
				type = TokenType.Assembly;
				goto IL_05b3;
				IL_0271:
				type = TokenType.Method;
				goto IL_05b3;
				IL_00ad:
				type = TokenType.Param;
				goto IL_05b3;
				IL_05b3:
				return new MetadataToken(type, rid);
				IL_0078:
				type = TokenType.TypeSpec;
				goto IL_05b3;
				IL_0212:
				type = TokenType.MethodSpec;
				goto IL_05b3;
				IL_0207:
				type = TokenType.GenericParamConstraint;
				goto IL_05b3;
				IL_01fc:
				type = TokenType.GenericParam;
				goto IL_05b3;
				IL_01f1:
				type = TokenType.ManifestResource;
				goto IL_05b3;
				IL_01e6:
				type = TokenType.ExportedType;
				goto IL_05b3;
				end_IL_0001:
				break;
			}
			return MetadataToken.Zero;
		}

		public static uint CompressMetadataToken(this CodedIndex self, MetadataToken token)
		{
			uint result = 0u;
			if (token.RID == 0)
			{
				return result;
			}
			switch (self)
			{
			case CodedIndex.TypeDefOrRef:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.TypeRef:
					return result | 1u;
				case TokenType.TypeSpec:
					return result | 2u;
				}
				break;
			case CodedIndex.HasConstant:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.Field:
					return result | 0u;
				case TokenType.Param:
					return result | 1u;
				case TokenType.Property:
					return result | 2u;
				}
				break;
			case CodedIndex.HasCustomAttribute:
				result = token.RID << 5;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 0u;
				case TokenType.Field:
					return result | 1u;
				case TokenType.TypeRef:
					return result | 2u;
				case TokenType.TypeDef:
					return result | 3u;
				case TokenType.Param:
					return result | 4u;
				case TokenType.InterfaceImpl:
					return result | 5u;
				case TokenType.MemberRef:
					return result | 6u;
				case TokenType.Module:
					return result | 7u;
				case TokenType.Permission:
					return result | 8u;
				case TokenType.Property:
					return result | 9u;
				case TokenType.Event:
					return result | 0xAu;
				case TokenType.Signature:
					return result | 0xBu;
				case TokenType.ModuleRef:
					return result | 0xCu;
				case TokenType.TypeSpec:
					return result | 0xDu;
				case TokenType.Assembly:
					return result | 0xEu;
				case TokenType.AssemblyRef:
					return result | 0xFu;
				case TokenType.File:
					return result | 0x10u;
				case TokenType.ExportedType:
					return result | 0x11u;
				case TokenType.ManifestResource:
					return result | 0x12u;
				case TokenType.GenericParam:
					return result | 0x13u;
				case TokenType.GenericParamConstraint:
					return result | 0x14u;
				case TokenType.MethodSpec:
					return result | 0x15u;
				}
				break;
			case CodedIndex.HasFieldMarshal:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Field:
					return result | 0u;
				case TokenType.Param:
					return result | 1u;
				}
				break;
			case CodedIndex.HasDeclSecurity:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.Method:
					return result | 1u;
				case TokenType.Assembly:
					return result | 2u;
				}
				break;
			case CodedIndex.MemberRefParent:
				result = token.RID << 3;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.TypeRef:
					return result | 1u;
				case TokenType.ModuleRef:
					return result | 2u;
				case TokenType.Method:
					return result | 3u;
				case TokenType.TypeSpec:
					return result | 4u;
				}
				break;
			case CodedIndex.HasSemantics:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Event:
					return result | 0u;
				case TokenType.Property:
					return result | 1u;
				}
				break;
			case CodedIndex.MethodDefOrRef:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 0u;
				case TokenType.MemberRef:
					return result | 1u;
				}
				break;
			case CodedIndex.MemberForwarded:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.Field:
					return result | 0u;
				case TokenType.Method:
					return result | 1u;
				}
				break;
			case CodedIndex.Implementation:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.File:
					return result | 0u;
				case TokenType.AssemblyRef:
					return result | 1u;
				case TokenType.ExportedType:
					return result | 2u;
				}
				break;
			case CodedIndex.CustomAttributeType:
				result = token.RID << 3;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 2u;
				case TokenType.MemberRef:
					return result | 3u;
				}
				break;
			case CodedIndex.ResolutionScope:
				result = token.RID << 2;
				switch (token.TokenType)
				{
				case TokenType.Module:
					return result | 0u;
				case TokenType.ModuleRef:
					return result | 1u;
				case TokenType.AssemblyRef:
					return result | 2u;
				case TokenType.TypeRef:
					return result | 3u;
				}
				break;
			case CodedIndex.TypeOrMethodDef:
				result = token.RID << 1;
				switch (token.TokenType)
				{
				case TokenType.TypeDef:
					return result | 0u;
				case TokenType.Method:
					return result | 1u;
				}
				break;
			case CodedIndex.HasCustomDebugInformation:
				result = token.RID << 5;
				switch (token.TokenType)
				{
				case TokenType.Method:
					return result | 0u;
				case TokenType.Field:
					return result | 1u;
				case TokenType.TypeRef:
					return result | 2u;
				case TokenType.TypeDef:
					return result | 3u;
				case TokenType.Param:
					return result | 4u;
				case TokenType.InterfaceImpl:
					return result | 5u;
				case TokenType.MemberRef:
					return result | 6u;
				case TokenType.Module:
					return result | 7u;
				case TokenType.Permission:
					return result | 8u;
				case TokenType.Property:
					return result | 9u;
				case TokenType.Event:
					return result | 0xAu;
				case TokenType.Signature:
					return result | 0xBu;
				case TokenType.ModuleRef:
					return result | 0xCu;
				case TokenType.TypeSpec:
					return result | 0xDu;
				case TokenType.Assembly:
					return result | 0xEu;
				case TokenType.AssemblyRef:
					return result | 0xFu;
				case TokenType.File:
					return result | 0x10u;
				case TokenType.ExportedType:
					return result | 0x11u;
				case TokenType.ManifestResource:
					return result | 0x12u;
				case TokenType.GenericParam:
					return result | 0x13u;
				case TokenType.GenericParamConstraint:
					return result | 0x14u;
				case TokenType.MethodSpec:
					return result | 0x15u;
				case TokenType.Document:
					return result | 0x16u;
				case TokenType.LocalScope:
					return result | 0x17u;
				case TokenType.LocalVariable:
					return result | 0x18u;
				case TokenType.LocalConstant:
					return result | 0x19u;
				case TokenType.ImportScope:
					return result | 0x1Au;
				}
				break;
			}
			throw new ArgumentException();
		}

		public static int GetSize(this CodedIndex self, Func<Table, int> counter)
		{
			int num;
			Table[] array;
			switch (self)
			{
			case CodedIndex.TypeDefOrRef:
				num = 2;
				array = new Table[3]
				{
					Table.TypeDef,
					Table.TypeRef,
					Table.TypeSpec
				};
				break;
			case CodedIndex.HasConstant:
				num = 2;
				array = new Table[3]
				{
					Table.Field,
					Table.Param,
					Table.Property
				};
				break;
			case CodedIndex.HasCustomAttribute:
				num = 5;
				array = new Table[22]
				{
					Table.Method,
					Table.Field,
					Table.TypeRef,
					Table.TypeDef,
					Table.Param,
					Table.InterfaceImpl,
					Table.MemberRef,
					Table.Module,
					Table.DeclSecurity,
					Table.Property,
					Table.Event,
					Table.StandAloneSig,
					Table.ModuleRef,
					Table.TypeSpec,
					Table.Assembly,
					Table.AssemblyRef,
					Table.File,
					Table.ExportedType,
					Table.ManifestResource,
					Table.GenericParam,
					Table.GenericParamConstraint,
					Table.MethodSpec
				};
				break;
			case CodedIndex.HasFieldMarshal:
				num = 1;
				array = new Table[2]
				{
					Table.Field,
					Table.Param
				};
				break;
			case CodedIndex.HasDeclSecurity:
				num = 2;
				array = new Table[3]
				{
					Table.TypeDef,
					Table.Method,
					Table.Assembly
				};
				break;
			case CodedIndex.MemberRefParent:
				num = 3;
				array = new Table[5]
				{
					Table.TypeDef,
					Table.TypeRef,
					Table.ModuleRef,
					Table.Method,
					Table.TypeSpec
				};
				break;
			case CodedIndex.HasSemantics:
				num = 1;
				array = new Table[2]
				{
					Table.Event,
					Table.Property
				};
				break;
			case CodedIndex.MethodDefOrRef:
				num = 1;
				array = new Table[2]
				{
					Table.Method,
					Table.MemberRef
				};
				break;
			case CodedIndex.MemberForwarded:
				num = 1;
				array = new Table[2]
				{
					Table.Field,
					Table.Method
				};
				break;
			case CodedIndex.Implementation:
				num = 2;
				array = new Table[3]
				{
					Table.File,
					Table.AssemblyRef,
					Table.ExportedType
				};
				break;
			case CodedIndex.CustomAttributeType:
				num = 3;
				array = new Table[2]
				{
					Table.Method,
					Table.MemberRef
				};
				break;
			case CodedIndex.ResolutionScope:
				num = 2;
				array = new Table[4]
				{
					Table.Module,
					Table.ModuleRef,
					Table.AssemblyRef,
					Table.TypeRef
				};
				break;
			case CodedIndex.TypeOrMethodDef:
				num = 1;
				array = new Table[2]
				{
					Table.TypeDef,
					Table.Method
				};
				break;
			case CodedIndex.HasCustomDebugInformation:
				num = 5;
				array = new Table[27]
				{
					Table.Method,
					Table.Field,
					Table.TypeRef,
					Table.TypeDef,
					Table.Param,
					Table.InterfaceImpl,
					Table.MemberRef,
					Table.Module,
					Table.DeclSecurity,
					Table.Property,
					Table.Event,
					Table.StandAloneSig,
					Table.ModuleRef,
					Table.TypeSpec,
					Table.Assembly,
					Table.AssemblyRef,
					Table.File,
					Table.ExportedType,
					Table.ManifestResource,
					Table.GenericParam,
					Table.GenericParamConstraint,
					Table.MethodSpec,
					Table.Document,
					Table.LocalScope,
					Table.LocalVariable,
					Table.LocalConstant,
					Table.ImportScope
				};
				break;
			default:
				throw new ArgumentException();
			}
			int num2 = 0;
			for (int i = 0; i < array.Length; i++)
			{
				num2 = Math.Max(counter(array[i]), num2);
			}
			if (num2 >= 1 << 16 - num)
			{
				return 4;
			}
			return 2;
		}

		public static RSA CreateRSA(this StrongNameKeyPair key_pair)
		{
			if (!TryGetKeyContainer(key_pair, out var key, out var key_container))
			{
				return CryptoConvert.FromCapiKeyBlob(key);
			}
			return new RSACryptoServiceProvider(new CspParameters
			{
				Flags = CspProviderFlags.UseMachineKeyStore,
				KeyContainerName = key_container,
				KeyNumber = 2
			});
		}

		private static bool TryGetKeyContainer(ISerializable key_pair, out byte[] key, out string key_container)
		{
			SerializationInfo serializationInfo = new SerializationInfo(typeof(StrongNameKeyPair), new FormatterConverter());
			key_pair.GetObjectData(serializationInfo, default(StreamingContext));
			key = (byte[])serializationInfo.GetValue("_keyPairArray", typeof(byte[]));
			key_container = serializationInfo.GetString("_keyPairContainer");
			return key_container != null;
		}
	}
	public struct ArrayDimension
	{
		private int? lower_bound;

		private int? upper_bound;

		public int? LowerBound
		{
			get
			{
				return lower_bound;
			}
			set
			{
				lower_bound = value;
			}
		}

		public int? UpperBound
		{
			get
			{
				return upper_bound;
			}
			set
			{
				upper_bound = value;
			}
		}

		public bool IsSized
		{
			get
			{
				if (!lower_bound.HasValue)
				{
					return upper_bound.HasValue;
				}
				return true;
			}
		}

		public ArrayDimension(int? lowerBound, int? upperBound)
		{
			lower_bound = lowerBound;
			upper_bound = upperBound;
		}

		public override string ToString()
		{
			if (IsSized)
			{
				return lower_bound + "..." + upper_bound;
			}
			return string.Empty;
		}
	}
	public sealed class ArrayType : TypeSpecification
	{
		private Collection<ArrayDimension> dimensions;

		public Collection<ArrayDimension> Dimensions
		{
			get
			{
				if (dimensions != null)
				{
					return dimensions;
				}
				dimensions = new Collection<ArrayDimension>();
				dimensions.Add(default(ArrayDimension));
				return dimensions;
			}
		}

		public int Rank
		{
			get
			{
				if (dimensions != null)
				{
					return dimensions.Count;
				}
				return 1;
			}
		}

		public bool IsVector
		{
			get
			{
				if (dimensions == null)
				{
					return true;
				}
				if (dimensions.Count > 1)
				{
					return false;
				}
				return !dimensions[0].IsSized;
			}
		}

		public override bool IsValueType
		{
			get
			{
				return false;
			}
			set
			{
				throw new InvalidOperationException();
			}
		}

		public override string Name => base.Name + Suffix;

		public override string FullName => base.FullName + Suffix;

		private string Suffix
		{
			get
			{
				if (IsVector)
				{
					return "[]";
				}
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append("[");
				for (int i = 0; i < dimensions.Count; i++)
				{
					if (i > 0)
					{
						stringBuilder.Append(",");
					}
					stringBuilder.Append(dimensions[i].ToString());
				}
				stringBuilder.Append("]");
				return stringBuilder.ToString();
			}
		}

		public override bool IsArray => true;

		public ArrayType(TypeReference type)
			: base(type)
		{
			Mixin.CheckType(type);
			etype = Mono.Cecil.Metadata.ElementType.Array;
		}

		public ArrayType(TypeReference type, int rank)
			: this(type)
		{
			Mixin.CheckType(type);
			if (rank != 1)
			{
				dimensions = new Collection<ArrayDimension>(rank);
				for (int i = 0; i < rank; i++)
				{
					dimensions.Add(default(ArrayDimension));
				}
				etype = Mono.Cecil.Metadata.ElementType.Array;
			}
		}
	}
	public sealed class AssemblyDefinition : ICustomAttributeProvider, IMetadataTokenProvider, ISecurityDeclarationProvider, IDisposable
	{
		private AssemblyNameDefinition name;

		internal ModuleDefinition main_module;

		private Collection<ModuleDefinition> modules;

		private Collection<CustomAttribute> custom_attributes;

		private Collection<SecurityDeclaration> security_declarations;

		public AssemblyNameDefinition Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}

		public string FullName
		{
			get
			{
				if (name == null)
				{
					return string.Empty;
				}
				return name.FullName;
			}
		}

		public MetadataToken MetadataToken
		{
			get
			{
				return new MetadataToken(TokenType.Assembly, 1);
			}
			set
			{
			}
		}

		public Collection<ModuleDefinition> Modules
		{
			get
			{
				if (modules != null)
				{
					return modules;
				}
				if (main_module.HasImage)
				{
					return main_module.Read(ref modules, this, (AssemblyDefinition _, MetadataReader reader) => reader.ReadModules());
				}
				return modules = new Collection<ModuleDefinition>(1) { main_module };
			}
		}

		public ModuleDefinition MainModule => main_module;

		public MethodDefinition EntryPoint
		{
			get
			{
				return main_module.EntryPoint;
			}
			set
			{
				main_module.EntryPoint = value;
			}
		}

		public bool HasCustomAttributes
		{
			get
			{
				if (custom_attributes != null)
				{
					return custom_attributes.Count > 0;
				}
				return this.GetHasCustomAttributes(main_module);
			}
		}

		public Collection<CustomAttribute> CustomAttributes => custom_attributes ?? this.GetCustomAttributes(ref custom_attributes, main_module);

		public bool HasSecurityDeclarations
		{
			get
			{
				if (security_declarations != null)
				{
					return security_declarations.Count > 0;
				}
				return this.GetHasSecurityDeclarations(main_module);
			}
		}

		public Collection<SecurityDeclaration> SecurityDeclarations => security_declarations ?? this.GetSecurityDeclarations(ref security_declarations, main_module);

		internal AssemblyDefinition()
		{
		}

		public void Dispose()
		{
			if (modules == null)
			{
				main_module.Dispose();
				return;
			}
			Collection<ModuleDefinition> collection = Modules;
			for (int i = 0; i < collection.Count; i++)
			{
				collection[i].Dispose();
			}
		}

		public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind)
		{
			return CreateAssembly(assemblyName, moduleName, new ModuleParameters
			{
				Kind = kind
			});
		}

		public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleParameters parameters)
		{
			if (assemblyName == null)
			{
				throw new ArgumentNullException("assemblyName");
			}
			if (moduleName == null)
			{
				throw new ArgumentNullException("moduleName");
			}
			Mixin.CheckParameters(parameters);
			if (parameters.Kind == ModuleKind.NetModule)
			{
				throw new ArgumentException("kind");
			}
			AssemblyDefinition assembly = ModuleDefinition.CreateModule(moduleName, parameters).Assembly;
			assembly.Name = assemblyName;
			return assembly;
		}

		public static AssemblyDefinition ReadAssembly(string fileName)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(fileName));
		}

		public static AssemblyDefinition ReadAssembly(string fileName, ReaderParameters parameters)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(fileName, parameters));
		}

		public static AssemblyDefinition ReadAssembly(Stream stream)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(stream));
		}

		public static AssemblyDefinition ReadAssembly(Stream stream, ReaderParameters parameters)
		{
			return ReadAssembly(ModuleDefinition.ReadModule(stream, parameters));
		}

		private static AssemblyDefinition ReadAssembly(ModuleDefinition module)
		{
			return module.Assembly ?? throw new ArgumentException();
		}

		public void Write(string fileName)
		{
			Write(fileName, new WriterParameters());
		}

		public void Write(string fileName, WriterParameters parameters)
		{
			main_module.Write(fileName, parameters);
		}

		public void Write()
		{
			main_module.Write();
		}

		public void Write(WriterParameters parameters)
		{
			main_module.Write(parameters);
		}

		public void Write(Stream stream)
		{
			Write(stream, new WriterParameters());
		}

		public void Write(Stream stream, WriterParameters parameters)
		{
			main_module.Write(stream, parameters);
		}

		public override string ToString()
		{
			return FullName;
		}
	}
	[Flags]
	public enum AssemblyAttributes : uint
	{
		PublicKey = 1u,
		SideBySideCompatible = 0u,
		Retargetable = 0x100u,
		WindowsRuntime = 0x200u,
		DisableJITCompileOptimizer = 0x4000u,
		EnableJITCompileTracking = 0x8000u
	}
	public enum AssemblyHashAlgorithm : uint
	{
		None = 0u,
		Reserved = 32771u,
		SHA1 = 32772u
	}
	public sealed class AssemblyLinkedResource : Resource
	{
		private AssemblyNameReference reference;

		public AssemblyNameReference Assembly
		{
			get
			{
				return reference;
			}
			set
			{
				reference = value;
			}
		}

		public override ResourceType ResourceType => ResourceType.AssemblyLinked;

		public AssemblyLinkedResource(string name, ManifestResourceAttributes flags)
			: base(name, flags)
		{
		}

		public AssemblyLinkedResource(string name, ManifestResourceAttributes flags, AssemblyNameReference reference)
			: base(name, flags)
		{
			this.reference = reference;
		}
	}
	public sealed class AssemblyNameDefinition : AssemblyNameReference
	{
		public override byte[] Hash => Empty<byte>.Array;

		internal AssemblyNameDefinition()
		{
			token = new MetadataToken(TokenType.Assembly, 1);
		}

		public AssemblyNameDefinition(string name, Version version)
			: base(name, version)
		{
			token = new MetadataToken(TokenType.Assembly, 1);
		}
	}
	public class AssemblyNameReference : IMetadataScope, IMetadataTokenProvider
	{
		private string name;

		private string culture;

		private Version version;

		private uint attributes;

		private byte[] public_key;

		private byte[] public_key_token;

		private AssemblyHashAlgorithm hash_algorithm;

		private byte[] hash;

		internal MetadataToken token;

		private string full_name;

		public string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
				full_name = null;
			}
		}

		public string Culture
		{
			get
			{
				return culture;
			}
			set
			{
				culture = value;
				full_name = null;
			}
		}

		public Version Version
		{
			get
			{
				return version;
			}
			set
			{
				version = Mixin.CheckVersion(value);
				full_name = null;
			}
		}

		public AssemblyAttributes Attributes
		{
			get
			{
				return (AssemblyAttributes)attributes;
			}
			set
			{
				attributes = (uint)value;
			}
		}

		public bool HasPublicKey
		{
			get
			{
				return attributes.GetAttributes(1u);
			}
			set
			{
				attributes = attributes.SetAttributes(1u, value);
			}
		}

		public bool IsSideBySideCompatible
		{
			get
			{
				return attributes.GetAttributes(0u);
			}
			set
			{
				attributes = attributes.SetAttributes(0u, value);
			}
		}

		public bool IsRetargetable
		{
			get
			{
				return attributes.GetAttributes(256u);
			}
			set
			{
				attributes = attributes.SetAttributes(256u, value);
			}
		}

		public bool IsWindowsRuntime
		{
			get
			{
				return attributes.GetAttributes(512u);
			}
			set
			{
				attributes = attributes.SetAttributes(512u, value);
			}
		}

		public byte[] PublicKey
		{
			get
			{
				return public_key ?? Empty<byte>.Array;
			}
			set
			{
				public_key = value;
				HasPublicKey = !public_key.IsNullOrEmpty();
				public_key_token = Empty<byte>.Array;
				full_name = null;
			}
		}

		public byte[] PublicKeyToken
		{
			get
			{
				if (public_key_token.IsNullOrEmpty() && !public_key.IsNullOrEmpty())
				{
					byte[] array = HashPublicKey();
					byte[] array2 = new byte[8];
					Array.Copy(array, array.Length - 8, array2, 0, 8);
					Array.Reverse((Array)array2, 0, 8);
					public_key_token = array2;
				}
				return public_key_token ?? Empty<byte>.Array;
			}
			set
			{
				public_key_token = value;
				full_name = null;
			}
		}

		public virtual MetadataScopeType MetadataScopeType => MetadataScopeType.AssemblyNameReference;

		public string FullName
		{
			get
			{
				if (full_name != null)
				{
					return full_name;
				}
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append(name);
				stringBuilder.Append(", ");
				stringBuilder.Append("Version=");
				stringBuilder.Append(version.ToString(4));
				stringBuilder.Append(", ");
				stringBuilder.Append("Culture=");
				stringBuilder.Append(string.IsNullOrEmpty(culture) ? "neutral" : culture);
				stringBuilder.Append(", ");
				stringBuilder.Append("PublicKeyToken=");
				byte[] publicKeyToken = PublicKeyToken;
				if (!publicKeyToken.IsNullOrEmpty() && publicKeyToken.Length != 0)
				{
					for (int i = 0; i < publicKeyToken.Length; i++)
					{
						stringBuilder.Append(publicKeyToken[i].ToString("x2"));
					}
				}
				else
				{
					stringBuilder.Append("null");
				}
				if (IsRetargetable)
				{
					stringBuilder.Append(", ");
					stringBuilder.Append("Retargetable=Yes");
				}
				return full_name = stringBuilder.ToString();
			}
		}

		public AssemblyHashAlgorithm HashAlgorithm
		{
			get
			{
				return hash_algorithm;
			}
			set
			{
				hash_algorithm = value;
			}
		}

		public virtual byte[] Hash
		{
			get
			{
				return hash;
			}
			set
			{
				hash = value;
			}
		}

		public MetadataToken MetadataToken
		{
			get
			{
				return token;
			}
			set
			{
				token = value;
			}
		}

		private byte[] HashPublicKey()
		{
			AssemblyHashAlgorithm assemblyHashAlgorithm = hash_algorithm;
			HashAlgorithm hashAlgorithm = ((assemblyHashAlgorithm != AssemblyHashAlgorithm.Reserved) ? ((HashAlgorithm)SHA1.Create()) : ((HashAlgorithm)MD5.Create()));
			using (hashAlgorithm)
			{
				return hashAlgorithm.ComputeHash(public_key);
			}
		}

		public static AssemblyNameReference Parse(string fullName)
		{
			if (fullName == null)
			{
				throw new ArgumentNullException("fullName");
			}
			if (fullName.Length == 0)
			{
				throw new ArgumentException("Name can not be empty");
			}
			AssemblyNameReference assemblyNameReference = new AssemblyNameReference();
			string[] array = fullName.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (i == 0)
				{
					assemblyNameReference.Name = text;
					continue;
				}
				string[] array2 = text.Split(new char[1] { '=' });
				if (array2.Length != 2)
				{
					throw new ArgumentException("Malformed name");
				}
				switch (array2[0].ToLowerInvariant())
				{
				case "version":
					assemblyNameReference.Version = new Version(array2[1]);
					break;
				case "culture":
					assemblyNameReference.Culture = ((array2[1] == "neutral") ? "" : array2[1]);
					break;
				case "publickeytoken":
				{
					string text2 = array2[1];
					if (!(text2 == "null"))
					{
						assemblyNameReference.PublicKeyToken = new byte[text2.Length / 2];
						for (int j = 0; j < assemblyNameReference.PublicKeyToken.Length; j++)
						{
							assemblyNameReference.PublicKeyToken[j] = byte.Parse(text2.Substring(j * 2, 2), NumberStyles.HexNumber);
						}
					}
					break;
				}
				}
			}
			return assemblyNameReference;
		}

		internal AssemblyNameReference()
		{
			version = Mixin.ZeroVersion;
			token = new MetadataToken(TokenType.AssemblyRef);
		}

		public AssemblyNameReference(string name, Version version)
		{
			Mixin.CheckName(name);
			this.name = name;
			this.version = Mixin.CheckVersion(version);
			hash_algorithm = AssemblyHashAlgorithm.None;
			token = new MetadataToken(TokenType.AssemblyRef);
		}

		public override string ToString()
		{
			return FullName;
		}
	}
	internal abstract class ModuleReader
	{
		protected readonly ModuleDefinition module;

		protected ModuleReader(Image image, ReadingMode mode)
		{
			module = new ModuleDefinition(image);
			module.ReadingMode = mode;
		}

		protected abstract void ReadModule();

		public abstract void ReadSymbols(ModuleDefinition module);

		protected void ReadModuleManifest(MetadataReader reader)
		{
			reader.Populate(module);
			ReadAssembly(reader);
		}

		private void ReadAssembly(MetadataReader reader)
		{
			AssemblyNameDefinition assemblyNameDefinition = reader.ReadAssemblyNameDefinition();
			if (assemblyNameDefinition == null)
			{
				module.kind = ModuleKind.NetModule;
				return;
			}
			AssemblyDefinition assemblyDefinition = new AssemblyDefinition();
			assemblyDefinition.Name = assemblyNameDefinition;
			module.assembly = assemblyDefinition;
			assemblyDefinition.main_module = module;
		}

		public static ModuleDefinition CreateModule(Image image, ReaderParameters parameters)
		{
			ModuleReader moduleReader = CreateModuleReader(image, parameters.ReadingMode);
			ModuleDefinition moduleDefinition = moduleReader.module;
			if (parameters.assembly_resolver != null)
			{
				moduleDefinition.assembly_resolver = Disposable.NotOwned(parameters.assembly_resolver);
			}
			if (parameters.metadata_resolver != null)
			{
				moduleDefinition.metadata_resolver = parameters.metadata_resolver;
			}
			if (parameters.metadata_importer_provider != null)
			{
				moduleDefinition.metadata_importer = parameters.metadata_importer_provider.GetMetadataImporter(moduleDefinition);
			}
			if (parameters.reflection_importer_provider != null)
			{
				moduleDefinition.reflection_importer = parameters.reflection_importer_provider.GetReflectionImporter(moduleDefinition);
			}
			GetMetadataKind(moduleDefinition, parameters);
			moduleReader.ReadModule();
			ReadSymbols(moduleDefinition, parameters);
			moduleReader.ReadSymbols(moduleDefinition);
			if (parameters.ReadingMode == ReadingMode.Immediate)
			{
				moduleDefinition.MetadataSystem.Clear();
			}
			return moduleDefinition;
		}

		private static void ReadSymbols(ModuleDefinition module, ReaderParameters parameters)
		{
			ISymbolReaderProvider symbolReaderProvider = parameters.SymbolReaderProvider;
			if (symbolReaderProvider == null && parameters.ReadSymbols)
			{
				symbolReaderProvider = new DefaultSymbolReaderProvider();
			}
			if (symbolReaderProvider != null)
			{
				module.SymbolReaderProvider = symbolReaderProvider;
				ISymbolReader symbolReader = ((parameters.SymbolStream != null) ? symbolReaderProvider.GetSymbolReader(module, parameters.SymbolStream) : symbolReaderProvider.GetSymbolReader(module, module.FileName));
				if (symbolReader != null)
				{
					try
					{
						module.ReadSymbols(symbolReader, parameters.ThrowIfSymbolsAreNotMatching);
					}
					catch (Exception)
					{
						symbolReader.Dispose();
						throw;
					}
				}
			}
			if (module.Image.HasDebugTables())
			{
				module.ReadSymbols(new PortablePdbReader(module.Image, module));
			}
		}

		private static void GetMetadataKind(ModuleDefinition module, ReaderParameters parameters)
		{
			if (!parameters.ApplyWindowsRuntimeProjections)
			{
				module.MetadataKind = MetadataKind.Ecma335;
				return;
			}
			string runtimeVersion = module.RuntimeVersion;
			if (!runtimeVersion.Contains("WindowsRuntime"))
			{
				module.MetadataKind = MetadataKind.Ecma335;
			}
			else if (runtimeVersion.Contains("CLR"))
			{
				module.MetadataKind = MetadataKind.ManagedWindowsMetadata;
			}
			else
			{
				module.MetadataKind = MetadataKind.WindowsMetadata;
			}
		}

		private static ModuleReader CreateModuleReader(Image image, ReadingMode mode)
		{
			return mode switch
			{
				ReadingMode.Immediate => new ImmediateModuleReader(image), 
				ReadingMode.Deferred => new DeferredModuleReader(image), 
				_ => throw new ArgumentException(), 
			};
		}
	}
	internal sealed class ImmediateModuleReader : ModuleReader
	{
		private bool resolve_attributes;

		public ImmediateModuleReader(Image image)
			: base(image, ReadingMode.Immediate)
		{
		}

		protected override void ReadModule()
		{
			module.Read(module, delegate(ModuleDefinition module, MetadataReader reader)
			{
				ReadModuleManifest(reader);
				ReadModule(module, resolve_attributes: true);
			});
		}

		public void ReadModule(ModuleDefinition module, bool resolve_attributes)
		{
			this.resolve_attributes = resolve_attributes;
			if (module.HasAssemblyReferences)
			{
				Mixin.Read(module.AssemblyReferences);
			}
			if (module.HasResources)
			{
				Mixin.Read(module.Resources);
			}
			if (module.HasModuleReferences)
			{
				Mixin.Read(module.ModuleReferences);
			}
			if (module.HasTypes)
			{
				ReadTypes(module.Types);
			}
			if (module.HasExportedTypes)
			{
				Mixin.Read(module.ExportedTypes);
			}
			ReadCustomAttributes(module);
			AssemblyDefinition assembly = module.Assembly;
			if (assembly != null)
			{
				ReadCustomAttributes(assembly);
				ReadSecurityDeclarations(assembly);
			}
		}

		private void ReadTypes(Collection<TypeDefinition> types)
		{
			for (int i = 0; i < types.Count; i++)
			{
				ReadType(types[i]);
			}
		}

		private void ReadType(TypeDefinition type)
		{
			ReadGenericParameters(type);
			if (type.HasInterfaces)
			{
				ReadInterfaces(type);
			}
			if (type.HasNestedTypes)
			{
				ReadTypes(type.NestedTypes);
			}
			if (type.HasLayoutInfo)
			{
				Mixin.Read(type.ClassSize);
			}
			if (type.HasFields)
			{
				ReadFields(type);
			}
			if (type.HasMethods)
			{
				ReadMethods(type);
			}
			if (type.HasProperties)
			{
				ReadProperties(type);
			}
			if (type.HasEvents)
			{
				ReadEvents(type);
			}
			ReadSecurityDeclarations(type);
			ReadCustomAttributes(type);
		}

		private void ReadInterfaces(TypeDefinition type)
		{
			Collection<InterfaceImplementation> interfaces = type.Interfaces;
			for (int i = 0; i < interfaces.Count; i++)
			{
				ReadCustomAttributes(interfaces[i]);
			}
		}

		private void ReadGenericParameters(IGenericParameterProvider provider)
		{
			if (!provider.HasGenericParameters)
			{
				return;
			}
			Collection<GenericParameter> genericParameters = provider.GenericParameters;
			for (int i = 0; i < genericParameters.Count; i++)
			{
				GenericParameter genericParameter = genericParameters[i];
				if (genericParameter.HasConstraints)
				{
					Mixin.Read(genericParameter.Constraints);
				}
				ReadCustomAttributes(genericParameter);
			}
		}

		private void ReadSecurityDeclarations(ISecurityDeclarationProvider provider)
		{
			if (!provider.HasSecurityDeclarations)
			{
				return;
			}
			Collection<SecurityDeclaration> securityDeclarations = provider.SecurityDeclarations;
			if (resolve_attributes)
			{
				for (int i = 0; i < securityDeclarations.Count; i++)
				{
					Mixin.Read(securityDeclarations[i].SecurityAttributes);
				}
			}
		}

		private void ReadCustomAttributes(ICustomAttributeProvider provider)
		{
			if (!provider.HasCustomAttributes)
			{
				return;
			}
			Collection<CustomAttribute> customAttributes = provider.CustomAttributes;
			if (resolve_attributes)
			{
				for (int i = 0; i < customAttributes.Count; i++)
				{
					Mixin.Read(customAttributes[i].ConstructorArguments);
				}
			}
		}

		private void ReadFields(TypeDefinition type)
		{
			Collection<FieldDefinition> fields = type.Fields;
			for (int i = 0; i < fields.Count; i++)
			{
				FieldDefinition fieldDefinition = fields[i];
				if (fieldDefinition.HasConstant)
				{
					Mixin.Read(fieldDefinition.Constant);
				}
				if (fieldDefinition.HasLayoutInfo)
				{
					Mixin.Read(fieldDefinition.Offset);
				}
				if (fieldDefinition.RVA > 0)
				{
					Mixin.Read(fieldDefinition.InitialValue);
				}
				if (fieldDefinition.HasMarshalInfo)
				{
					Mixin.Read(fieldDefinition.MarshalInfo);
				}
				ReadCustomAttributes(fieldDefinition);
			}
		}

		private void ReadMethods(TypeDefinition type)
		{
			Collection<MethodDefinition> methods = type.Methods;
			for (int i = 0; i < methods.Count; i++)
			{
				MethodDefinition methodDefinition = methods[i];
				ReadGenericParameters(methodDefinition);
				if (methodDefinition.HasParameters)
				{
					ReadParameters(methodDefinition);
				}
				if (methodDefinition.HasOverrides)
				{
					Mixin.Read(methodDefinition.Overrides);
				}
				if (methodDefinition.IsPInvokeImpl)
				{
					Mixin.Read(methodDefinition.PInvokeInfo);
				}
				ReadSecurityDeclarations(methodDefinition);
				ReadCustomAttributes(methodDefinition);
				MethodReturnType methodReturnType = methodDefinition.MethodReturnType;
				if (methodReturnType.HasConstant)
				{
					Mixin.Read(methodReturnType.Constant);
				}
				if (methodReturnType.HasMarshalInfo)
				{
					Mixin.Read(methodReturnType.MarshalInfo);
				}
				ReadCustomAttributes(methodReturnType);
			}
		}

		private void ReadParameters(MethodDefinition method)
		{
			Collection<ParameterDefinition> parameters = method.Parameters;
			for (int i = 0; i < parameters.Count; i++)
			{
				ParameterDefinition parameterDefinition = parameters[i];
				if (parameterDefinition.HasConstant)
				{
					Mixin.Read(parameterDefinition.Constant);
				}
				if (parameterDefinition.HasMarshalInfo)
				{
					Mixin.Read(parameterDefinition.MarshalInfo);
				}
				ReadCustomAttributes(parameterDefinition);
			}
		}

		private void ReadProperties(TypeDefinition type)
		{
			Collection<PropertyDefinition> properties = type.Properties;
			for (int i = 0; i < properties.Count; i++)
			{
				PropertyDefinition propertyDefinition = properties[i];
				Mixin.Read(propertyDefinition.GetMethod);
				if (propertyDefinition.HasConstant)
				{
					Mixin.Read(propertyDefinition.Constant);
				}
				ReadCustomAttributes(propertyDefinition);
			}
		}

		private void ReadEvents(TypeDefinition type)
		{
			Collection<EventDefinition> events = type.Events;
			for (int i = 0; i < events.Count; i++)
			{
				EventDefinition eventDefinition = events[i];
				Mixin.Read(eventDefinition.AddMethod);
				ReadCustomAttributes(eventDefinition);
			}
		}

		public override void ReadSymbols(ModuleDefinition module)
		{
			if (module.symbol_reader != null)
			{
				ReadTypesSymbols(module.Types, module.symbol_reader);
			}
		}

		private void ReadTypesSymbols(Collection<TypeDefinition> types, ISymbolReader symbol_reader)
		{
			for (int i = 0; i < types.Count; i++)
			{
				TypeDefinition typeDefinition = types[i];
				if (typeDefinition.HasNestedTypes)
				{
					ReadTypesSymbols(typeDefinition.NestedTypes, symbol_reader);
				}
				if (typeDefinition.HasMethods)
				{
					ReadMethodsSymbols(typeDefinition, symbol_reader);
				}
			}
		}

		private void ReadMethodsSymbols(TypeDefinition type, ISymbolReader symbol_reader)
		{
			Collection<MethodDefinition> methods = type.Methods;
			for (int i = 0; i < methods.Count; i++)
			{
				MethodDefinition methodDefinition = methods[i];
				if (methodDefinition.HasBody && methodDefinition.token.RID != 0 && methodDefinition.debug_info == null)
				{
					methodDefinition.debug_info = symbol_reader.Read(methodDefinition);
				}
			}
		}
	}
	internal sealed class DeferredModuleReader : ModuleReader
	{
		public DeferredModuleReader(Image image)
			: base(image, ReadingMode.Deferred)
		{
		}

		protected override void ReadModule()
		{
			module.Read(module, delegate(ModuleDefinition _, MetadataReader reader)
			{
				ReadModuleManifest(reader);
			});
		}

		public override void ReadSymbols(ModuleDefinition module)
		{
		}
	}
	internal sealed class MetadataReader : ByteBuffer
	{
		internal readonly Image image;

		internal readonly ModuleDefinition module;

		internal readonly MetadataSystem metadata;

		internal CodeReader code;

		internal IGenericContext context;

		private readonly MetadataReader metadata_reader;

		public MetadataReader(ModuleDefinition module)
			: base(module.Image.TableHeap.data)
		{
			image = module.Image;
			this.module = module;
			metadata = module.MetadataSystem;
			code = new CodeReader(this);
		}

		public MetadataReader(Image image, ModuleDefinition module, MetadataReader metadata_reader)
			: base(image.TableHeap.data)
		{
			this.image = image;
			this.module = module;
			metadata = module.MetadataSystem;
			this.metadata_reader = metadata_reader;
		}

		private int GetCodedIndexSize(CodedIndex index)
		{
			return image.GetCodedIndexSize(index);
		}

		private uint ReadByIndexSize(int size)
		{
			if (size == 4)
			{
				return ReadUInt32();
			}
			return ReadUInt16();
		}

		private byte[] ReadBlob()
		{
			BlobHeap blobHeap = image.BlobHeap;
			if (blobHeap == null)
			{
				position += 2;
				return Empty<byte>.Array;
			}
			return blobHeap.Read(ReadBlobIndex());
		}

		private byte[] ReadBlob(uint signature)
		{
			BlobHeap blobHeap = image.BlobHeap;
			if (blobHeap == null)
			{
				return Empty<byte>.Array;
			}
			return blobHeap.Read(signature);
		}

		private uint ReadBlobIndex()
		{
			return ReadByIndexSize(image.BlobHeap?.IndexSize ?? 2);
		}

		private void GetBlobView(uint signature, out byte[] blob, out int index, out int count)
		{
			BlobHeap blobHeap = image.BlobHeap;
			if (blobHeap == null)
			{
				blob = null;
				index = (count = 0);
			}
			else
			{
				blobHeap.GetView(signature, out blob, out index, out count);
			}
		}

		private string ReadString()
		{
			return image.StringHeap.Read(ReadByIndexSize(image.StringHeap.IndexSize));
		}

		private uint ReadStringIndex()
		{
			return ReadByIndexSize(image.StringHeap.IndexSize);
		}

		private Guid ReadGuid()
		{
			return image.GuidHeap.Read(ReadByIndexSize(image.GuidHeap.IndexSize));
		}

		private uint ReadTableIndex(Table table)
		{
			return ReadByIndexSize(image.GetTableIndexSize(table));
		}

		private MetadataToken ReadMetadataToken(CodedIndex index)
		{
			return index.GetMetadataToken(ReadByIndexSize(GetCodedIndexSize(index)));
		}

		private int MoveTo(Table table)
		{
			TableInformation tableInformation = image.TableHeap[table];
			if (tableInformation.Length != 0)
			{
				position = (int)tableInformation.Offset;
			}
			return (int)tableInformation.Length;
		}

		private bool MoveTo(Table table, uint row)
		{
			TableInformation tableInformation = image.TableHeap[table];
			uint num = tableInformation.Length;
			if (num == 0 || row > num)
			{
				return false;
			}
			position = (int)(tableInformation.Offset + tableInformation.RowSize * (row - 1));
			return true;
		}

		public AssemblyNameDefinition ReadAssemblyNameDefinition()
		{
			if (MoveTo(Table.Assembly) == 0)
			{
				return null;
			}
			AssemblyNameDefinition assemblyNameDefinition = new AssemblyNameDefinition();
			assemblyNameDefinition.HashAlgorithm = (AssemblyHashAlgorithm)ReadUInt32();
			PopulateVersionAndFlags(assemblyNameDefinition);
			assemblyNameDefinition.PublicKey = ReadBlob();
			PopulateNameAndCulture(assemblyNameDefinition);
			return assemblyNameDefinition;
		}

		public ModuleDefinition Populate(ModuleDefinition module)
		{
			if (MoveTo(Table.Module) == 0)
			{
				return module;
			}
			Advance(2);
			module.Name = ReadString();
			module.Mvid = ReadGuid();
			return module;
		}

		private void InitializeAssemblyReferences()
		{
			if (metadata.AssemblyReferences != null)
			{
				return;
			}
			int num = MoveTo(Table.AssemblyRef);
			AssemblyNameReference[] array = (metadata.AssemblyReferences = new AssemblyNameReference[num]);
			for (uint num2 = 0u; num2 < num; num2++)
			{
				AssemblyNameReference assemblyNameReference = new AssemblyNameReference();
				assemblyNameReference.token = new MetadataToken(TokenType.AssemblyRef, num2 + 1);
				PopulateVersionAndFlags(assemblyNameReference);
				byte[] array2 = ReadBlob();
				if (assemblyNameReference.HasPublicKey)
				{
					assemblyNameReference.PublicKey = array2;
				}
				else
				{
					assemblyNameReference.PublicKeyToken = array2;
				}
				PopulateNameAndCulture(assemblyNameReference);
				assemblyNameReference.Hash = ReadBlob();
				array[num2] = assemblyNameReference;
			}
		}

		public Collection<AssemblyNameReference> ReadAssemblyReferences()
		{
			InitializeAssemblyReferences();
			Collection<AssemblyNameReference> collection = new Collection<AssemblyNameReference>(metadata.AssemblyReferences);
			if (module.IsWindowsMetadata())
			{
				module.Projections.AddVirtualReferences(collection);
			}
			return collection;
		}

		public MethodDefinition ReadEntryPoint()
		{
			if (module.Image.EntryPointToken == 0)
			{
				return null;
			}
			return GetMethodDefinition(new MetadataToken(module.Image.EntryPointToken).RID);
		}

		public Collection<ModuleDefinition> ReadModules()
		{
			Collection<ModuleDefinition> collection = new Collection<ModuleDefinition>(1);
			collection.Add(module);
			int num = MoveTo(Table.File);
			for (uint num2 = 1u; num2 <= num; num2++)
			{
				uint num3 = ReadUInt32();
				string name = ReadString();
				ReadBlobIndex();
				if (num3 == 0)
				{
					ReaderParameters parameters = new ReaderParameters
					{
						ReadingMode = module.ReadingMode,
						SymbolReaderProvider = module.SymbolReaderProvider,
						AssemblyResolver = module.AssemblyResolver
					};
					collection.Add(ModuleDefinition.ReadModule(GetModuleFileName(name), parameters));
				}
			}
			return collection;
		}

		private string GetModuleFileName(string name)
		{
			if (module.FileName == null)
			{
				throw new NotSupportedException();
			}
			return Path.Combine(Path.GetDirectoryName(module.FileName), name);
		}

		private void InitializeModuleReferences()
		{
			if (metadata.ModuleReferences == null)
			{
				int num = MoveTo(Table.ModuleRef);
				ModuleReference[] array = (metadata.ModuleReferences = new ModuleReference[num]);
				for (uint num2 = 0u; num2 < num; num2++)
				{
					ModuleReference moduleReference = new ModuleReference(ReadString());
					moduleReference.token = new MetadataToken(TokenType.ModuleRef, num2 + 1);
					array[num2] = moduleReference;
				}
			}
		}

		public Collection<ModuleReference> ReadModuleReferences()
		{
			InitializeModuleReferences();
			return new Collection<ModuleReference>(metadata.ModuleReferences);
		}

		public bool HasFileResource()
		{
			int num = MoveTo(Table.File);
			if (num == 0)
			{
				return false;
			}
			for (uint num2 = 1u; num2 <= num; num2++)
			{
				if (ReadFileRecord(num2).Col1 == FileAttributes.ContainsNoMetaData)
				{
					return true;
				}
			}
			return false;
		}

		public Collection<Resource> ReadResources()
		{
			int num = MoveTo(Table.ManifestResource);
			Collection<Resource> collection = new Collection<Resource>(num);
			for (int i = 1; i <= num; i++)
			{
				uint offset = ReadUInt32();
				ManifestResourceAttributes manifestResourceAttributes = (ManifestResourceAttributes)ReadUInt32();
				string name = ReadString();
				MetadataToken scope = ReadMetadataToken(CodedIndex.Implementation);
				Resource item;
				if (scope.RID == 0)
				{
					item = new EmbeddedResource(name, manifestResourceAttributes, offset, this);
				}
				else if (scope.TokenType == TokenType.AssemblyRef)
				{
					item = new AssemblyLinkedResource(name, manifestResourceAttributes)
					{
						Assembly = (AssemblyNameReference)GetTypeReferenceScope(scope)
					};
				}
				else
				{
					if (scope.TokenType != TokenType.File)
					{
						continue;
					}
					Row<FileAttributes, string, uint> row = ReadFileRecord(scope.RID);
					item = new LinkedResource(name, manifestResourceAttributes)
					{
						File = row.Col2,
						hash = ReadBlob(row.Col3)
					};
				}
				collection.Add(item);
			}
			return collection;
		}

		private Row<FileAttributes, string, uint> ReadFileRecord(uint rid)
		{
			int num = position;
			if (!MoveTo(Table.File, rid))
			{
				throw new ArgumentException();
			}
			Row<FileAttributes, string, uint> result = new Row<FileAttributes, string, uint>((FileAttributes)ReadUInt32(), ReadString(), ReadBlobIndex());
			position = num;
			return result;
		}

		public byte[] GetManagedResource(uint offset)
		{
			return image.GetReaderAt(image.Resources.VirtualAddress, offset, delegate(uint o, BinaryStreamReader reader)
			{
				reader.Advance((int)o);
				return reader.ReadBytes(reader.ReadInt32());
			}) ?? Empty<byte>.Array;
		}

		private void PopulateVersionAndFlags(AssemblyNameReference name)
		{
			name.Version = new Version(ReadUInt16(), ReadUInt16(), ReadUInt16(), ReadUInt16());
			name.Attributes = (AssemblyAttributes)ReadUInt32();
		}

		private void PopulateNameAndCulture(AssemblyNameReference name)
		{
			name.Name = ReadString();
			name.Culture = ReadString();
		}

		public TypeDefinitionCollection ReadTypes()
		{
			InitializeTypeDefinitions();
			TypeDefinition[] types = metadata.Types;
			int capacity = types.Length - metadata.NestedTypes.Count;
			TypeDefinitionCollection typeDefinitionCollection = new TypeDefinitionCollection(module, capacity);
			foreach (TypeDefinition typeDefinition in types)
			{
				if (!IsNested(typeDefinition.Attributes))
				{
					typeDefinitionCollection.Add(typeDefinition);
				}
			}
			if (image.HasTable(Table.MethodPtr) || image.HasTable(Table.FieldPtr))
			{
				CompleteTypes();
			}
			return typeDefinitionCollection;
		}

		private void CompleteTypes()
		{
			TypeDefinition[] types = metadata.Types;
			foreach (TypeDefinition obj in types)
			{
				Mixin.Read(obj.Fields);
				Mixin.Read(obj.Methods);
			}
		}

		private void InitializeTypeDefinitions()
		{
			if (metadata.Types != null)
			{
				return;
			}
			InitializeNestedTypes();
			InitializeFields();
			InitializeMethods();
			int num = MoveTo(Table.TypeDef);
			TypeDefinition[] array = (metadata.Types = new TypeDefinition[num]);
			for (uint num2 = 0u; num2 < num; num2++)
			{
				if (array[num2] == null)
				{
					array[num2] = ReadType(num2 + 1);
				}
			}
			if (module.IsWindowsMetadata())
			{
				for (uint num3 = 0u; num3 < num; num3++)
				{
					WindowsRuntimeProjections.Project(array[num3]);
				}
			}
		}

		private static bool IsNested(TypeAttributes attributes)
		{
			switch (attributes & TypeAttributes.VisibilityMask)
			{
			case TypeAttributes.NestedPublic:
			case TypeAttributes.NestedPrivate:
			case TypeAttributes.NestedFamily:
			case TypeAttributes.NestedAssembly:
			case TypeAttributes.NestedFamANDAssem:
			case TypeAttributes.VisibilityMask:
				return true;
			default:
				return false;
			}
		}

		public bool HasNestedTypes(TypeDefinition type)
		{
			InitializeNestedTypes();
			if (!metadata.TryGetNestedTypeMapping(type, out var mapping))
			{
				return false;
			}
			return mapping.Count > 0;
		}

		public Collection<TypeDefinition> ReadNestedTypes(TypeDefinition type)
		{
			InitializeNestedTypes();
			if (!metadata.TryGetNestedTypeMapping(type, out var mapping))
			{
				return new MemberDefinitionCollection<TypeDefinition>(type);
			}
			MemberDefinitionCollection<TypeDefinition> memberDefinitionCollection = new MemberDefinitionCollection<TypeDefinition>(type, mapping.Count);
			for (int i = 0; i < mapping.Count; i++)
			{
				TypeDefinition typeDefinition = GetTypeDefinition(mapping[i]);
				if (typeDefinition != null)
				{
					memberDefinitionCollection.Add(typeDefinition);
				}
			}
			metadata.RemoveNestedTypeMapping(type);
			return memberDefinitionCollection;
		}

		private void InitializeNestedTypes()
		{
			if (metadata.NestedTypes != null)
			{
				return;
			}
			int num = MoveTo(Table.NestedClass);
			metadata.NestedTypes = new Dictionary<uint, Collection<uint>>(num);
			metadata.ReverseNestedTypes = new Dictionary<uint, uint>(num);
			if (num != 0)
			{
				for (int i = 1; i <= num; i++)
				{
					uint nested = ReadTableIndex(Table.TypeDef);
					uint declaring = ReadTableIndex(Table.TypeDef);
					AddNestedMapping(declaring, nested);
				}
			}
		}

		private void AddNestedMapping(uint declaring, uint nested)
		{
			metadata.SetNestedTypeMapping(declaring, AddMapping(metadata.NestedTypes, declaring, nested));
			metadata.SetReverseNestedTypeMapping(nested, declaring);
		}

		private static Collection<TValue> AddMapping<TKey, TValue>(Dictionary<TKey, Collection<TValue>> cache, TKey key, TValue value)
		{
			if (!cache.TryGetValue(key, out var value2))
			{
				value2 = new Collection<TValue>();
			}
			value2.Add(value);
			return value2;
		}

		private TypeDefinition ReadType(uint rid)
		{
			if (!MoveTo(Table.TypeDef, rid))
			{
				return null;
			}
			TypeAttributes attributes = (TypeAttributes)ReadUInt32();
			string name = ReadString();
			TypeDefinition typeDefinition = new TypeDefinition(ReadString(), name, attributes);
			typeDefinition.token = new MetadataToken(TokenType.TypeDef, rid);
			typeDefinition.scope = module;
			typeDefinition.module = module;
			metadata.AddTypeDefinition(typeDefinition);
			context = typeDefinition;
			typeDefinition.BaseType = GetTypeDefOrRef(ReadMetadataToken(CodedIndex.TypeDefOrRef));
			typeDefinition.fields_range = ReadListRange(rid, Table.TypeDef, Table.Field);
			typeDefinition.methods_range = ReadListRange(rid, Table.TypeDef, Table.Method);
			if (IsNested(attributes))
			{
				typeDefinition.DeclaringType = GetNestedTypeDeclaringType(typeDefinition);
			}
			return typeDefinition;
		}

		private TypeDefinition GetNestedTypeDeclaringType(TypeDefinition type)
		{
			if (!metadata.TryGetReverseNestedTypeMapping(type, out var declaring))
			{
				return null;
			}
			metadata.RemoveReverseNestedTypeMapping(type);
			return GetTypeDefinition(declaring);
		}

		private Range ReadListRange(uint current_index, Table current, Table target)
		{
			Range result = default(Range);
			uint num = ReadTableIndex(target);
			if (num == 0)
			{
				return result;
			}
			TableInformation tableInformation = image.TableHeap[current];
			uint num2;
			if (current_index == tableInformation.Length)
			{
				num2 = image.TableHeap[target].Length + 1;
			}
			else
			{
				int num3 = position;
				position += (int)(tableInformation.RowSize - image.GetTableIndexSize(target));
				num2 = ReadTableIndex(target);
				position = num3;
			}
			result.Start = num;
			result.Length = num2 - num;
			return result;
		}

		public Row<short, int> ReadTypeLayout(TypeDefinition type)
		{
			InitializeTypeLayouts();
			uint rID = type.token.RID;
			if (!metadata.ClassLayouts.TryGetValue(rID, out var value))
			{
				return new Row<short, int>(-1, -1);
			}
			type.PackingSize = (short)value.Col1;
			type.ClassSize = (int)value.Col2;
			metadata.ClassLayouts.Remove(rID);
			return new Row<short, int>((short)value.Col1, (int)value.Col2);
		}

		private void InitializeTypeLayouts()
		{
			if (metadata.ClassLayouts == null)
			{
				int num = MoveTo(Table.ClassLayout);
				Dictionary<uint, Row<ushort, uint>> dictionary = (metadata.ClassLayouts = new Dictionary<uint, Row<ushort, uint>>(num));
				for (uint num2 = 0u; 

FrozenDevv-ModPack-1.1.0/BepInEx/core/Mono.Cecil.Mdb.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil.Mdb")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyVersion("0.10.4.0")]
namespace Mono.CompilerServices.SymbolWriter
{
	public class MonoSymbolFileException : Exception
	{
		public MonoSymbolFileException()
		{
		}

		public MonoSymbolFileException(string message, params object[] args)
			: base(string.Format(message, args))
		{
		}

		public MonoSymbolFileException(string message, Exception innerException)
			: base(message, innerException)
		{
		}
	}
	internal sealed class MyBinaryWriter : BinaryWriter
	{
		public MyBinaryWriter(Stream stream)
			: base(stream)
		{
		}

		public void WriteLeb128(int value)
		{
			Write7BitEncodedInt(value);
		}
	}
	internal class MyBinaryReader : BinaryReader
	{
		public MyBinaryReader(Stream stream)
			: base(stream)
		{
		}

		public int ReadLeb128()
		{
			return Read7BitEncodedInt();
		}

		public string ReadString(int offset)
		{
			long position = BaseStream.Position;
			BaseStream.Position = offset;
			string result = ReadString();
			BaseStream.Position = position;
			return result;
		}
	}
	public interface ISourceFile
	{
		SourceFileEntry Entry { get; }
	}
	public interface ICompileUnit
	{
		CompileUnitEntry Entry { get; }
	}
	public interface IMethodDef
	{
		string Name { get; }

		int Token { get; }
	}
	public class MonoSymbolFile : IDisposable
	{
		private List<MethodEntry> methods = new List<MethodEntry>();

		private List<SourceFileEntry> sources = new List<SourceFileEntry>();

		private List<CompileUnitEntry> comp_units = new List<CompileUnitEntry>();

		private Dictionary<int, AnonymousScopeEntry> anonymous_scopes;

		private OffsetTable ot;

		private int last_type_index;

		private int last_method_index;

		private int last_namespace_index;

		public readonly int MajorVersion = 50;

		public readonly int MinorVersion;

		public int NumLineNumbers;

		private MyBinaryReader reader;

		private Dictionary<int, SourceFileEntry> source_file_hash;

		private Dictionary<int, CompileUnitEntry> compile_unit_hash;

		private List<MethodEntry> method_list;

		private Dictionary<int, MethodEntry> method_token_hash;

		private Dictionary<string, int> source_name_hash;

		private Guid guid;

		internal int LineNumberCount;

		internal int LocalCount;

		internal int StringSize;

		internal int LineNumberSize;

		internal int ExtendedLineNumberSize;

		public int CompileUnitCount => ot.CompileUnitCount;

		public int SourceCount => ot.SourceCount;

		public int MethodCount => ot.MethodCount;

		public int TypeCount => ot.TypeCount;

		public int AnonymousScopeCount => ot.AnonymousScopeCount;

		public int NamespaceCount => last_namespace_index;

		public Guid Guid => guid;

		public OffsetTable OffsetTable => ot;

		public SourceFileEntry[] Sources
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				SourceFileEntry[] array = new SourceFileEntry[SourceCount];
				for (int i = 0; i < SourceCount; i++)
				{
					array[i] = GetSourceFile(i + 1);
				}
				return array;
			}
		}

		public CompileUnitEntry[] CompileUnits
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				CompileUnitEntry[] array = new CompileUnitEntry[CompileUnitCount];
				for (int i = 0; i < CompileUnitCount; i++)
				{
					array[i] = GetCompileUnit(i + 1);
				}
				return array;
			}
		}

		public MethodEntry[] Methods
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				lock (this)
				{
					read_methods();
					MethodEntry[] array = new MethodEntry[MethodCount];
					method_list.CopyTo(array, 0);
					return array;
				}
			}
		}

		internal MyBinaryReader BinaryReader
		{
			get
			{
				if (reader == null)
				{
					throw new InvalidOperationException();
				}
				return reader;
			}
		}

		public MonoSymbolFile()
		{
			ot = new OffsetTable();
		}

		public int AddSource(SourceFileEntry source)
		{
			sources.Add(source);
			return sources.Count;
		}

		public int AddCompileUnit(CompileUnitEntry entry)
		{
			comp_units.Add(entry);
			return comp_units.Count;
		}

		public void AddMethod(MethodEntry entry)
		{
			methods.Add(entry);
		}

		public MethodEntry DefineMethod(CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, MethodEntry.Flags flags, int namespace_id)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			MethodEntry methodEntry = new MethodEntry(this, comp_unit, token, scope_vars, locals, lines, code_blocks, real_name, flags, namespace_id);
			AddMethod(methodEntry);
			return methodEntry;
		}

		internal void DefineAnonymousScope(int id)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			if (anonymous_scopes == null)
			{
				anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>();
			}
			anonymous_scopes.Add(id, new AnonymousScopeEntry(id));
		}

		internal void DefineCapturedVariable(int scope_id, string name, string captured_name, CapturedVariable.CapturedKind kind)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			anonymous_scopes[scope_id].AddCapturedVariable(name, captured_name, kind);
		}

		internal void DefineCapturedScope(int scope_id, int id, string captured_name)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			anonymous_scopes[scope_id].AddCapturedScope(id, captured_name);
		}

		internal int GetNextTypeIndex()
		{
			return ++last_type_index;
		}

		internal int GetNextMethodIndex()
		{
			return ++last_method_index;
		}

		internal int GetNextNamespaceIndex()
		{
			return ++last_namespace_index;
		}

		private void Write(MyBinaryWriter bw, Guid guid)
		{
			bw.Write(5037318119232611860L);
			bw.Write(MajorVersion);
			bw.Write(MinorVersion);
			bw.Write(guid.ToByteArray());
			long position = bw.BaseStream.Position;
			ot.Write(bw, MajorVersion, MinorVersion);
			methods.Sort();
			for (int i = 0; i < methods.Count; i++)
			{
				methods[i].Index = i + 1;
			}
			ot.DataSectionOffset = (int)bw.BaseStream.Position;
			foreach (SourceFileEntry source in sources)
			{
				source.WriteData(bw);
			}
			foreach (CompileUnitEntry comp_unit in comp_units)
			{
				comp_unit.WriteData(bw);
			}
			foreach (MethodEntry method in methods)
			{
				method.WriteData(this, bw);
			}
			ot.DataSectionSize = (int)bw.BaseStream.Position - ot.DataSectionOffset;
			ot.MethodTableOffset = (int)bw.BaseStream.Position;
			for (int j = 0; j < methods.Count; j++)
			{
				methods[j].Write(bw);
			}
			ot.MethodTableSize = (int)bw.BaseStream.Position - ot.MethodTableOffset;
			ot.SourceTableOffset = (int)bw.BaseStream.Position;
			for (int k = 0; k < sources.Count; k++)
			{
				sources[k].Write(bw);
			}
			ot.SourceTableSize = (int)bw.BaseStream.Position - ot.SourceTableOffset;
			ot.CompileUnitTableOffset = (int)bw.BaseStream.Position;
			for (int l = 0; l < comp_units.Count; l++)
			{
				comp_units[l].Write(bw);
			}
			ot.CompileUnitTableSize = (int)bw.BaseStream.Position - ot.CompileUnitTableOffset;
			ot.AnonymousScopeCount = ((anonymous_scopes != null) ? anonymous_scopes.Count : 0);
			ot.AnonymousScopeTableOffset = (int)bw.BaseStream.Position;
			if (anonymous_scopes != null)
			{
				foreach (AnonymousScopeEntry value in anonymous_scopes.Values)
				{
					value.Write(bw);
				}
			}
			ot.AnonymousScopeTableSize = (int)bw.BaseStream.Position - ot.AnonymousScopeTableOffset;
			ot.TypeCount = last_type_index;
			ot.MethodCount = methods.Count;
			ot.SourceCount = sources.Count;
			ot.CompileUnitCount = comp_units.Count;
			ot.TotalFileSize = (int)bw.BaseStream.Position;
			bw.Seek((int)position, SeekOrigin.Begin);
			ot.Write(bw, MajorVersion, MinorVersion);
			bw.Seek(0, SeekOrigin.End);
		}

		public void CreateSymbolFile(Guid guid, FileStream fs)
		{
			if (reader != null)
			{
				throw new InvalidOperationException();
			}
			Write(new MyBinaryWriter(fs), guid);
		}

		private MonoSymbolFile(Stream stream)
		{
			reader = new MyBinaryReader(stream);
			try
			{
				long num = reader.ReadInt64();
				int num2 = reader.ReadInt32();
				int num3 = reader.ReadInt32();
				if (num != 5037318119232611860L)
				{
					throw new MonoSymbolFileException("Symbol file is not a valid");
				}
				if (num2 != 50)
				{
					throw new MonoSymbolFileException("Symbol file has version {0} but expected {1}", num2, 50);
				}
				if (num3 != 0)
				{
					throw new MonoSymbolFileException("Symbol file has version {0}.{1} but expected {2}.{3}", num2, num3, 50, 0);
				}
				MajorVersion = num2;
				MinorVersion = num3;
				guid = new Guid(reader.ReadBytes(16));
				ot = new OffsetTable(reader, num2, num3);
			}
			catch (Exception innerException)
			{
				throw new MonoSymbolFileException("Cannot read symbol file", innerException);
			}
			source_file_hash = new Dictionary<int, SourceFileEntry>();
			compile_unit_hash = new Dictionary<int, CompileUnitEntry>();
		}

		public static MonoSymbolFile ReadSymbolFile(Assembly assembly)
		{
			string mdbFilename = assembly.Location + ".mdb";
			Guid moduleVersionId = assembly.GetModules()[0].ModuleVersionId;
			return ReadSymbolFile(mdbFilename, moduleVersionId);
		}

		public static MonoSymbolFile ReadSymbolFile(string mdbFilename)
		{
			return ReadSymbolFile(new FileStream(mdbFilename, FileMode.Open, FileAccess.Read));
		}

		public static MonoSymbolFile ReadSymbolFile(string mdbFilename, Guid assemblyGuid)
		{
			MonoSymbolFile monoSymbolFile = ReadSymbolFile(mdbFilename);
			if (assemblyGuid != monoSymbolFile.guid)
			{
				throw new MonoSymbolFileException("Symbol file `{0}' does not match assembly", mdbFilename);
			}
			return monoSymbolFile;
		}

		public static MonoSymbolFile ReadSymbolFile(Stream stream)
		{
			return new MonoSymbolFile(stream);
		}

		public SourceFileEntry GetSourceFile(int index)
		{
			if (index < 1 || index > ot.SourceCount)
			{
				throw new ArgumentException();
			}
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (source_file_hash.TryGetValue(index, out var value))
				{
					return value;
				}
				long position = reader.BaseStream.Position;
				reader.BaseStream.Position = ot.SourceTableOffset + SourceFileEntry.Size * (index - 1);
				value = new SourceFileEntry(this, reader);
				source_file_hash.Add(index, value);
				reader.BaseStream.Position = position;
				return value;
			}
		}

		public CompileUnitEntry GetCompileUnit(int index)
		{
			if (index < 1 || index > ot.CompileUnitCount)
			{
				throw new ArgumentException();
			}
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (compile_unit_hash.TryGetValue(index, out var value))
				{
					return value;
				}
				long position = reader.BaseStream.Position;
				reader.BaseStream.Position = ot.CompileUnitTableOffset + CompileUnitEntry.Size * (index - 1);
				value = new CompileUnitEntry(this, reader);
				compile_unit_hash.Add(index, value);
				reader.BaseStream.Position = position;
				return value;
			}
		}

		private void read_methods()
		{
			lock (this)
			{
				if (method_token_hash == null)
				{
					method_token_hash = new Dictionary<int, MethodEntry>();
					method_list = new List<MethodEntry>();
					long position = reader.BaseStream.Position;
					reader.BaseStream.Position = ot.MethodTableOffset;
					for (int i = 0; i < MethodCount; i++)
					{
						MethodEntry methodEntry = new MethodEntry(this, reader, i + 1);
						method_token_hash.Add(methodEntry.Token, methodEntry);
						method_list.Add(methodEntry);
					}
					reader.BaseStream.Position = position;
				}
			}
		}

		public MethodEntry GetMethodByToken(int token)
		{
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				read_methods();
				method_token_hash.TryGetValue(token, out var value);
				return value;
			}
		}

		public MethodEntry GetMethod(int index)
		{
			if (index < 1 || index > ot.MethodCount)
			{
				throw new ArgumentException();
			}
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				read_methods();
				return method_list[index - 1];
			}
		}

		public int FindSource(string file_name)
		{
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (source_name_hash == null)
				{
					source_name_hash = new Dictionary<string, int>();
					for (int i = 0; i < ot.SourceCount; i++)
					{
						SourceFileEntry sourceFile = GetSourceFile(i + 1);
						source_name_hash.Add(sourceFile.FileName, i);
					}
				}
				if (!source_name_hash.TryGetValue(file_name, out var value))
				{
					return -1;
				}
				return value;
			}
		}

		public AnonymousScopeEntry GetAnonymousScope(int id)
		{
			if (reader == null)
			{
				throw new InvalidOperationException();
			}
			lock (this)
			{
				if (anonymous_scopes != null)
				{
					anonymous_scopes.TryGetValue(id, out var value);
					return value;
				}
				anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>();
				reader.BaseStream.Position = ot.AnonymousScopeTableOffset;
				for (int i = 0; i < ot.AnonymousScopeCount; i++)
				{
					AnonymousScopeEntry value = new AnonymousScopeEntry(reader);
					anonymous_scopes.Add(value.ID, value);
				}
				return anonymous_scopes[id];
			}
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing && reader != null)
			{
				reader.Close();
				reader = null;
			}
		}
	}
	public class OffsetTable
	{
		[Flags]
		public enum Flags
		{
			IsAspxSource = 1,
			WindowsFileNames = 2
		}

		public const int MajorVersion = 50;

		public const int MinorVersion = 0;

		public const long Magic = 5037318119232611860L;

		public int TotalFileSize;

		public int DataSectionOffset;

		public int DataSectionSize;

		public int CompileUnitCount;

		public int CompileUnitTableOffset;

		public int CompileUnitTableSize;

		public int SourceCount;

		public int SourceTableOffset;

		public int SourceTableSize;

		public int MethodCount;

		public int MethodTableOffset;

		public int MethodTableSize;

		public int TypeCount;

		public int AnonymousScopeCount;

		public int AnonymousScopeTableOffset;

		public int AnonymousScopeTableSize;

		public Flags FileFlags;

		public int LineNumberTable_LineBase = -1;

		public int LineNumberTable_LineRange = 8;

		public int LineNumberTable_OpcodeBase = 9;

		internal OffsetTable()
		{
			int platform = (int)Environment.OSVersion.Platform;
			if (platform != 4 && platform != 128)
			{
				FileFlags |= Flags.WindowsFileNames;
			}
		}

		internal OffsetTable(BinaryReader reader, int major_version, int minor_version)
		{
			TotalFileSize = reader.ReadInt32();
			DataSectionOffset = reader.ReadInt32();
			DataSectionSize = reader.ReadInt32();
			CompileUnitCount = reader.ReadInt32();
			CompileUnitTableOffset = reader.ReadInt32();
			CompileUnitTableSize = reader.ReadInt32();
			SourceCount = reader.ReadInt32();
			SourceTableOffset = reader.ReadInt32();
			SourceTableSize = reader.ReadInt32();
			MethodCount = reader.ReadInt32();
			MethodTableOffset = reader.ReadInt32();
			MethodTableSize = reader.ReadInt32();
			TypeCount = reader.ReadInt32();
			AnonymousScopeCount = reader.ReadInt32();
			AnonymousScopeTableOffset = reader.ReadInt32();
			AnonymousScopeTableSize = reader.ReadInt32();
			LineNumberTable_LineBase = reader.ReadInt32();
			LineNumberTable_LineRange = reader.ReadInt32();
			LineNumberTable_OpcodeBase = reader.ReadInt32();
			FileFlags = (Flags)reader.ReadInt32();
		}

		internal void Write(BinaryWriter bw, int major_version, int minor_version)
		{
			bw.Write(TotalFileSize);
			bw.Write(DataSectionOffset);
			bw.Write(DataSectionSize);
			bw.Write(CompileUnitCount);
			bw.Write(CompileUnitTableOffset);
			bw.Write(CompileUnitTableSize);
			bw.Write(SourceCount);
			bw.Write(SourceTableOffset);
			bw.Write(SourceTableSize);
			bw.Write(MethodCount);
			bw.Write(MethodTableOffset);
			bw.Write(MethodTableSize);
			bw.Write(TypeCount);
			bw.Write(AnonymousScopeCount);
			bw.Write(AnonymousScopeTableOffset);
			bw.Write(AnonymousScopeTableSize);
			bw.Write(LineNumberTable_LineBase);
			bw.Write(LineNumberTable_LineRange);
			bw.Write(LineNumberTable_OpcodeBase);
			bw.Write((int)FileFlags);
		}

		public override string ToString()
		{
			return $"OffsetTable [{TotalFileSize} - {DataSectionOffset}:{DataSectionSize} - {SourceCount}:{SourceTableOffset}:{SourceTableSize} - {MethodCount}:{MethodTableOffset}:{MethodTableSize} - {TypeCount}]";
		}
	}
	public class LineNumberEntry
	{
		public sealed class LocationComparer : IComparer<LineNumberEntry>
		{
			public static readonly LocationComparer Default = new LocationComparer();

			public int Compare(LineNumberEntry l1, LineNumberEntry l2)
			{
				if (l1.Row != l2.Row)
				{
					int row = l1.Row;
					return row.CompareTo(l2.Row);
				}
				return l1.Column.CompareTo(l2.Column);
			}
		}

		public readonly int Row;

		public int Column;

		public int EndRow;

		public int EndColumn;

		public readonly int File;

		public readonly int Offset;

		public readonly bool IsHidden;

		public static readonly LineNumberEntry Null = new LineNumberEntry(0, 0, 0, 0);

		public LineNumberEntry(int file, int row, int column, int offset)
			: this(file, row, column, offset, is_hidden: false)
		{
		}

		public LineNumberEntry(int file, int row, int offset)
			: this(file, row, -1, offset, is_hidden: false)
		{
		}

		public LineNumberEntry(int file, int row, int column, int offset, bool is_hidden)
			: this(file, row, column, -1, -1, offset, is_hidden)
		{
		}

		public LineNumberEntry(int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden)
		{
			File = file;
			Row = row;
			Column = column;
			EndRow = end_row;
			EndColumn = end_column;
			Offset = offset;
			IsHidden = is_hidden;
		}

		public override string ToString()
		{
			return $"[Line {File}:{Row},{Column}-{EndRow},{EndColumn}:{Offset}]";
		}
	}
	public class CodeBlockEntry
	{
		public enum Type
		{
			Lexical = 1,
			CompilerGenerated,
			IteratorBody,
			IteratorDispatcher
		}

		public int Index;

		public int Parent;

		public Type BlockType;

		public int StartOffset;

		public int EndOffset;

		public CodeBlockEntry(int index, int parent, Type type, int start_offset)
		{
			Index = index;
			Parent = parent;
			BlockType = type;
			StartOffset = start_offset;
		}

		internal CodeBlockEntry(int index, MyBinaryReader reader)
		{
			Index = index;
			int num = reader.ReadLeb128();
			BlockType = (Type)(num & 0x3F);
			Parent = reader.ReadLeb128();
			StartOffset = reader.ReadLeb128();
			EndOffset = reader.ReadLeb128();
			if (((uint)num & 0x40u) != 0)
			{
				int num2 = reader.ReadInt16();
				reader.BaseStream.Position += num2;
			}
		}

		public void Close(int end_offset)
		{
			EndOffset = end_offset;
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128((int)BlockType);
			bw.WriteLeb128(Parent);
			bw.WriteLeb128(StartOffset);
			bw.WriteLeb128(EndOffset);
		}

		public override string ToString()
		{
			return $"[CodeBlock {Index}:{Parent}:{BlockType}:{StartOffset}:{EndOffset}]";
		}
	}
	public struct LocalVariableEntry
	{
		public readonly int Index;

		public readonly string Name;

		public readonly int BlockIndex;

		public LocalVariableEntry(int index, string name, int block)
		{
			Index = index;
			Name = name;
			BlockIndex = block;
		}

		internal LocalVariableEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			Index = reader.ReadLeb128();
			Name = reader.ReadString();
			BlockIndex = reader.ReadLeb128();
		}

		internal void Write(MonoSymbolFile file, MyBinaryWriter bw)
		{
			bw.WriteLeb128(Index);
			bw.Write(Name);
			bw.WriteLeb128(BlockIndex);
		}

		public override string ToString()
		{
			return $"[LocalVariable {Name}:{Index}:{BlockIndex - 1}]";
		}
	}
	public struct CapturedVariable
	{
		public enum CapturedKind : byte
		{
			Local,
			Parameter,
			This
		}

		public readonly string Name;

		public readonly string CapturedName;

		public readonly CapturedKind Kind;

		public CapturedVariable(string name, string captured_name, CapturedKind kind)
		{
			Name = name;
			CapturedName = captured_name;
			Kind = kind;
		}

		internal CapturedVariable(MyBinaryReader reader)
		{
			Name = reader.ReadString();
			CapturedName = reader.ReadString();
			Kind = (CapturedKind)reader.ReadByte();
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.Write(Name);
			bw.Write(CapturedName);
			bw.Write((byte)Kind);
		}

		public override string ToString()
		{
			return $"[CapturedVariable {Name}:{CapturedName}:{Kind}]";
		}
	}
	public struct CapturedScope
	{
		public readonly int Scope;

		public readonly string CapturedName;

		public CapturedScope(int scope, string captured_name)
		{
			Scope = scope;
			CapturedName = captured_name;
		}

		internal CapturedScope(MyBinaryReader reader)
		{
			Scope = reader.ReadLeb128();
			CapturedName = reader.ReadString();
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128(Scope);
			bw.Write(CapturedName);
		}

		public override string ToString()
		{
			return $"[CapturedScope {Scope}:{CapturedName}]";
		}
	}
	public struct ScopeVariable
	{
		public readonly int Scope;

		public readonly int Index;

		public ScopeVariable(int scope, int index)
		{
			Scope = scope;
			Index = index;
		}

		internal ScopeVariable(MyBinaryReader reader)
		{
			Scope = reader.ReadLeb128();
			Index = reader.ReadLeb128();
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128(Scope);
			bw.WriteLeb128(Index);
		}

		public override string ToString()
		{
			return $"[ScopeVariable {Scope}:{Index}]";
		}
	}
	public class AnonymousScopeEntry
	{
		public readonly int ID;

		private List<CapturedVariable> captured_vars = new List<CapturedVariable>();

		private List<CapturedScope> captured_scopes = new List<CapturedScope>();

		public CapturedVariable[] CapturedVariables
		{
			get
			{
				CapturedVariable[] array = new CapturedVariable[captured_vars.Count];
				captured_vars.CopyTo(array, 0);
				return array;
			}
		}

		public CapturedScope[] CapturedScopes
		{
			get
			{
				CapturedScope[] array = new CapturedScope[captured_scopes.Count];
				captured_scopes.CopyTo(array, 0);
				return array;
			}
		}

		public AnonymousScopeEntry(int id)
		{
			ID = id;
		}

		internal AnonymousScopeEntry(MyBinaryReader reader)
		{
			ID = reader.ReadLeb128();
			int num = reader.ReadLeb128();
			for (int i = 0; i < num; i++)
			{
				captured_vars.Add(new CapturedVariable(reader));
			}
			int num2 = reader.ReadLeb128();
			for (int j = 0; j < num2; j++)
			{
				captured_scopes.Add(new CapturedScope(reader));
			}
		}

		internal void AddCapturedVariable(string name, string captured_name, CapturedVariable.CapturedKind kind)
		{
			captured_vars.Add(new CapturedVariable(name, captured_name, kind));
		}

		internal void AddCapturedScope(int scope, string captured_name)
		{
			captured_scopes.Add(new CapturedScope(scope, captured_name));
		}

		internal void Write(MyBinaryWriter bw)
		{
			bw.WriteLeb128(ID);
			bw.WriteLeb128(captured_vars.Count);
			foreach (CapturedVariable captured_var in captured_vars)
			{
				captured_var.Write(bw);
			}
			bw.WriteLeb128(captured_scopes.Count);
			foreach (CapturedScope captured_scope in captured_scopes)
			{
				captured_scope.Write(bw);
			}
		}

		public override string ToString()
		{
			return $"[AnonymousScope {ID}]";
		}
	}
	public class CompileUnitEntry : ICompileUnit
	{
		public readonly int Index;

		private int DataOffset;

		private MonoSymbolFile file;

		private SourceFileEntry source;

		private List<SourceFileEntry> include_files;

		private List<NamespaceEntry> namespaces;

		private bool creating;

		public static int Size => 8;

		CompileUnitEntry ICompileUnit.Entry => this;

		public SourceFileEntry SourceFile
		{
			get
			{
				if (creating)
				{
					return source;
				}
				ReadData();
				return source;
			}
		}

		public NamespaceEntry[] Namespaces
		{
			get
			{
				ReadData();
				NamespaceEntry[] array = new NamespaceEntry[namespaces.Count];
				namespaces.CopyTo(array, 0);
				return array;
			}
		}

		public SourceFileEntry[] IncludeFiles
		{
			get
			{
				ReadData();
				if (include_files == null)
				{
					return new SourceFileEntry[0];
				}
				SourceFileEntry[] array = new SourceFileEntry[include_files.Count];
				include_files.CopyTo(array, 0);
				return array;
			}
		}

		public CompileUnitEntry(MonoSymbolFile file, SourceFileEntry source)
		{
			this.file = file;
			this.source = source;
			Index = file.AddCompileUnit(this);
			creating = true;
			namespaces = new List<NamespaceEntry>();
		}

		public void AddFile(SourceFileEntry file)
		{
			if (!creating)
			{
				throw new InvalidOperationException();
			}
			if (include_files == null)
			{
				include_files = new List<SourceFileEntry>();
			}
			include_files.Add(file);
		}

		public int DefineNamespace(string name, string[] using_clauses, int parent)
		{
			if (!creating)
			{
				throw new InvalidOperationException();
			}
			int nextNamespaceIndex = file.GetNextNamespaceIndex();
			NamespaceEntry item = new NamespaceEntry(name, nextNamespaceIndex, using_clauses, parent);
			namespaces.Add(item);
			return nextNamespaceIndex;
		}

		internal void WriteData(MyBinaryWriter bw)
		{
			DataOffset = (int)bw.BaseStream.Position;
			bw.WriteLeb128(source.Index);
			int value = ((include_files != null) ? include_files.Count : 0);
			bw.WriteLeb128(value);
			if (include_files != null)
			{
				foreach (SourceFileEntry include_file in include_files)
				{
					bw.WriteLeb128(include_file.Index);
				}
			}
			bw.WriteLeb128(namespaces.Count);
			foreach (NamespaceEntry @namespace in namespaces)
			{
				@namespace.Write(file, bw);
			}
		}

		internal void Write(BinaryWriter bw)
		{
			bw.Write(Index);
			bw.Write(DataOffset);
		}

		internal CompileUnitEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			this.file = file;
			Index = reader.ReadInt32();
			DataOffset = reader.ReadInt32();
		}

		public void ReadAll()
		{
			ReadData();
		}

		private void ReadData()
		{
			if (creating)
			{
				throw new InvalidOperationException();
			}
			lock (file)
			{
				if (namespaces != null)
				{
					return;
				}
				MyBinaryReader binaryReader = file.BinaryReader;
				int num = (int)binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = DataOffset;
				int index = binaryReader.ReadLeb128();
				source = file.GetSourceFile(index);
				int num2 = binaryReader.ReadLeb128();
				if (num2 > 0)
				{
					include_files = new List<SourceFileEntry>();
					for (int i = 0; i < num2; i++)
					{
						include_files.Add(file.GetSourceFile(binaryReader.ReadLeb128()));
					}
				}
				int num3 = binaryReader.ReadLeb128();
				namespaces = new List<NamespaceEntry>();
				for (int j = 0; j < num3; j++)
				{
					namespaces.Add(new NamespaceEntry(file, binaryReader));
				}
				binaryReader.BaseStream.Position = num;
			}
		}
	}
	public class SourceFileEntry
	{
		public readonly int Index;

		private int DataOffset;

		private MonoSymbolFile file;

		private string file_name;

		private byte[] guid;

		private byte[] hash;

		private bool creating;

		private bool auto_generated;

		private readonly string sourceFile;

		public static int Size => 8;

		public byte[] Checksum => hash;

		public string FileName
		{
			get
			{
				return file_name;
			}
			set
			{
				file_name = value;
			}
		}

		public bool AutoGenerated => auto_generated;

		public SourceFileEntry(MonoSymbolFile file, string file_name)
		{
			this.file = file;
			this.file_name = file_name;
			Index = file.AddSource(this);
			creating = true;
		}

		public SourceFileEntry(MonoSymbolFile file, string sourceFile, byte[] guid, byte[] checksum)
			: this(file, sourceFile, sourceFile, guid, checksum)
		{
		}

		public SourceFileEntry(MonoSymbolFile file, string fileName, string sourceFile, byte[] guid, byte[] checksum)
			: this(file, fileName)
		{
			this.guid = guid;
			hash = checksum;
			this.sourceFile = sourceFile;
		}

		internal void WriteData(MyBinaryWriter bw)
		{
			DataOffset = (int)bw.BaseStream.Position;
			bw.Write(file_name);
			if (guid == null)
			{
				guid = new byte[16];
			}
			if (hash == null)
			{
				try
				{
					using FileStream inputStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
					MD5 mD = MD5.Create();
					hash = mD.ComputeHash(inputStream);
				}
				catch
				{
					hash = new byte[16];
				}
			}
			bw.Write(guid);
			bw.Write(hash);
			bw.Write((byte)(auto_generated ? 1u : 0u));
		}

		internal void Write(BinaryWriter bw)
		{
			bw.Write(Index);
			bw.Write(DataOffset);
		}

		internal SourceFileEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			this.file = file;
			Index = reader.ReadInt32();
			DataOffset = reader.ReadInt32();
			int num = (int)reader.BaseStream.Position;
			reader.BaseStream.Position = DataOffset;
			sourceFile = (file_name = reader.ReadString());
			guid = reader.ReadBytes(16);
			hash = reader.ReadBytes(16);
			auto_generated = reader.ReadByte() == 1;
			reader.BaseStream.Position = num;
		}

		public void SetAutoGenerated()
		{
			if (!creating)
			{
				throw new InvalidOperationException();
			}
			auto_generated = true;
			file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource;
		}

		public bool CheckChecksum()
		{
			try
			{
				using FileStream inputStream = new FileStream(sourceFile, FileMode.Open);
				byte[] array = MD5.Create().ComputeHash(inputStream);
				for (int i = 0; i < 16; i++)
				{
					if (array[i] != hash[i])
					{
						return false;
					}
				}
				return true;
			}
			catch
			{
				return false;
			}
		}

		public override string ToString()
		{
			return $"SourceFileEntry ({Index}:{DataOffset})";
		}
	}
	public class LineNumberTable
	{
		protected LineNumberEntry[] _line_numbers;

		public readonly int LineBase;

		public readonly int LineRange;

		public readonly byte OpcodeBase;

		public readonly int MaxAddressIncrement;

		public const int Default_LineBase = -1;

		public const int Default_LineRange = 8;

		public const byte Default_OpcodeBase = 9;

		public const byte DW_LNS_copy = 1;

		public const byte DW_LNS_advance_pc = 2;

		public const byte DW_LNS_advance_line = 3;

		public const byte DW_LNS_set_file = 4;

		public const byte DW_LNS_const_add_pc = 8;

		public const byte DW_LNE_end_sequence = 1;

		public const byte DW_LNE_MONO_negate_is_hidden = 64;

		internal const byte DW_LNE_MONO__extensions_start = 64;

		internal const byte DW_LNE_MONO__extensions_end = 127;

		public LineNumberEntry[] LineNumbers => _line_numbers;

		protected LineNumberTable(MonoSymbolFile file)
		{
			LineBase = file.OffsetTable.LineNumberTable_LineBase;
			LineRange = file.OffsetTable.LineNumberTable_LineRange;
			OpcodeBase = (byte)file.OffsetTable.LineNumberTable_OpcodeBase;
			MaxAddressIncrement = (255 - OpcodeBase) / LineRange;
		}

		internal LineNumberTable(MonoSymbolFile file, LineNumberEntry[] lines)
			: this(file)
		{
			_line_numbers = lines;
		}

		internal void Write(MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo)
		{
			int num = (int)bw.BaseStream.Position;
			bool flag = false;
			int num2 = 1;
			int num3 = 0;
			int num4 = 1;
			for (int i = 0; i < LineNumbers.Length; i++)
			{
				int num5 = LineNumbers[i].Row - num2;
				int num6 = LineNumbers[i].Offset - num3;
				if (LineNumbers[i].File != num4)
				{
					bw.Write((byte)4);
					bw.WriteLeb128(LineNumbers[i].File);
					num4 = LineNumbers[i].File;
				}
				if (LineNumbers[i].IsHidden != flag)
				{
					bw.Write((byte)0);
					bw.Write((byte)1);
					bw.Write((byte)64);
					flag = LineNumbers[i].IsHidden;
				}
				if (num6 >= MaxAddressIncrement)
				{
					if (num6 < 2 * MaxAddressIncrement)
					{
						bw.Write((byte)8);
						num6 -= MaxAddressIncrement;
					}
					else
					{
						bw.Write((byte)2);
						bw.WriteLeb128(num6);
						num6 = 0;
					}
				}
				if (num5 < LineBase || num5 >= LineBase + LineRange)
				{
					bw.Write((byte)3);
					bw.WriteLeb128(num5);
					if (num6 != 0)
					{
						bw.Write((byte)2);
						bw.WriteLeb128(num6);
					}
					bw.Write((byte)1);
				}
				else
				{
					byte value = (byte)(num5 - LineBase + LineRange * num6 + OpcodeBase);
					bw.Write(value);
				}
				num2 = LineNumbers[i].Row;
				num3 = LineNumbers[i].Offset;
			}
			bw.Write((byte)0);
			bw.Write((byte)1);
			bw.Write((byte)1);
			if (hasColumnsInfo)
			{
				for (int j = 0; j < LineNumbers.Length; j++)
				{
					LineNumberEntry lineNumberEntry = LineNumbers[j];
					if (lineNumberEntry.Row >= 0)
					{
						bw.WriteLeb128(lineNumberEntry.Column);
					}
				}
			}
			if (hasEndInfo)
			{
				for (int k = 0; k < LineNumbers.Length; k++)
				{
					LineNumberEntry lineNumberEntry2 = LineNumbers[k];
					if (lineNumberEntry2.EndRow == -1 || lineNumberEntry2.EndColumn == -1 || lineNumberEntry2.Row > lineNumberEntry2.EndRow)
					{
						bw.WriteLeb128(16777215);
						continue;
					}
					bw.WriteLeb128(lineNumberEntry2.EndRow - lineNumberEntry2.Row);
					bw.WriteLeb128(lineNumberEntry2.EndColumn);
				}
			}
			file.ExtendedLineNumberSize += (int)bw.BaseStream.Position - num;
		}

		internal static LineNumberTable Read(MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo)
		{
			LineNumberTable lineNumberTable = new LineNumberTable(file);
			lineNumberTable.DoRead(file, br, readColumnsInfo, readEndInfo);
			return lineNumberTable;
		}

		private void DoRead(MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds)
		{
			List<LineNumberEntry> list = new List<LineNumberEntry>();
			bool flag = false;
			bool flag2 = false;
			int num = 1;
			int num2 = 0;
			int file2 = 1;
			while (true)
			{
				byte b = br.ReadByte();
				if (b == 0)
				{
					byte b2 = br.ReadByte();
					long position = br.BaseStream.Position + b2;
					b = br.ReadByte();
					switch (b)
					{
					case 1:
					{
						if (flag2)
						{
							list.Add(new LineNumberEntry(file2, num, -1, num2, flag));
						}
						_line_numbers = list.ToArray();
						if (includesColumns)
						{
							for (int i = 0; i < _line_numbers.Length; i++)
							{
								LineNumberEntry lineNumberEntry = _line_numbers[i];
								if (lineNumberEntry.Row >= 0)
								{
									lineNumberEntry.Column = br.ReadLeb128();
								}
							}
						}
						if (!includesEnds)
						{
							return;
						}
						for (int j = 0; j < _line_numbers.Length; j++)
						{
							LineNumberEntry lineNumberEntry2 = _line_numbers[j];
							int num3 = br.ReadLeb128();
							if (num3 == 16777215)
							{
								lineNumberEntry2.EndRow = -1;
								lineNumberEntry2.EndColumn = -1;
							}
							else
							{
								lineNumberEntry2.EndRow = lineNumberEntry2.Row + num3;
								lineNumberEntry2.EndColumn = br.ReadLeb128();
							}
						}
						return;
					}
					case 64:
						flag = !flag;
						flag2 = true;
						break;
					default:
						throw new MonoSymbolFileException("Unknown extended opcode {0:x}", b);
					case 65:
					case 66:
					case 67:
					case 68:
					case 69:
					case 70:
					case 71:
					case 72:
					case 73:
					case 74:
					case 75:
					case 76:
					case 77:
					case 78:
					case 79:
					case 80:
					case 81:
					case 82:
					case 83:
					case 84:
					case 85:
					case 86:
					case 87:
					case 88:
					case 89:
					case 90:
					case 91:
					case 92:
					case 93:
					case 94:
					case 95:
					case 96:
					case 97:
					case 98:
					case 99:
					case 100:
					case 101:
					case 102:
					case 103:
					case 104:
					case 105:
					case 106:
					case 107:
					case 108:
					case 109:
					case 110:
					case 111:
					case 112:
					case 113:
					case 114:
					case 115:
					case 116:
					case 117:
					case 118:
					case 119:
					case 120:
					case 121:
					case 122:
					case 123:
					case 124:
					case 125:
					case 126:
					case 127:
						break;
					}
					br.BaseStream.Position = position;
				}
				else if (b < OpcodeBase)
				{
					switch (b)
					{
					case 1:
						list.Add(new LineNumberEntry(file2, num, -1, num2, flag));
						flag2 = false;
						break;
					case 2:
						num2 += br.ReadLeb128();
						flag2 = true;
						break;
					case 3:
						num += br.ReadLeb128();
						flag2 = true;
						break;
					case 4:
						file2 = br.ReadLeb128();
						flag2 = true;
						break;
					case 8:
						num2 += MaxAddressIncrement;
						flag2 = true;
						break;
					default:
						throw new MonoSymbolFileException("Unknown standard opcode {0:x} in LNT", b);
					}
				}
				else
				{
					b -= OpcodeBase;
					num2 += b / LineRange;
					num += LineBase + b % LineRange;
					list.Add(new LineNumberEntry(file2, num, -1, num2, flag));
					flag2 = false;
				}
			}
		}

		public bool GetMethodBounds(out LineNumberEntry start, out LineNumberEntry end)
		{
			if (_line_numbers.Length > 1)
			{
				start = _line_numbers[0];
				end = _line_numbers[_line_numbers.Length - 1];
				return true;
			}
			start = LineNumberEntry.Null;
			end = LineNumberEntry.Null;
			return false;
		}
	}
	public class MethodEntry : IComparable
	{
		[Flags]
		public enum Flags
		{
			LocalNamesAmbiguous = 1,
			ColumnsInfoIncluded = 2,
			EndInfoIncluded = 4
		}

		public readonly int CompileUnitIndex;

		public readonly int Token;

		public readonly int NamespaceID;

		private int DataOffset;

		private int LocalVariableTableOffset;

		private int LineNumberTableOffset;

		private int CodeBlockTableOffset;

		private int ScopeVariableTableOffset;

		private int RealNameOffset;

		private Flags flags;

		private int index;

		public readonly CompileUnitEntry CompileUnit;

		private LocalVariableEntry[] locals;

		private CodeBlockEntry[] code_blocks;

		private ScopeVariable[] scope_vars;

		private LineNumberTable lnt;

		private string real_name;

		public readonly MonoSymbolFile SymbolFile;

		public const int Size = 12;

		public Flags MethodFlags => flags;

		public int Index
		{
			get
			{
				return index;
			}
			set
			{
				index = value;
			}
		}

		internal MethodEntry(MonoSymbolFile file, MyBinaryReader reader, int index)
		{
			SymbolFile = file;
			this.index = index;
			Token = reader.ReadInt32();
			DataOffset = reader.ReadInt32();
			LineNumberTableOffset = reader.ReadInt32();
			long position = reader.BaseStream.Position;
			reader.BaseStream.Position = DataOffset;
			CompileUnitIndex = reader.ReadLeb128();
			LocalVariableTableOffset = reader.ReadLeb128();
			NamespaceID = reader.ReadLeb128();
			CodeBlockTableOffset = reader.ReadLeb128();
			ScopeVariableTableOffset = reader.ReadLeb128();
			RealNameOffset = reader.ReadLeb128();
			flags = (Flags)reader.ReadLeb128();
			reader.BaseStream.Position = position;
			CompileUnit = file.GetCompileUnit(CompileUnitIndex);
		}

		internal MethodEntry(MonoSymbolFile file, CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, Flags flags, int namespace_id)
		{
			SymbolFile = file;
			this.real_name = real_name;
			this.locals = locals;
			this.code_blocks = code_blocks;
			this.scope_vars = scope_vars;
			this.flags = flags;
			index = -1;
			Token = token;
			CompileUnitIndex = comp_unit.Index;
			CompileUnit = comp_unit;
			NamespaceID = namespace_id;
			CheckLineNumberTable(lines);
			lnt = new LineNumberTable(file, lines);
			file.NumLineNumbers += lines.Length;
			int num = ((locals != null) ? locals.Length : 0);
			if (num <= 32)
			{
				for (int i = 0; i < num; i++)
				{
					string name = locals[i].Name;
					for (int j = i + 1; j < num; j++)
					{
						if (locals[j].Name == name)
						{
							flags |= Flags.LocalNamesAmbiguous;
							return;
						}
					}
				}
				return;
			}
			Dictionary<string, LocalVariableEntry> dictionary = new Dictionary<string, LocalVariableEntry>();
			for (int k = 0; k < locals.Length; k++)
			{
				LocalVariableEntry value = locals[k];
				if (dictionary.ContainsKey(value.Name))
				{
					flags |= Flags.LocalNamesAmbiguous;
					break;
				}
				dictionary.Add(value.Name, value);
			}
		}

		private static void CheckLineNumberTable(LineNumberEntry[] line_numbers)
		{
			int num = -1;
			int num2 = -1;
			if (line_numbers == null)
			{
				return;
			}
			foreach (LineNumberEntry lineNumberEntry in line_numbers)
			{
				if (lineNumberEntry.Equals(LineNumberEntry.Null))
				{
					throw new MonoSymbolFileException();
				}
				if (lineNumberEntry.Offset < num)
				{
					throw new MonoSymbolFileException();
				}
				if (lineNumberEntry.Offset > num)
				{
					num2 = lineNumberEntry.Row;
					num = lineNumberEntry.Offset;
				}
				else if (lineNumberEntry.Row > num2)
				{
					num2 = lineNumberEntry.Row;
				}
			}
		}

		internal void Write(MyBinaryWriter bw)
		{
			if (index <= 0 || DataOffset == 0)
			{
				throw new InvalidOperationException();
			}
			bw.Write(Token);
			bw.Write(DataOffset);
			bw.Write(LineNumberTableOffset);
		}

		internal void WriteData(MonoSymbolFile file, MyBinaryWriter bw)
		{
			if (index <= 0)
			{
				throw new InvalidOperationException();
			}
			LocalVariableTableOffset = (int)bw.BaseStream.Position;
			int num = ((locals != null) ? locals.Length : 0);
			bw.WriteLeb128(num);
			for (int i = 0; i < num; i++)
			{
				locals[i].Write(file, bw);
			}
			file.LocalCount += num;
			CodeBlockTableOffset = (int)bw.BaseStream.Position;
			int num2 = ((code_blocks != null) ? code_blocks.Length : 0);
			bw.WriteLeb128(num2);
			for (int j = 0; j < num2; j++)
			{
				code_blocks[j].Write(bw);
			}
			ScopeVariableTableOffset = (int)bw.BaseStream.Position;
			int num3 = ((scope_vars != null) ? scope_vars.Length : 0);
			bw.WriteLeb128(num3);
			for (int k = 0; k < num3; k++)
			{
				scope_vars[k].Write(bw);
			}
			if (real_name != null)
			{
				RealNameOffset = (int)bw.BaseStream.Position;
				bw.Write(real_name);
			}
			LineNumberEntry[] lineNumbers = lnt.LineNumbers;
			foreach (LineNumberEntry lineNumberEntry in lineNumbers)
			{
				if (lineNumberEntry.EndRow != -1 || lineNumberEntry.EndColumn != -1)
				{
					flags |= Flags.EndInfoIncluded;
				}
			}
			LineNumberTableOffset = (int)bw.BaseStream.Position;
			lnt.Write(file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
			DataOffset = (int)bw.BaseStream.Position;
			bw.WriteLeb128(CompileUnitIndex);
			bw.WriteLeb128(LocalVariableTableOffset);
			bw.WriteLeb128(NamespaceID);
			bw.WriteLeb128(CodeBlockTableOffset);
			bw.WriteLeb128(ScopeVariableTableOffset);
			bw.WriteLeb128(RealNameOffset);
			bw.WriteLeb128((int)flags);
		}

		public void ReadAll()
		{
			GetLineNumberTable();
			GetLocals();
			GetCodeBlocks();
			GetScopeVariables();
			GetRealName();
		}

		public LineNumberTable GetLineNumberTable()
		{
			lock (SymbolFile)
			{
				if (lnt != null)
				{
					return lnt;
				}
				if (LineNumberTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = LineNumberTableOffset;
				lnt = LineNumberTable.Read(SymbolFile, binaryReader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0);
				binaryReader.BaseStream.Position = position;
				return lnt;
			}
		}

		public LocalVariableEntry[] GetLocals()
		{
			lock (SymbolFile)
			{
				if (locals != null)
				{
					return locals;
				}
				if (LocalVariableTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = LocalVariableTableOffset;
				int num = binaryReader.ReadLeb128();
				locals = new LocalVariableEntry[num];
				for (int i = 0; i < num; i++)
				{
					locals[i] = new LocalVariableEntry(SymbolFile, binaryReader);
				}
				binaryReader.BaseStream.Position = position;
				return locals;
			}
		}

		public CodeBlockEntry[] GetCodeBlocks()
		{
			lock (SymbolFile)
			{
				if (code_blocks != null)
				{
					return code_blocks;
				}
				if (CodeBlockTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = CodeBlockTableOffset;
				int num = binaryReader.ReadLeb128();
				code_blocks = new CodeBlockEntry[num];
				for (int i = 0; i < num; i++)
				{
					code_blocks[i] = new CodeBlockEntry(i, binaryReader);
				}
				binaryReader.BaseStream.Position = position;
				return code_blocks;
			}
		}

		public ScopeVariable[] GetScopeVariables()
		{
			lock (SymbolFile)
			{
				if (scope_vars != null)
				{
					return scope_vars;
				}
				if (ScopeVariableTableOffset == 0)
				{
					return null;
				}
				MyBinaryReader binaryReader = SymbolFile.BinaryReader;
				long position = binaryReader.BaseStream.Position;
				binaryReader.BaseStream.Position = ScopeVariableTableOffset;
				int num = binaryReader.ReadLeb128();
				scope_vars = new ScopeVariable[num];
				for (int i = 0; i < num; i++)
				{
					scope_vars[i] = new ScopeVariable(binaryReader);
				}
				binaryReader.BaseStream.Position = position;
				return scope_vars;
			}
		}

		public string GetRealName()
		{
			lock (SymbolFile)
			{
				if (real_name != null)
				{
					return real_name;
				}
				if (RealNameOffset == 0)
				{
					return null;
				}
				real_name = SymbolFile.BinaryReader.ReadString(RealNameOffset);
				return real_name;
			}
		}

		public int CompareTo(object obj)
		{
			MethodEntry methodEntry = (MethodEntry)obj;
			if (methodEntry.Token < Token)
			{
				return 1;
			}
			if (methodEntry.Token > Token)
			{
				return -1;
			}
			return 0;
		}

		public override string ToString()
		{
			return $"[Method {index}:{Token:x}:{CompileUnitIndex}:{CompileUnit}]";
		}
	}
	public struct NamespaceEntry
	{
		public readonly string Name;

		public readonly int Index;

		public readonly int Parent;

		public readonly string[] UsingClauses;

		public NamespaceEntry(string name, int index, string[] using_clauses, int parent)
		{
			Name = name;
			Index = index;
			Parent = parent;
			UsingClauses = ((using_clauses != null) ? using_clauses : new string[0]);
		}

		internal NamespaceEntry(MonoSymbolFile file, MyBinaryReader reader)
		{
			Name = reader.ReadString();
			Index = reader.ReadLeb128();
			Parent = reader.ReadLeb128();
			int num = reader.ReadLeb128();
			UsingClauses = new string[num];
			for (int i = 0; i < num; i++)
			{
				UsingClauses[i] = reader.ReadString();
			}
		}

		internal void Write(MonoSymbolFile file, MyBinaryWriter bw)
		{
			bw.Write(Name);
			bw.WriteLeb128(Index);
			bw.WriteLeb128(Parent);
			bw.WriteLeb128(UsingClauses.Length);
			string[] usingClauses = UsingClauses;
			foreach (string value in usingClauses)
			{
				bw.Write(value);
			}
		}

		public override string ToString()
		{
			return $"[Namespace {Name}:{Index}:{Parent}]";
		}
	}
	public class MonoSymbolWriter
	{
		private List<SourceMethodBuilder> methods;

		private List<SourceFileEntry> sources;

		private List<CompileUnitEntry> comp_units;

		protected readonly MonoSymbolFile file;

		private string filename;

		private SourceMethodBuilder current_method;

		private Stack<SourceMethodBuilder> current_method_stack = new Stack<SourceMethodBuilder>();

		public MonoSymbolFile SymbolFile => file;

		public MonoSymbolWriter(string filename)
		{
			methods = new List<SourceMethodBuilder>();
			sources = new List<SourceFileEntry>();
			comp_units = new List<CompileUnitEntry>();
			file = new MonoSymbolFile();
			this.filename = filename + ".mdb";
		}

		public void CloseNamespace()
		{
		}

		public void DefineLocalVariable(int index, string name)
		{
			if (current_method != null)
			{
				current_method.AddLocal(index, name);
			}
		}

		public void DefineCapturedLocal(int scope_id, string name, string captured_name)
		{
			file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Local);
		}

		public void DefineCapturedParameter(int scope_id, string name, string captured_name)
		{
			file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Parameter);
		}

		public void DefineCapturedThis(int scope_id, string captured_name)
		{
			file.DefineCapturedVariable(scope_id, "this", captured_name, CapturedVariable.CapturedKind.This);
		}

		public void DefineCapturedScope(int scope_id, int id, string captured_name)
		{
			file.DefineCapturedScope(scope_id, id, captured_name);
		}

		public void DefineScopeVariable(int scope, int index)
		{
			if (current_method != null)
			{
				current_method.AddScopeVariable(scope, index);
			}
		}

		public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden)
		{
			if (current_method != null)
			{
				current_method.MarkSequencePoint(offset, file, line, column, is_hidden);
			}
		}

		public SourceMethodBuilder OpenMethod(ICompileUnit file, int ns_id, IMethodDef method)
		{
			SourceMethodBuilder result = new SourceMethodBuilder(file, ns_id, method);
			current_method_stack.Push(current_method);
			current_method = result;
			methods.Add(current_method);
			return result;
		}

		public void CloseMethod()
		{
			current_method = current_method_stack.Pop();
		}

		public SourceFileEntry DefineDocument(string url)
		{
			SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url);
			sources.Add(sourceFileEntry);
			return sourceFileEntry;
		}

		public SourceFileEntry DefineDocument(string url, byte[] guid, byte[] checksum)
		{
			SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url, guid, checksum);
			sources.Add(sourceFileEntry);
			return sourceFileEntry;
		}

		public CompileUnitEntry DefineCompilationUnit(SourceFileEntry source)
		{
			CompileUnitEntry compileUnitEntry = new CompileUnitEntry(file, source);
			comp_units.Add(compileUnitEntry);
			return compileUnitEntry;
		}

		public int DefineNamespace(string name, CompileUnitEntry unit, string[] using_clauses, int parent)
		{
			if (unit == null || using_clauses == null)
			{
				throw new NullReferenceException();
			}
			return unit.DefineNamespace(name, using_clauses, parent);
		}

		public int OpenScope(int start_offset)
		{
			if (current_method == null)
			{
				return 0;
			}
			current_method.StartBlock(CodeBlockEntry.Type.Lexical, start_offset);
			return 0;
		}

		public void CloseScope(int end_offset)
		{
			if (current_method != null)
			{
				current_method.EndBlock(end_offset);
			}
		}

		public void OpenCompilerGeneratedBlock(int start_offset)
		{
			if (current_method != null)
			{
				current_method.StartBlock(CodeBlockEntry.Type.CompilerGenerated, start_offset);
			}
		}

		public void CloseCompilerGeneratedBlock(int end_offset)
		{
			if (current_method != null)
			{
				current_method.EndBlock(end_offset);
			}
		}

		public void StartIteratorBody(int start_offset)
		{
			current_method.StartBlock(CodeBlockEntry.Type.IteratorBody, start_offset);
		}

		public void EndIteratorBody(int end_offset)
		{
			current_method.EndBlock(end_offset);
		}

		public void StartIteratorDispatcher(int start_offset)
		{
			current_method.StartBlock(CodeBlockEntry.Type.IteratorDispatcher, start_offset);
		}

		public void EndIteratorDispatcher(int end_offset)
		{
			current_method.EndBlock(end_offset);
		}

		public void DefineAnonymousScope(int id)
		{
			file.DefineAnonymousScope(id);
		}

		public void WriteSymbolFile(Guid guid)
		{
			foreach (SourceMethodBuilder method in methods)
			{
				method.DefineMethod(file);
			}
			try
			{
				File.Delete(filename);
			}
			catch
			{
			}
			using FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
			file.CreateSymbolFile(guid, fs);
		}
	}
	public class SourceMethodBuilder
	{
		private List<LocalVariableEntry> _locals;

		private List<CodeBlockEntry> _blocks;

		private List<ScopeVariable> _scope_vars;

		private Stack<CodeBlockEntry> _block_stack;

		private readonly List<LineNumberEntry> method_lines;

		private readonly ICompileUnit _comp_unit;

		private readonly int ns_id;

		private readonly IMethodDef method;

		public CodeBlockEntry[] Blocks
		{
			get
			{
				if (_blocks == null)
				{
					return new CodeBlockEntry[0];
				}
				CodeBlockEntry[] array = new CodeBlockEntry[_blocks.Count];
				_blocks.CopyTo(array, 0);
				return array;
			}
		}

		public CodeBlockEntry CurrentBlock
		{
			get
			{
				if (_block_stack != null && _block_stack.Count > 0)
				{
					return _block_stack.Peek();
				}
				return null;
			}
		}

		public LocalVariableEntry[] Locals
		{
			get
			{
				if (_locals == null)
				{
					return new LocalVariableEntry[0];
				}
				return _locals.ToArray();
			}
		}

		public ICompileUnit SourceFile => _comp_unit;

		public ScopeVariable[] ScopeVariables
		{
			get
			{
				if (_scope_vars == null)
				{
					return new ScopeVariable[0];
				}
				return _scope_vars.ToArray();
			}
		}

		public SourceMethodBuilder(ICompileUnit comp_unit)
		{
			_comp_unit = comp_unit;
			method_lines = new List<LineNumberEntry>();
		}

		public SourceMethodBuilder(ICompileUnit comp_unit, int ns_id, IMethodDef method)
			: this(comp_unit)
		{
			this.ns_id = ns_id;
			this.method = method;
		}

		public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden)
		{
			MarkSequencePoint(offset, file, line, column, -1, -1, is_hidden);
		}

		public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, int end_line, int end_column, bool is_hidden)
		{
			LineNumberEntry lineNumberEntry = new LineNumberEntry(file?.Index ?? 0, line, column, end_line, end_column, offset, is_hidden);
			if (method_lines.Count > 0)
			{
				LineNumberEntry lineNumberEntry2 = method_lines[method_lines.Count - 1];
				if (lineNumberEntry2.Offset == offset)
				{
					if (LineNumberEntry.LocationComparer.Default.Compare(lineNumberEntry, lineNumberEntry2) > 0)
					{
						method_lines[method_lines.Count - 1] = lineNumberEntry;
					}
					return;
				}
			}
			method_lines.Add(lineNumberEntry);
		}

		public void StartBlock(CodeBlockEntry.Type type, int start_offset)
		{
			StartBlock(type, start_offset, (_blocks == null) ? 1 : (_blocks.Count + 1));
		}

		public void StartBlock(CodeBlockEntry.Type type, int start_offset, int scopeIndex)
		{
			if (_block_stack == null)
			{
				_block_stack = new Stack<CodeBlockEntry>();
			}
			if (_blocks == null)
			{
				_blocks = new List<CodeBlockEntry>();
			}
			int parent = ((CurrentBlock != null) ? CurrentBlock.Index : (-1));
			CodeBlockEntry item = new CodeBlockEntry(scopeIndex, parent, type, start_offset);
			_block_stack.Push(item);
			_blocks.Add(item);
		}

		public void EndBlock(int end_offset)
		{
			_block_stack.Pop().Close(end_offset);
		}

		public void AddLocal(int index, string name)
		{
			if (_locals == null)
			{
				_locals = new List<LocalVariableEntry>();
			}
			int block = ((CurrentBlock != null) ? CurrentBlock.Index : 0);
			_locals.Add(new LocalVariableEntry(index, name, block));
		}

		public void AddScopeVariable(int scope, int index)
		{
			if (_scope_vars == null)
			{
				_scope_vars = new List<ScopeVariable>();
			}
			_scope_vars.Add(new ScopeVariable(scope, index));
		}

		public void DefineMethod(MonoSymbolFile file)
		{
			DefineMethod(file, method.Token);
		}

		public void DefineMethod(MonoSymbolFile file, int token)
		{
			CodeBlockEntry[] array = Blocks;
			if (array.Length != 0)
			{
				List<CodeBlockEntry> list = new List<CodeBlockEntry>(array.Length);
				int num = 0;
				for (int i = 0; i < array.Length; i++)
				{
					num = Math.Max(num, array[i].Index);
				}
				for (int j = 0; j < num; j++)
				{
					int num2 = j + 1;
					if (j < array.Length && array[j].Index == num2)
					{
						list.Add(array[j]);
						continue;
					}
					bool flag = false;
					for (int k = 0; k < array.Length; k++)
					{
						if (array[k].Index == num2)
						{
							list.Add(array[k]);
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						list.Add(new CodeBlockEntry(num2, -1, CodeBlockEntry.Type.CompilerGenerated, 0));
					}
				}
				array = list.ToArray();
			}
			MethodEntry entry = new MethodEntry(file, _comp_unit.Entry, token, ScopeVariables, Locals, method_lines.ToArray(), array, null, MethodEntry.Flags.ColumnsInfoIncluded, ns_id);
			file.AddMethod(entry);
		}
	}
	public class SymbolWriterImpl : ISymbolWriter
	{
		private MonoSymbolWriter msw;

		private int nextLocalIndex;

		private int currentToken;

		private string methodName;

		private Stack namespaceStack = new Stack();

		private bool methodOpened;

		private Hashtable documents = new Hashtable();

		private Guid guid;

		public SymbolWriterImpl(Guid guid)
		{
			this.guid = guid;
		}

		public void Close()
		{
			msw.WriteSymbolFile(guid);
		}

		public void CloseMethod()
		{
			if (methodOpened)
			{
				methodOpened = false;
				nextLocalIndex = 0;
				msw.CloseMethod();
			}
		}

		public void CloseNamespace()
		{
			namespaceStack.Pop();
			msw.CloseNamespace();
		}

		public void CloseScope(int endOffset)
		{
			msw.CloseScope(endOffset);
		}

		public ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType)
		{
			SymbolDocumentWriterImpl symbolDocumentWriterImpl = (SymbolDocumentWriterImpl)documents[url];
			if (symbolDocumentWriterImpl == null)
			{
				SourceFileEntry source = msw.DefineDocument(url);
				symbolDocumentWriterImpl = new SymbolDocumentWriterImpl(msw.DefineCompilationUnit(source));
				documents[url] = symbolDocumentWriterImpl;
			}
			return symbolDocumentWriterImpl;
		}

		public void DefineField(SymbolToken parent, string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3)
		{
		}

		public void DefineGlobalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3)
		{
		}

		public void DefineLocalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset)
		{
			msw.DefineLocalVariable(nextLocalIndex++, name);
		}

		public void DefineParameter(string name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3)
		{
		}

		public void DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns)
		{
			SourceFileEntry file = ((SymbolDocumentWriterImpl)document)?.Entry.SourceFile;
			for (int i = 0; i < offsets.Length; i++)
			{
				if (i <= 0 || offsets[i] != offsets[i - 1] || lines[i] != lines[i - 1] || columns[i] != columns[i - 1])
				{
					msw.MarkSequencePoint(offsets[i], file, lines[i], columns[i], is_hidden: false);
				}
			}
		}

		public void Initialize(IntPtr emitter, string filename, bool fFullBuild)
		{
			msw = new MonoSymbolWriter(filename);
		}

		public void OpenMethod(SymbolToken method)
		{
			currentToken = method.GetToken();
		}

		public void OpenNamespace(string name)
		{
			NamespaceInfo namespaceInfo = new NamespaceInfo();
			namespaceInfo.NamespaceID = -1;
			namespaceInfo.Name = name;
			namespaceStack.Push(namespaceInfo);
		}

		public int OpenScope(int startOffset)
		{
			return msw.OpenScope(startOffset);
		}

		public void SetMethodSourceRange(ISymbolDocumentWriter startDoc, int startLine, int startColumn, ISymbolDocumentWriter endDoc, int endLine, int endColumn)
		{
			int currentNamespace = GetCurrentNamespace(startDoc);
			SourceMethodImpl method = new SourceMethodImpl(methodName, currentToken, currentNamespace);
			msw.OpenMethod(((ICompileUnit)startDoc).Entry, currentNamespace, method);
			methodOpened = true;
		}

		public void SetScopeRange(int scopeID, int startOffset, int endOffset)
		{
		}

		public void SetSymAttribute(SymbolToken parent, string name, byte[] data)
		{
			if (name == "__name")
			{
				methodName = Encoding.UTF8.GetString(data);
			}
		}

		public void SetUnderlyingWriter(IntPtr underlyingWriter)
		{
		}

		public void SetUserEntryPoint(SymbolToken entryMethod)
		{
		}

		public void UsingNamespace(string fullName)
		{
			if (namespaceStack.Count == 0)
			{
				OpenNamespace("");
			}
			NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek();
			if (namespaceInfo.NamespaceID != -1)
			{
				NamespaceInfo namespaceInfo2 = namespaceInfo;
				CloseNamespace();
				OpenNamespace(namespaceInfo2.Name);
				namespaceInfo = (NamespaceInfo)namespaceStack.Peek();
				namespaceInfo.UsingClauses = namespaceInfo2.UsingClauses;
			}
			namespaceInfo.UsingClauses.Add(fullName);
		}

		private int GetCurrentNamespace(ISymbolDocumentWriter doc)
		{
			if (namespaceStack.Count == 0)
			{
				OpenNamespace("");
			}
			NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek();
			if (namespaceInfo.NamespaceID == -1)
			{
				string[] using_clauses = (string[])namespaceInfo.UsingClauses.ToArray(typeof(string));
				int parent = 0;
				if (namespaceStack.Count > 1)
				{
					namespaceStack.Pop();
					parent = ((NamespaceInfo)namespaceStack.Peek()).NamespaceID;
					namespaceStack.Push(namespaceInfo);
				}
				namespaceInfo.NamespaceID = msw.DefineNamespace(namespaceInfo.Name, ((ICompileUnit)doc).Entry, using_clauses, parent);
			}
			return namespaceInfo.NamespaceID;
		}
	}
	internal class SymbolDocumentWriterImpl : ISymbolDocumentWriter, ISourceFile, ICompileUnit
	{
		private CompileUnitEntry comp_unit;

		SourceFileEntry ISourceFile.Entry => comp_unit.SourceFile;

		public CompileUnitEntry Entry => comp_unit;

		public SymbolDocumentWriterImpl(CompileUnitEntry comp_unit)
		{
			this.comp_unit = comp_unit;
		}

		public void SetCheckSum(Guid algorithmId, byte[] checkSum)
		{
		}

		public void SetSource(byte[] source)
		{
		}
	}
	internal class SourceMethodImpl : IMethodDef
	{
		private string name;

		private int token;

		private int namespaceID;

		public string Name => name;

		public int NamespaceID => namespaceID;

		public int Token => token;

		public SourceMethodImpl(string name, int token, int namespaceID)
		{
			this.name = name;
			this.token = token;
			this.namespaceID = namespaceID;
		}
	}
	internal class NamespaceInfo
	{
		public string Name;

		public int NamespaceID;

		public ArrayList UsingClauses = new ArrayList();
	}
}
namespace Mono.Cecil.Mdb
{
	public sealed class MdbReaderProvider : ISymbolReaderProvider
	{
		public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
		{
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(Mixin.GetMdbFileName(fileName)));
		}

		public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
		{
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(symbolStream));
		}
	}
	public sealed class MdbReader : ISymbolReader, IDisposable
	{
		private readonly ModuleDefinition module;

		private readonly MonoSymbolFile symbol_file;

		private readonly Dictionary<string, Document> documents;

		public MdbReader(ModuleDefinition module, MonoSymbolFile symFile)
		{
			this.module = module;
			symbol_file = symFile;
			documents = new Dictionary<string, Document>();
		}

		public ISymbolWriterProvider GetWriterProvider()
		{
			return (ISymbolWriterProvider)(object)new MdbWriterProvider();
		}

		public bool ProcessDebugHeader(ImageDebugHeader header)
		{
			return symbol_file.Guid == module.Mvid;
		}

		public MethodDebugInformation Read(MethodDefinition method)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			MetadataToken metadataToken = ((MemberReference)method).MetadataToken;
			MethodEntry methodByToken = symbol_file.GetMethodByToken(((MetadataToken)(ref metadataToken)).ToInt32());
			if (methodByToken == null)
			{
				return null;
			}
			MethodDebugInformation val = new MethodDebugInformation(method);
			val.code_size = ReadCodeSize(method);
			ScopeDebugInformation[] scopes = ReadScopes(methodByToken, val);
			ReadLineNumbers(methodByToken, val);
			ReadLocalVariables(methodByToken, scopes);
			return val;
		}

		private static int ReadCodeSize(MethodDefinition method)
		{
			return ((MemberReference)method).Module.Read<MethodDefinition, int>(method, (Func<MethodDefinition, MetadataReader, int>)((MethodDefinition m, MetadataReader reader) => reader.ReadCodeSize(m)));
		}

		private static void ReadLocalVariables(MethodEntry entry, ScopeDebugInformation[] scopes)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			LocalVariableEntry[] locals = entry.GetLocals();
			for (int i = 0; i < locals.Length; i++)
			{
				LocalVariableEntry localVariableEntry = locals[i];
				VariableDebugInformation val = new VariableDebugInformation(localVariableEntry.Index, localVariableEntry.Name);
				int blockIndex = localVariableEntry.BlockIndex;
				if (blockIndex >= 0 && blockIndex < scopes.Length)
				{
					ScopeDebugInformation val2 = scopes[blockIndex];
					if (val2 != null)
					{
						val2.Variables.Add(val);
					}
				}
			}
		}

		private void ReadLineNumbers(MethodEntry entry, MethodDebugInformation info)
		{
			LineNumberTable lineNumberTable = entry.GetLineNumberTable();
			info.sequence_points = new Collection<SequencePoint>(lineNumberTable.LineNumbers.Length);
			for (int i = 0; i < lineNumberTable.LineNumbers.Length; i++)
			{
				LineNumberEntry lineNumberEntry = lineNumberTable.LineNumbers[i];
				if (i <= 0 || lineNumberTable.LineNumbers[i - 1].Offset != lineNumberEntry.Offset)
				{
					info.sequence_points.Add(LineToSequencePoint(lineNumberEntry));
				}
			}
		}

		private Document GetDocument(SourceFileEntry file)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			string fileName = file.FileName;
			if (documents.TryGetValue(fileName, out var value))
			{
				return value;
			}
			value = new Document(fileName)
			{
				Hash = file.Checksum
			};
			documents.Add(fileName, value);
			return value;
		}

		private static ScopeDebugInformation[] ReadScopes(MethodEntry entry, MethodDebugInformation info)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0039: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			CodeBlockEntry[] codeBlocks = entry.GetCodeBlocks();
			ScopeDebugInformation[] array = (ScopeDebugInformation[])(object)new ScopeDebugInformation[codeBlocks.Length + 1];
			ScopeDebugInformation val = new ScopeDebugInformation
			{
				Start = new InstructionOffset(0),
				End = new InstructionOffset(info.code_size)
			};
			ScopeDebugInformation scope = val;
			array[0] = val;
			info.scope = scope;
			CodeBlockEntry[] array2 = codeBlocks;
			foreach (CodeBlockEntry codeBlockEntry in array2)
			{
				if (codeBlockEntry.BlockType == CodeBlockEntry.Type.Lexical || codeBlockEntry.BlockType == CodeBlockEntry.Type.CompilerGenerated)
				{
					ScopeDebugInformation val2 = new ScopeDebugInformation();
					val2.Start = new InstructionOffset(codeBlockEntry.StartOffset);
					val2.End = new InstructionOffset(codeBlockEntry.EndOffset);
					array[codeBlockEntry.Index + 1] = val2;
					if (!AddScope(info.scope.Scopes, val2))
					{
						info.scope.Scopes.Add(val2);
					}
				}
			}
			return array;
		}

		private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ScopeDebugInformation current = enumerator.Current;
					if (current.HasScopes && AddScope(current.Scopes, scope))
					{
						return true;
					}
					InstructionOffset val = scope.Start;
					int offset = ((InstructionOffset)(ref val)).Offset;
					val = current.Start;
					if (offset >= ((InstructionOffset)(ref val)).Offset)
					{
						val = scope.End;
						int offset2 = ((InstructionOffset)(ref val)).Offset;
						val = current.End;
						if (offset2 <= ((InstructionOffset)(ref val)).Offset)
						{
							current.Scopes.Add(scope);
							return true;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return false;
		}

		private SequencePoint LineToSequencePoint(LineNumberEntry line)
		{
			//IL_001f: 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_0030: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			SourceFileEntry sourceFile = symbol_file.GetSourceFile(line.File);
			return new SequencePoint(line.Offset, GetDocument(sourceFile))
			{
				StartLine = line.Row,
				EndLine = line.EndRow,
				StartColumn = line.Column,
				EndColumn = line.EndColumn
			};
		}

		public void Dispose()
		{
			symbol_file.Dispose();
		}
	}
	internal static class MethodEntryExtensions
	{
		public static bool HasColumnInfo(this MethodEntry entry)
		{
			return (entry.MethodFlags & MethodEntry.Flags.ColumnsInfoIncluded) != 0;
		}

		public static bool HasEndInfo(this MethodEntry entry)
		{
			return (entry.MethodFlags & MethodEntry.Flags.EndInfoIncluded) != 0;
		}
	}
	public sealed class MdbWriterProvider : ISymbolWriterProvider
	{
		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName)
		{
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolWriter)(object)new MdbWriter(module.Mvid, fileName);
		}

		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream)
		{
			throw new NotImplementedException();
		}
	}
	public sealed class MdbWriter : ISymbolWriter, IDisposable
	{
		private class SourceFile : ISourceFile
		{
			private readonly CompileUnitEntry compilation_unit;

			private readonly SourceFileEntry entry;

			public SourceFileEntry Entry => entry;

			public CompileUnitEntry CompilationUnit => compilation_unit;

			public SourceFile(CompileUnitEntry comp_unit, SourceFileEntry entry)
			{
				compilation_unit = comp_unit;
				this.entry = entry;
			}
		}

		private class SourceMethod : IMethodDef
		{
			private readonly MethodDefinition method;

			public string Name => ((MemberReference)method).Name;

			public int Token
			{
				get
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_000b: Unknown result type (might be due to invalid IL or missing references)
					MetadataToken metadataToken = ((MemberReference)method).MetadataToken;
					return ((MetadataToken)(ref metadataToken)).ToInt32();
				}
			}

			public SourceMethod(MethodDefinition method)
			{
				this.method = method;
			}
		}

		private readonly Guid mvid;

		private readonly MonoSymbolWriter writer;

		private readonly Dictionary<string, SourceFile> source_files;

		public MdbWriter(Guid mvid, string assembly)
		{
			this.mvid = mvid;
			writer = new MonoSymbolWriter(assembly);
			source_files = new Dictionary<string, SourceFile>();
		}

		public ISymbolReaderProvider GetReaderProvider()
		{
			return (ISymbolReaderProvider)(object)new MdbReaderProvider();
		}

		private SourceFile GetSourceFile(Document document)
		{
			string url = document.Url;
			if (source_files.TryGetValue(url, out var value))
			{
				return value;
			}
			SourceFileEntry sourceFileEntry = writer.DefineDocument(url, null, (document.Hash != null && document.Hash.Length == 16) ? document.Hash : null);
			value = new SourceFile(writer.DefineCompilationUnit(sourceFileEntry), sourceFileEntry);
			source_files.Add(url, value);
			return value;
		}

		private void Populate(Collection<SequencePoint> sequencePoints, int[] offsets, int[] startRows, int[] endRows, int[] startCols, int[] endCols, out SourceFile file)
		{
			SourceFile sourceFile = null;
			for (int i = 0; i < sequencePoints.Count; i++)
			{
				SequencePoint val = sequencePoints[i];
				offsets[i] = val.Offset;
				if (sourceFile == null)
				{
					sourceFile = GetSourceFile(val.Document);
				}
				startRows[i] = val.StartLine;
				endRows[i] = val.EndLine;
				startCols[i] = val.StartColumn;
				endCols[i] = val.EndColumn;
			}
			file = sourceFile;
		}

		public void Write(MethodDebugInformation info)
		{
			SourceMethod method = new SourceMethod(info.method);
			Collection<SequencePoint> sequencePoints = info.SequencePoints;
			int count = sequencePoints.Count;
			if (count != 0)
			{
				int[] array = new int[count];
				int[] array2 = new int[count];
				int[] array3 = new int[count];
				int[] array4 = new int[count];
				int[] array5 = new int[count];
				Populate(sequencePoints, array, array2, array3, array4, array5, out var file);
				SourceMethodBuilder sourceMethodBuilder = writer.OpenMethod(file.CompilationUnit, 0, method);
				for (int i = 0; i < count; i++)
				{
					sourceMethodBuilder.MarkSequencePoint(array[i], file.CompilationUnit.SourceFile, array2[i], array4[i], array3[i], array5[i], is_hidden: false);
				}
				if (info.scope != null)
				{
					WriteRootScope(info.scope, info);
				}
				writer.CloseMethod();
			}
		}

		private void WriteRootScope(ScopeDebugInformation scope, MethodDebugInformation info)
		{
			WriteScopeVariables(scope);
			if (scope.HasScopes)
			{
				WriteScopes(scope.Scopes, info);
			}
		}

		private void WriteScope(ScopeDebugInformation scope, MethodDebugInformation info)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			MonoSymbolWriter monoSymbolWriter = writer;
			InstructionOffset val = scope.Start;
			monoSymbolWriter.OpenScope(((InstructionOffset)(ref val)).Offset);
			WriteScopeVariables(scope);
			if (scope.HasScopes)
			{
				WriteScopes(scope.Scopes, info);
			}
			MonoSymbolWriter monoSymbolWriter2 = writer;
			val = scope.End;
			int end_offset;
			if (!((InstructionOffset)(ref val)).IsEndOfMethod)
			{
				val = scope.End;
				end_offset = ((InstructionOffset)(ref val)).Offset;
			}
			else
			{
				end_offset = info.code_size;
			}
			monoSymbolWriter2.CloseScope(end_offset);
		}

		private void WriteScopes(Collection<ScopeDebugInformation> scopes, MethodDebugInformation info)
		{
			for (int i = 0; i < scopes.Count; i++)
			{
				WriteScope(scopes[i], info);
			}
		}

		private void WriteScopeVariables(ScopeDebugInformation scope)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (!scope.HasVariables)
			{
				return;
			}
			Enumerator<VariableDebugInformation> enumerator = scope.variables.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					VariableDebugInformation current = enumerator.Current;
					if (!string.IsNullOrEmpty(current.Name))
					{
						writer.DefineLocalVariable(current.Index, current.Name);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public ImageDebugHeader GetDebugHeader()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			return new ImageDebugHeader();
		}

		public void Dispose()
		{
			writer.WriteSymbolFile(mvid);
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/core/Mono.Cecil.Pdb.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using Microsoft.Cci;
using Microsoft.Cci.Pdb;
using Mono.Cecil.Cil;
using Mono.Cecil.PE;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil.Pdb")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyVersion("0.10.4.0")]
namespace Mono.Cecil.Pdb
{
	[ComImport]
	[Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface ISymUnmanagedDocumentWriter
	{
	}
	[ComImport]
	[Guid("0B97726E-9E6D-4f05-9A26-424022093CAA")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface ISymUnmanagedWriter2
	{
		void DefineDocument([In][MarshalAs(UnmanagedType.LPWStr)] string url, [In] ref Guid langauge, [In] ref Guid languageVendor, [In] ref Guid documentType, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedDocumentWriter pRetVal);

		void SetUserEntryPoint([In] int methodToken);

		void OpenMethod([In] int methodToken);

		void CloseMethod();

		void OpenScope([In] int startOffset, out int pRetVal);

		void CloseScope([In] int endOffset);

		void SetScopeRange_Placeholder();

		void DefineLocalVariable_Placeholder();

		void DefineParameter_Placeholder();

		void DefineField_Placeholder();

		void DefineGlobalVariable_Placeholder();

		void Close();

		void SetSymAttribute(uint parent, string name, uint data, IntPtr signature);

		void OpenNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string name);

		void CloseNamespace();

		void UsingNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string fullName);

		void SetMethodSourceRange_Placeholder();

		void Initialize([In][MarshalAs(UnmanagedType.IUnknown)] object emitter, [In][MarshalAs(UnmanagedType.LPWStr)] string filename, [In] IStream pIStream, [In] bool fFullBuild);

		void GetDebugInfo(out ImageDebugDirectory pIDD, [In] int cData, out int pcData, [In][Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data);

		void DefineSequencePoints([In][MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter document, [In] int spCount, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns);

		void RemapToken_Placeholder();

		void Initialize2_Placeholder();

		void DefineConstant_Placeholder();

		void Abort_Placeholder();

		void DefineLocalVariable2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In] int attributes, [In] int sigToken, [In] int addrKind, [In] int addr1, [In] int addr2, [In] int addr3, [In] int startOffset, [In] int endOffset);

		void DefineGlobalVariable2_Placeholder();

		void DefineConstant2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In][MarshalAs(UnmanagedType.Struct)] object variant, [In] int sigToken);
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")]
	internal interface IMetaDataEmit
	{
		void SetModuleProps(string szName);

		void Save(string szFile, uint dwSaveFlags);

		void SaveToStream(IntPtr pIStream, uint dwSaveFlags);

		uint GetSaveSize(uint fSave);

		uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements);

		uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser);

		void SetHandler([In][MarshalAs(UnmanagedType.IUnknown)] object pUnk);

		uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags);

		void DefineMethodImpl(uint td, uint tkBody, uint tkDecl);

		uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName);

		uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit);

		uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob);

		uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent);

		uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods);

		void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize);

		void DeleteClassLayout(uint td);

		void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType);

		void DeleteFieldMarshal(uint tk);

		uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission);

		void SetRVA(uint md, uint ulRVA);

		uint GetTokenFromSig(IntPtr pvSig, uint cbSig);

		uint DefineModuleRef(string szName);

		void SetParent(uint mr, uint tk);

		uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig);

		void SaveToMemory(IntPtr pbData, uint cbData);

		uint DefineUserString(string szString, uint cchString);

		void DeleteToken(uint tkObj);

		void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags);

		void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements);

		void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods);

		uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission);

		void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);

		void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL);

		void DeletePinvokeMap(uint tk);

		uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute);

		void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute);

		uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods);

		uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods);

		void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue);

		uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs);

		void ApplyEditAndContinue([MarshalAs(UnmanagedType.IUnknown)] object pImport);

		uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax);

		void SetMethodImplFlags(uint md, uint dwImplFlags);

		void SetFieldRVA(uint fd, uint ulRVA);

		void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, [MarshalAs(UnmanagedType.IUnknown)] object pHandler);

		void MergeEnd();
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44")]
	internal interface IMetaDataImport
	{
		[PreserveSig]
		void CloseEnum(uint hEnum);

		uint CountEnum(uint hEnum);

		void ResetEnum(uint hEnum, uint ulPos);

		uint EnumTypeDefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeDefs, uint cMax);

		uint EnumInterfaceImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rImpls, uint cMax);

		uint EnumTypeRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeRefs, uint cMax);

		uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass);

		Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName);

		uint GetModuleFromScope();

		uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags);

		uint GetInterfaceImplProps(uint iiImpl, out uint pClass);

		uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName);

		uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope);

		uint EnumMembers(ref uint phEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMembers, uint cMax);

		uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMembers, uint cMax);

		uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax);

		uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethods, uint cMax);

		uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax);

		uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rFields, uint cMax);

		uint EnumParams(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rParams, uint cMax);

		uint EnumMemberRefs(ref uint phEnum, uint tkParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMemberRefs, uint cMax);

		uint EnumMethodImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodBody, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodDecl, uint cMax);

		uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rPermission, uint cMax);

		uint FindMember(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint FindMethod(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint FindField(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint FindMemberRef(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob);

		uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA);

		uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob);

		uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax);

		uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax);

		uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint cMax);

		uint EnumMethodSemantics(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rEventProp, uint cMax);

		uint GetMethodSemantics(uint mb, uint tkEventProp);

		uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset);

		uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType);

		uint GetRVA(uint tk, out uint pulCodeRVA);

		uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission);

		uint GetSigFromToken(uint mdSig, out IntPtr ppvSig);

		uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName);

		uint EnumModuleRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rModuleRefs, uint cmax);

		uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig);

		uint GetNameFromToken(uint tk);

		uint EnumUnresolvedMethods(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rMethods, uint cMax);

		uint GetUserString(uint stk, StringBuilder szString, uint cchString);

		uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName);

		uint EnumSignatures(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rSignatures, uint cmax);

		uint EnumTypeSpecs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeSpecs, uint cmax);

		uint EnumUserStrings(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rStrings, uint cmax);

		[PreserveSig]
		int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam);

		uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rCustomAttributes, uint cMax);

		uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob);

		uint FindTypeRef(uint tkResolutionScope, string szName);

		uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue);

		uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue);

		uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint cMax);

		uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue);

		uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData);

		[PreserveSig]
		[return: MarshalAs(UnmanagedType.Bool)]
		bool IsValidToken(uint tk);

		uint GetNestedClassProps(uint tdNestedClass);

		uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig);

		int IsGlobal(uint pd);
	}
	internal class ModuleMetadata : IMetaDataEmit, IMetaDataImport
	{
		private readonly ModuleDefinition module;

		private Dictionary<uint, TypeDefinition> types;

		private Dictionary<uint, MethodDefinition> methods;

		public ModuleMetadata(ModuleDefinition module)
		{
			this.module = module;
		}

		private bool TryGetType(uint token, out TypeDefinition type)
		{
			if (types == null)
			{
				InitializeMetadata(module);
			}
			return types.TryGetValue(token, out type);
		}

		private bool TryGetMethod(uint token, out MethodDefinition method)
		{
			if (methods == null)
			{
				InitializeMetadata(module);
			}
			return methods.TryGetValue(token, out method);
		}

		private void InitializeMetadata(ModuleDefinition module)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			types = new Dictionary<uint, TypeDefinition>();
			methods = new Dictionary<uint, MethodDefinition>();
			foreach (TypeDefinition type in module.GetTypes())
			{
				Dictionary<uint, TypeDefinition> dictionary = types;
				MetadataToken metadataToken = ((MemberReference)type).MetadataToken;
				dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), type);
				InitializeMethods(type);
			}
		}

		private void InitializeMethods(TypeDefinition type)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//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_0022: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					Dictionary<uint, MethodDefinition> dictionary = methods;
					MetadataToken metadataToken = ((MemberReference)current).MetadataToken;
					dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void SetModuleProps(string szName)
		{
			throw new NotImplementedException();
		}

		public void Save(string szFile, uint dwSaveFlags)
		{
			throw new NotImplementedException();
		}

		public void SaveToStream(IntPtr pIStream, uint dwSaveFlags)
		{
			throw new NotImplementedException();
		}

		public uint GetSaveSize(uint fSave)
		{
			throw new NotImplementedException();
		}

		public uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements)
		{
			throw new NotImplementedException();
		}

		public uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser)
		{
			throw new NotImplementedException();
		}

		public void SetHandler(object pUnk)
		{
			throw new NotImplementedException();
		}

		public uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags)
		{
			throw new NotImplementedException();
		}

		public void DefineMethodImpl(uint td, uint tkBody, uint tkDecl)
		{
			throw new NotImplementedException();
		}

		public uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName)
		{
			throw new NotImplementedException();
		}

		public uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit)
		{
			throw new NotImplementedException();
		}

		public uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent)
		{
			throw new NotImplementedException();
		}

		public uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize)
		{
			throw new NotImplementedException();
		}

		public void DeleteClassLayout(uint td)
		{
			throw new NotImplementedException();
		}

		public void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType)
		{
			throw new NotImplementedException();
		}

		public void DeleteFieldMarshal(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission)
		{
			throw new NotImplementedException();
		}

		public void SetRVA(uint md, uint ulRVA)
		{
			throw new NotImplementedException();
		}

		public uint GetTokenFromSig(IntPtr pvSig, uint cbSig)
		{
			throw new NotImplementedException();
		}

		public uint DefineModuleRef(string szName)
		{
			throw new NotImplementedException();
		}

		public void SetParent(uint mr, uint tk)
		{
			throw new NotImplementedException();
		}

		public uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig)
		{
			throw new NotImplementedException();
		}

		public void SaveToMemory(IntPtr pbData, uint cbData)
		{
			throw new NotImplementedException();
		}

		public uint DefineUserString(string szString, uint cchString)
		{
			throw new NotImplementedException();
		}

		public void DeleteToken(uint tkObj)
		{
			throw new NotImplementedException();
		}

		public void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags)
		{
			throw new NotImplementedException();
		}

		public void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements)
		{
			throw new NotImplementedException();
		}

		public void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission)
		{
			throw new NotImplementedException();
		}

		public void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL)
		{
			throw new NotImplementedException();
		}

		public void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL)
		{
			throw new NotImplementedException();
		}

		public void DeletePinvokeMap(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute)
		{
			throw new NotImplementedException();
		}

		public void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute)
		{
			throw new NotImplementedException();
		}

		public uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods)
		{
			throw new NotImplementedException();
		}

		public void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue)
		{
			throw new NotImplementedException();
		}

		public uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs)
		{
			throw new NotImplementedException();
		}

		public void ApplyEditAndContinue(object pImport)
		{
			throw new NotImplementedException();
		}

		public uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax)
		{
			throw new NotImplementedException();
		}

		public void SetMethodImplFlags(uint md, uint dwImplFlags)
		{
			throw new NotImplementedException();
		}

		public void SetFieldRVA(uint fd, uint ulRVA)
		{
			throw new NotImplementedException();
		}

		public void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, object pHandler)
		{
			throw new NotImplementedException();
		}

		public void MergeEnd()
		{
			throw new NotImplementedException();
		}

		public void CloseEnum(uint hEnum)
		{
			throw new NotImplementedException();
		}

		public uint CountEnum(uint hEnum)
		{
			throw new NotImplementedException();
		}

		public void ResetEnum(uint hEnum, uint ulPos)
		{
			throw new NotImplementedException();
		}

		public uint EnumTypeDefs(ref uint phEnum, uint[] rTypeDefs, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumInterfaceImpls(ref uint phEnum, uint td, uint[] rImpls, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumTypeRefs(ref uint phEnum, uint[] rTypeRefs, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass)
		{
			throw new NotImplementedException();
		}

		public Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName)
		{
			throw new NotImplementedException();
		}

		public uint GetModuleFromScope()
		{
			throw new NotImplementedException();
		}

		public uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected I4, but got Unknown
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGetType(td, out var type))
			{
				Marshal.WriteInt16(szTypeDef, 0);
				pchTypeDef = 1u;
				return 0u;
			}
			WriteString(((TypeReference)type).IsNested ? ((MemberReference)type).Name : ((MemberReference)type).FullName, szTypeDef, cchTypeDef, out pchTypeDef);
			WriteIntPtr(pdwTypeDefFlags, (uint)(int)type.Attributes);
			if (type.BaseType == null)
			{
				return 0u;
			}
			MetadataToken metadataToken = ((MemberReference)type.BaseType).MetadataToken;
			return ((MetadataToken)(ref metadataToken)).ToUInt32();
		}

		private static void WriteIntPtr(IntPtr ptr, uint value)
		{
			if (!(ptr == IntPtr.Zero))
			{
				Marshal.WriteInt32(ptr, (int)value);
			}
		}

		private static void WriteString(string str, IntPtr buffer, uint bufferSize, out uint chars)
		{
			uint num = ((str.Length + 1 >= bufferSize) ? (bufferSize - 1) : ((uint)str.Length));
			chars = num + 1;
			int num2 = 0;
			for (int i = 0; i < num; i++)
			{
				Marshal.WriteInt16(buffer, num2, str[i]);
				num2 += 2;
			}
			Marshal.WriteInt16(buffer, num2, 0);
		}

		public uint GetInterfaceImplProps(uint iiImpl, out uint pClass)
		{
			throw new NotImplementedException();
		}

		public uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName)
		{
			throw new NotImplementedException();
		}

		public uint ResolveTypeRef(uint tr, ref Guid riid, out object ppIScope)
		{
			throw new NotImplementedException();
		}

		public uint EnumMembers(ref uint phEnum, uint cl, uint[] rMembers, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, uint[] rMembers, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, uint[] rMethods, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, uint[] rFields, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumParams(ref uint phEnum, uint mb, uint[] rParams, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMemberRefs(ref uint phEnum, uint tkParent, uint[] rMemberRefs, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethodImpls(ref uint phEnum, uint td, uint[] rMethodBody, uint[] rMethodDecl, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, uint[] rPermission, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint FindMember(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindMethod(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindField(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindMemberRef(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected I4, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected I4, but got Unknown
			if (!TryGetMethod(mb, out var method))
			{
				Marshal.WriteInt16(szMethod, 0);
				pchMethod = 1u;
				pClass = 0u;
				return 0u;
			}
			MetadataToken metadataToken = ((MemberReference)method.DeclaringType).MetadataToken;
			pClass = ((MetadataToken)(ref metadataToken)).ToUInt32();
			WriteString(((MemberReference)method).Name, szMethod, cchMethod, out pchMethod);
			WriteIntPtr(pdwAttr, (uint)(int)method.Attributes);
			WriteIntPtr(pulCodeRVA, (uint)method.RVA);
			return (uint)(int)method.ImplAttributes;
		}

		public uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob)
		{
			throw new NotImplementedException();
		}

		public uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, uint[] rmdOtherMethod, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint EnumMethodSemantics(ref uint phEnum, uint mb, uint[] rEventProp, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetMethodSemantics(uint mb, uint tkEventProp)
		{
			throw new NotImplementedException();
		}

		public uint GetClassLayout(uint td, out uint pdwPackSize, IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset)
		{
			throw new NotImplementedException();
		}

		public uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType)
		{
			throw new NotImplementedException();
		}

		public uint GetRVA(uint tk, out uint pulCodeRVA)
		{
			throw new NotImplementedException();
		}

		public uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission)
		{
			throw new NotImplementedException();
		}

		public uint GetSigFromToken(uint mdSig, out IntPtr ppvSig)
		{
			throw new NotImplementedException();
		}

		public uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName)
		{
			throw new NotImplementedException();
		}

		public uint EnumModuleRefs(ref uint phEnum, uint[] rModuleRefs, uint cmax)
		{
			throw new NotImplementedException();
		}

		public uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig)
		{
			throw new NotImplementedException();
		}

		public uint GetNameFromToken(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint EnumUnresolvedMethods(ref uint phEnum, uint[] rMethods, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetUserString(uint stk, StringBuilder szString, uint cchString)
		{
			throw new NotImplementedException();
		}

		public uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName)
		{
			throw new NotImplementedException();
		}

		public uint EnumSignatures(ref uint phEnum, uint[] rSignatures, uint cmax)
		{
			throw new NotImplementedException();
		}

		public uint EnumTypeSpecs(ref uint phEnum, uint[] rTypeSpecs, uint cmax)
		{
			throw new NotImplementedException();
		}

		public uint EnumUserStrings(ref uint phEnum, uint[] rStrings, uint cmax)
		{
			throw new NotImplementedException();
		}

		public int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam)
		{
			throw new NotImplementedException();
		}

		public uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, uint[] rCustomAttributes, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob)
		{
			throw new NotImplementedException();
		}

		public uint FindTypeRef(uint tkResolutionScope, string szName)
		{
			throw new NotImplementedException();
		}

		public uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
		{
			throw new NotImplementedException();
		}

		public uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
		{
			throw new NotImplementedException();
		}

		public uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, uint[] rmdOtherMethod, uint cMax)
		{
			throw new NotImplementedException();
		}

		public uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue)
		{
			throw new NotImplementedException();
		}

		public uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData)
		{
			throw new NotImplementedException();
		}

		public bool IsValidToken(uint tk)
		{
			throw new NotImplementedException();
		}

		public uint GetNestedClassProps(uint tdNestedClass)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGetType(tdNestedClass, out var type))
			{
				return 0u;
			}
			if (!((TypeReference)type).IsNested)
			{
				return 0u;
			}
			MetadataToken metadataToken = ((MemberReference)type.DeclaringType).MetadataToken;
			return ((MetadataToken)(ref metadataToken)).ToUInt32();
		}

		public uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig)
		{
			throw new NotImplementedException();
		}

		public int IsGlobal(uint pd)
		{
			throw new NotImplementedException();
		}
	}
	public class NativePdbReader : ISymbolReader, IDisposable
	{
		private int age;

		private Guid guid;

		private readonly Disposable<Stream> pdb_file;

		private readonly Dictionary<string, Document> documents = new Dictionary<string, Document>();

		private readonly Dictionary<uint, PdbFunction> functions = new Dictionary<uint, PdbFunction>();

		private readonly Dictionary<PdbScope, ImportDebugInformation> imports = new Dictionary<PdbScope, ImportDebugInformation>();

		internal NativePdbReader(Disposable<Stream> file)
		{
			//IL_0028: 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)
			pdb_file = file;
		}

		public ISymbolWriterProvider GetWriterProvider()
		{
			return (ISymbolWriterProvider)(object)new NativePdbWriterProvider();
		}

		public bool ProcessDebugHeader(ImageDebugHeader header)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Invalid comparison between Unknown and I4
			if (!header.HasEntries)
			{
				return false;
			}
			ImageDebugHeaderEntry codeViewEntry = Mixin.GetCodeViewEntry(header);
			if (codeViewEntry == null)
			{
				return false;
			}
			if ((int)codeViewEntry.Directory.Type != 2)
			{
				return false;
			}
			byte[] data = codeViewEntry.Data;
			if (data.Length < 24)
			{
				return false;
			}
			if (ReadInt32(data, 0) != 1396986706)
			{
				return false;
			}
			byte[] array = new byte[16];
			Buffer.BlockCopy(data, 4, array, 0, 16);
			guid = new Guid(array);
			age = ReadInt32(data, 20);
			return PopulateFunctions();
		}

		private static int ReadInt32(byte[] bytes, int start)
		{
			return bytes[start] | (bytes[start + 1] << 8) | (bytes[start + 2] << 16) | (bytes[start + 3] << 24);
		}

		private bool PopulateFunctions()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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)
			Disposable<Stream> val = pdb_file;
			try
			{
				Dictionary<uint, PdbTokenLine> tokenToSourceMapping;
				string sourceServerData;
				int num;
				Guid guid;
				PdbFunction[] array = PdbFile.LoadFunctions(pdb_file.value, out tokenToSourceMapping, out sourceServerData, out num, out guid);
				if (this.guid != guid)
				{
					return false;
				}
				PdbFunction[] array2 = array;
				foreach (PdbFunction pdbFunction in array2)
				{
					functions.Add(pdbFunction.token, pdbFunction);
				}
			}
			finally
			{
				((IDisposable)val).Dispose();
			}
			return true;
		}

		public MethodDebugInformation Read(MethodDefinition method)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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)
			//IL_0118: Expected O, but got Unknown
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Expected O, but got Unknown
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Expected O, but got Unknown
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Expected O, but got Unknown
			MetadataToken metadataToken = ((MemberReference)method).MetadataToken;
			if (!functions.TryGetValue(((MetadataToken)(ref metadataToken)).ToUInt32(), out var value))
			{
				return null;
			}
			MethodDebugInformation val = new MethodDebugInformation(method);
			ReadSequencePoints(value, val);
			val.scope = (ScopeDebugInformation)((!Mixin.IsNullOrEmpty<PdbScope>(value.scopes)) ? ((object)ReadScopeAndLocals(value.scopes[0], val)) : ((object)new ScopeDebugInformation
			{
				Start = new InstructionOffset(0),
				End = new InstructionOffset((int)value.length)
			}));
			uint tokenOfMethodWhoseUsingInfoAppliesToThisMethod = value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod;
			MetadataToken metadataToken2 = ((MemberReference)method).MetadataToken;
			if (tokenOfMethodWhoseUsingInfoAppliesToThisMethod != ((MetadataToken)(ref metadataToken2)).ToUInt32() && value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod != 0)
			{
				val.scope.import = GetImport(value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod, ((MemberReference)method).Module);
			}
			if (value.scopes.Length > 1)
			{
				for (int i = 1; i < value.scopes.Length; i++)
				{
					ScopeDebugInformation val2 = ReadScopeAndLocals(value.scopes[i], val);
					if (!AddScope(val.scope.Scopes, val2))
					{
						val.scope.Scopes.Add(val2);
					}
				}
			}
			if (value.iteratorScopes != null)
			{
				StateMachineScopeDebugInformation val3 = new StateMachineScopeDebugInformation();
				foreach (ILocalScope iteratorScope in value.iteratorScopes)
				{
					val3.Scopes.Add(new StateMachineScope((int)iteratorScope.Offset, (int)(iteratorScope.Offset + iteratorScope.Length + 1)));
				}
				((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val3);
			}
			if (value.synchronizationInformation != null)
			{
				AsyncMethodBodyDebugInformation val4 = new AsyncMethodBodyDebugInformation((int)value.synchronizationInformation.GeneratedCatchHandlerOffset);
				PdbSynchronizationPoint[] synchronizationPoints = value.synchronizationInformation.synchronizationPoints;
				foreach (PdbSynchronizationPoint pdbSynchronizationPoint in synchronizationPoints)
				{
					val4.Yields.Add(new InstructionOffset((int)pdbSynchronizationPoint.SynchronizeOffset));
					val4.Resumes.Add(new InstructionOffset((int)pdbSynchronizationPoint.ContinuationOffset));
					val4.ResumeMethods.Add(method);
				}
				((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val4);
				val.StateMachineKickOffMethod = (MethodDefinition)((MemberReference)method).Module.LookupToken((int)value.synchronizationInformation.kickoffMethodToken);
			}
			return val;
		}

		private Collection<ScopeDebugInformation> ReadScopeAndLocals(PdbScope[] scopes, MethodDebugInformation info)
		{
			Collection<ScopeDebugInformation> val = new Collection<ScopeDebugInformation>(scopes.Length);
			foreach (PdbScope pdbScope in scopes)
			{
				if (pdbScope != null)
				{
					val.Add(ReadScopeAndLocals(pdbScope, info));
				}
			}
			return val;
		}

		private ScopeDebugInformation ReadScopeAndLocals(PdbScope scope, MethodDebugInformation info)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Expected O, but got Unknown
			ScopeDebugInformation val = new ScopeDebugInformation();
			val.Start = new InstructionOffset((int)scope.offset);
			val.End = new InstructionOffset((int)(scope.offset + scope.length));
			if (!Mixin.IsNullOrEmpty<PdbSlot>(scope.slots))
			{
				val.variables = new Collection<VariableDebugInformation>(scope.slots.Length);
				PdbSlot[] slots = scope.slots;
				foreach (PdbSlot pdbSlot in slots)
				{
					if ((pdbSlot.flags & 1) == 0)
					{
						VariableDebugInformation val2 = new VariableDebugInformation((int)pdbSlot.slot, pdbSlot.name);
						if ((pdbSlot.flags & 4u) != 0)
						{
							val2.IsDebuggerHidden = true;
						}
						val.variables.Add(val2);
					}
				}
			}
			if (!Mixin.IsNullOrEmpty<PdbConstant>(scope.constants))
			{
				val.constants = new Collection<ConstantDebugInformation>(scope.constants.Length);
				PdbConstant[] constants = scope.constants;
				foreach (PdbConstant pdbConstant in constants)
				{
					TypeReference val3 = ((MemberReference)info.Method).Module.Read<PdbConstant, TypeReference>(pdbConstant, (Func<PdbConstant, MetadataReader, TypeReference>)((PdbConstant c, MetadataReader r) => r.ReadConstantSignature(new MetadataToken(c.token))));
					object obj = pdbConstant.value;
					if (val3 != null && !val3.IsValueType && obj is int && (int)obj == 0)
					{
						obj = null;
					}
					val.constants.Add(new ConstantDebugInformation(pdbConstant.name, val3, obj));
				}
			}
			if (!Mixin.IsNullOrEmpty<string>(scope.usedNamespaces))
			{
				if (imports.TryGetValue(scope, out var value))
				{
					val.import = value;
				}
				else
				{
					value = GetImport(scope, ((MemberReference)info.Method).Module);
					imports.Add(scope, value);
					val.import = value;
				}
			}
			val.scopes = ReadScopeAndLocals(scope.scopes, info);
			return val;
		}

		private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ScopeDebugInformation current = enumerator.Current;
					if (current.HasScopes && AddScope(current.Scopes, scope))
					{
						return true;
					}
					InstructionOffset val = scope.Start;
					int offset = ((InstructionOffset)(ref val)).Offset;
					val = current.Start;
					if (offset >= ((InstructionOffset)(ref val)).Offset)
					{
						val = scope.End;
						int offset2 = ((InstructionOffset)(ref val)).Offset;
						val = current.End;
						if (offset2 <= ((InstructionOffset)(ref val)).Offset)
						{
							current.Scopes.Add(scope);
							return true;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return false;
		}

		private ImportDebugInformation GetImport(uint token, ModuleDefinition module)
		{
			if (!functions.TryGetValue(token, out var value))
			{
				return null;
			}
			if (value.scopes.Length != 1)
			{
				return null;
			}
			PdbScope pdbScope = value.scopes[0];
			if (imports.TryGetValue(pdbScope, out var value2))
			{
				return value2;
			}
			value2 = GetImport(pdbScope, module);
			imports.Add(pdbScope, value2);
			return value2;
		}

		private static ImportDebugInformation GetImport(PdbScope scope, ModuleDefinition module)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Expected O, but got Unknown
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			//IL_010a: 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_0121: Expected O, but got Unknown
			if (Mixin.IsNullOrEmpty<string>(scope.usedNamespaces))
			{
				return null;
			}
			ImportDebugInformation val = new ImportDebugInformation();
			string[] usedNamespaces = scope.usedNamespaces;
			foreach (string text in usedNamespaces)
			{
				if (string.IsNullOrEmpty(text))
				{
					continue;
				}
				ImportTarget val2 = null;
				string text2 = text.Substring(1);
				switch (text[0])
				{
				case 'U':
					val2 = new ImportTarget((ImportTargetKind)1)
					{
						@namespace = text2
					};
					break;
				case 'T':
				{
					TypeReference val4 = TypeParser.ParseType(module, text2, false);
					if (val4 != null)
					{
						val2 = new ImportTarget((ImportTargetKind)3)
						{
							type = val4
						};
					}
					break;
				}
				case 'A':
				{
					int num = text.IndexOf(' ');
					if (num < 0)
					{
						val2 = new ImportTarget((ImportTargetKind)1)
						{
							@namespace = text
						};
						break;
					}
					string alias = text.Substring(1, num - 1);
					string text3 = text.Substring(num + 2);
					switch (text[num + 1])
					{
					case 'U':
						val2 = new ImportTarget((ImportTargetKind)7)
						{
							alias = alias,
							@namespace = text3
						};
						break;
					case 'T':
					{
						TypeReference val3 = TypeParser.ParseType(module, text3, false);
						if (val3 != null)
						{
							val2 = new ImportTarget((ImportTargetKind)9)
							{
								alias = alias,
								type = val3
							};
						}
						break;
					}
					}
					break;
				}
				case '*':
					val2 = new ImportTarget((ImportTargetKind)1)
					{
						@namespace = text2
					};
					break;
				case '@':
					if (!text2.StartsWith("P:"))
					{
						continue;
					}
					val2 = new ImportTarget((ImportTargetKind)1)
					{
						@namespace = text2.Substring(2)
					};
					break;
				}
				if (val2 != null)
				{
					val.Targets.Add(val2);
				}
			}
			return val;
		}

		private void ReadSequencePoints(PdbFunction function, MethodDebugInformation info)
		{
			if (function.lines != null)
			{
				info.sequence_points = new Collection<SequencePoint>();
				PdbLines[] lines = function.lines;
				foreach (PdbLines lines2 in lines)
				{
					ReadLines(lines2, info);
				}
			}
		}

		private void ReadLines(PdbLines lines, MethodDebugInformation info)
		{
			Document document = GetDocument(lines.file);
			PdbLine[] lines2 = lines.lines;
			for (int i = 0; i < lines2.Length; i++)
			{
				ReadLine(lines2[i], document, info);
			}
		}

		private static void ReadLine(PdbLine line, Document document, MethodDebugInformation info)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			SequencePoint val = new SequencePoint((int)line.offset, document);
			val.StartLine = (int)line.lineBegin;
			val.StartColumn = line.colBegin;
			val.EndLine = (int)line.lineEnd;
			val.EndColumn = line.colEnd;
			info.sequence_points.Add(val);
		}

		private Document GetDocument(PdbSource source)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			string name = source.name;
			if (documents.TryGetValue(name, out var value))
			{
				return value;
			}
			value = new Document(name)
			{
				Language = PdbGuidMapping.ToLanguage(source.language),
				LanguageVendor = PdbGuidMapping.ToVendor(source.vendor),
				Type = PdbGuidMapping.ToType(source.doctype)
			};
			documents.Add(name, value);
			return value;
		}

		public void Dispose()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			pdb_file.Dispose();
		}
	}
	public class NativePdbWriter : ISymbolWriter, IDisposable
	{
		private readonly ModuleDefinition module;

		private readonly MetadataBuilder metadata;

		private readonly SymWriter writer;

		private readonly Dictionary<string, SymDocumentWriter> documents;

		private readonly Dictionary<ImportDebugInformation, MetadataToken> import_info_to_parent;

		internal NativePdbWriter(ModuleDefinition module, SymWriter writer)
		{
			this.module = module;
			metadata = module.metadata_builder;
			this.writer = writer;
			documents = new Dictionary<string, SymDocumentWriter>();
			import_info_to_parent = new Dictionary<ImportDebugInformation, MetadataToken>();
		}

		public ISymbolReaderProvider GetReaderProvider()
		{
			return (ISymbolReaderProvider)(object)new NativePdbReaderProvider();
		}

		public ImageDebugHeader GetDebugHeader()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			ImageDebugDirectory idd;
			byte[] debugInfo = writer.GetDebugInfo(out idd);
			idd.TimeDateStamp = (int)module.timestamp;
			return new ImageDebugHeader(new ImageDebugHeaderEntry(idd, debugInfo));
		}

		public void Write(MethodDebugInformation info)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			MetadataToken metadataToken = ((MemberReference)info.method).MetadataToken;
			int methodToken = ((MetadataToken)(ref metadataToken)).ToInt32();
			if (info.HasSequencePoints || info.scope != null || ((DebugInformation)info).HasCustomDebugInformations || info.StateMachineKickOffMethod != null)
			{
				writer.OpenMethod(methodToken);
				if (!Mixin.IsNullOrEmpty<SequencePoint>(info.sequence_points))
				{
					DefineSequencePoints(info.sequence_points);
				}
				MetadataToken import_parent = default(MetadataToken);
				if (info.scope != null)
				{
					DefineScope(info.scope, info, out import_parent);
				}
				DefineCustomMetadata(info, import_parent);
				writer.CloseMethod();
			}
		}

		private void DefineCustomMetadata(MethodDebugInformation info, MetadataToken import_parent)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			CustomMetadataWriter customMetadataWriter = new CustomMetadataWriter(writer);
			if (((MetadataToken)(ref import_parent)).RID != 0)
			{
				customMetadataWriter.WriteForwardInfo(import_parent);
			}
			else if (info.scope != null && info.scope.Import != null && info.scope.Import.HasTargets)
			{
				customMetadataWriter.WriteUsingInfo(info.scope.Import);
			}
			if (info.Method.HasCustomAttributes)
			{
				Enumerator<CustomAttribute> enumerator = info.Method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						TypeReference attributeType = current.AttributeType;
						if (Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "IteratorStateMachineAttribute") || Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute"))
						{
							CustomAttributeArgument val = current.ConstructorArguments[0];
							object value = ((CustomAttributeArgument)(ref val)).Value;
							TypeReference val2 = (TypeReference)((value is TypeReference) ? value : null);
							if (val2 != null)
							{
								customMetadataWriter.WriteForwardIterator(val2);
							}
						}
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			}
			if (((DebugInformation)info).HasCustomDebugInformations)
			{
				CustomDebugInformation? obj = ((IEnumerable<CustomDebugInformation>)((DebugInformation)info).CustomDebugInformations).FirstOrDefault((Func<CustomDebugInformation, bool>)((CustomDebugInformation cdi) => (int)cdi.Kind == 1));
				StateMachineScopeDebugInformation val3 = (StateMachineScopeDebugInformation)(object)((obj is StateMachineScopeDebugInformation) ? obj : null);
				if (val3 != null)
				{
					customMetadataWriter.WriteIteratorScopes(val3, info);
				}
			}
			customMetadataWriter.WriteCustomMetadata();
			DefineAsyncCustomMetadata(info);
		}

		private void DefineAsyncCustomMetadata(MethodDebugInformation info)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: 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)
			//IL_003a: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			if (!((DebugInformation)info).HasCustomDebugInformations)
			{
				return;
			}
			Enumerator<CustomDebugInformation> enumerator = ((DebugInformation)info).CustomDebugInformations.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomDebugInformation current = enumerator.Current;
					AsyncMethodBodyDebugInformation val = (AsyncMethodBodyDebugInformation)(object)((current is AsyncMethodBodyDebugInformation) ? current : null);
					if (val == null)
					{
						continue;
					}
					using MemoryStream memoryStream = new MemoryStream();
					BinaryStreamWriter val2 = new BinaryStreamWriter((Stream)memoryStream);
					int num;
					MetadataToken metadataToken;
					if (info.StateMachineKickOffMethod == null)
					{
						num = 0;
					}
					else
					{
						metadataToken = ((MemberReference)info.StateMachineKickOffMethod).MetadataToken;
						num = (int)((MetadataToken)(ref metadataToken)).ToUInt32();
					}
					val2.WriteUInt32((uint)num);
					InstructionOffset val3 = val.CatchHandler;
					val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset);
					val2.WriteUInt32((uint)val.Resumes.Count);
					for (int i = 0; i < val.Resumes.Count; i++)
					{
						val3 = val.Yields[i];
						val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset);
						metadataToken = ((MemberReference)val.resume_methods[i]).MetadataToken;
						val2.WriteUInt32(((MetadataToken)(ref metadataToken)).ToUInt32());
						val3 = val.Resumes[i];
						val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset);
					}
					writer.DefineCustomMetadata("asyncMethodInfo", memoryStream.ToArray());
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		private void DefineScope(ScopeDebugInformation scope, MethodDebugInformation info, out MetadataToken import_parent)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: 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)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Invalid comparison between Unknown and I4
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Invalid comparison between Unknown and I4
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Invalid comparison between Unknown and I4
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Invalid comparison between Unknown and I4
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Invalid comparison between Unknown and I4
			InstructionOffset val = scope.Start;
			int offset = ((InstructionOffset)(ref val)).Offset;
			val = scope.End;
			int num;
			if (!((InstructionOffset)(ref val)).IsEndOfMethod)
			{
				val = scope.End;
				num = ((InstructionOffset)(ref val)).Offset;
			}
			else
			{
				num = info.code_size;
			}
			int num2 = num;
			import_parent = new MetadataToken(0u);
			writer.OpenScope(offset);
			if (scope.Import != null && scope.Import.HasTargets && !import_info_to_parent.TryGetValue(info.scope.Import, out import_parent))
			{
				Enumerator<ImportTarget> enumerator = scope.Import.Targets.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						ImportTarget current = enumerator.Current;
						ImportTargetKind kind = current.Kind;
						if ((int)kind <= 3)
						{
							if ((int)kind != 1)
							{
								if ((int)kind == 3)
								{
									writer.UsingNamespace("T" + TypeParser.ToParseable(current.type, true));
								}
							}
							else
							{
								writer.UsingNamespace("U" + current.@namespace);
							}
						}
						else if ((int)kind != 7)
						{
							if ((int)kind == 9)
							{
								writer.UsingNamespace("A" + current.Alias + " T" + TypeParser.ToParseable(current.type, true));
							}
						}
						else
						{
							writer.UsingNamespace("A" + current.Alias + " U" + current.@namespace);
						}
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				import_info_to_parent.Add(info.scope.Import, ((MemberReference)info.method).MetadataToken);
			}
			int local_var_token = ((MetadataToken)(ref info.local_var_token)).ToInt32();
			if (!Mixin.IsNullOrEmpty<VariableDebugInformation>(scope.variables))
			{
				for (int i = 0; i < scope.variables.Count; i++)
				{
					VariableDebugInformation variable = scope.variables[i];
					DefineLocalVariable(variable, local_var_token, offset, num2);
				}
			}
			if (!Mixin.IsNullOrEmpty<ConstantDebugInformation>(scope.constants))
			{
				for (int j = 0; j < scope.constants.Count; j++)
				{
					ConstantDebugInformation constant = scope.constants[j];
					DefineConstant(constant);
				}
			}
			if (!Mixin.IsNullOrEmpty<ScopeDebugInformation>(scope.scopes))
			{
				for (int k = 0; k < scope.scopes.Count; k++)
				{
					DefineScope(scope.scopes[k], info, out var _);
				}
			}
			writer.CloseScope(num2);
		}

		private void DefineSequencePoints(Collection<SequencePoint> sequence_points)
		{
			for (int i = 0; i < sequence_points.Count; i++)
			{
				SequencePoint val = sequence_points[i];
				writer.DefineSequencePoints(GetDocument(val.Document), new int[1] { val.Offset }, new int[1] { val.StartLine }, new int[1] { val.StartColumn }, new int[1] { val.EndLine }, new int[1] { val.EndColumn });
			}
		}

		private void DefineLocalVariable(VariableDebugInformation variable, int local_var_token, int start_offset, int end_offset)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			writer.DefineLocalVariable2(variable.Name, variable.Attributes, local_var_token, variable.Index, 0, 0, start_offset, end_offset);
		}

		private void DefineConstant(ConstantDebugInformation constant)
		{
			uint num = metadata.AddStandAloneSignature(metadata.GetConstantTypeBlobIndex(constant.ConstantType));
			MetadataToken val = default(MetadataToken);
			((MetadataToken)(ref val))..ctor((TokenType)285212672, num);
			writer.DefineConstant2(constant.Name, constant.Value, ((MetadataToken)(ref val)).ToInt32());
		}

		private SymDocumentWriter GetDocument(Document document)
		{
			if (document == null)
			{
				return null;
			}
			if (documents.TryGetValue(document.Url, out var value))
			{
				return value;
			}
			value = writer.DefineDocument(document.Url, document.LanguageGuid, document.LanguageVendorGuid, document.TypeGuid);
			documents[document.Url] = value;
			return value;
		}

		public void Dispose()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			MethodDefinition entryPoint = module.EntryPoint;
			if (entryPoint != null)
			{
				SymWriter symWriter = writer;
				MetadataToken metadataToken = ((MemberReference)entryPoint).MetadataToken;
				symWriter.SetUserEntryPoint(((MetadataToken)(ref metadataToken)).ToInt32());
			}
			writer.Close();
		}
	}
	internal enum CustomMetadataType : byte
	{
		UsingInfo = 0,
		ForwardInfo = 1,
		IteratorScopes = 3,
		ForwardIterator = 4
	}
	internal class CustomMetadataWriter : IDisposable
	{
		private readonly SymWriter sym_writer;

		private readonly MemoryStream stream;

		private readonly BinaryStreamWriter writer;

		private int count;

		private const byte version = 4;

		public CustomMetadataWriter(SymWriter sym_writer)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			this.sym_writer = sym_writer;
			stream = new MemoryStream();
			writer = new BinaryStreamWriter((Stream)stream);
			writer.WriteByte((byte)4);
			writer.WriteByte((byte)0);
			writer.Align(4);
		}

		public void WriteUsingInfo(ImportDebugInformation import_info)
		{
			Write(CustomMetadataType.UsingInfo, delegate
			{
				writer.WriteUInt16((ushort)1);
				writer.WriteUInt16((ushort)import_info.Targets.Count);
			});
		}

		public void WriteForwardInfo(MetadataToken import_parent)
		{
			//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)
			Write(CustomMetadataType.ForwardInfo, delegate
			{
				writer.WriteUInt32(((MetadataToken)(ref import_parent)).ToUInt32());
			});
		}

		public void WriteIteratorScopes(StateMachineScopeDebugInformation state_machine, MethodDebugInformation debug_info)
		{
			Write(CustomMetadataType.IteratorScopes, delegate
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: 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)
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0044: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				Collection<StateMachineScope> scopes = state_machine.Scopes;
				writer.WriteInt32(scopes.Count);
				Enumerator<StateMachineScope> enumerator = scopes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						StateMachineScope current = enumerator.Current;
						InstructionOffset val = current.Start;
						int offset = ((InstructionOffset)(ref val)).Offset;
						val = current.End;
						int num;
						if (!((InstructionOffset)(ref val)).IsEndOfMethod)
						{
							val = current.End;
							num = ((InstructionOffset)(ref val)).Offset;
						}
						else
						{
							num = debug_info.code_size;
						}
						int num2 = num;
						writer.WriteInt32(offset);
						writer.WriteInt32(num2 - 1);
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			});
		}

		public void WriteForwardIterator(TypeReference type)
		{
			Write(CustomMetadataType.ForwardIterator, delegate
			{
				writer.WriteBytes(Encoding.Unicode.GetBytes(((MemberReference)type).Name));
			});
		}

		private void Write(CustomMetadataType type, Action write)
		{
			count++;
			writer.WriteByte((byte)4);
			writer.WriteByte((byte)type);
			writer.Align(4);
			int position = writer.Position;
			writer.WriteUInt32(0u);
			write();
			writer.Align(4);
			int position2 = writer.Position;
			int num = position2 - position + 4;
			writer.Position = position;
			writer.WriteInt32(num);
			writer.Position = position2;
		}

		public void WriteCustomMetadata()
		{
			if (count != 0)
			{
				((BinaryWriter)(object)writer).BaseStream.Position = 1L;
				writer.WriteByte((byte)count);
				((BinaryWriter)(object)writer).Flush();
				sym_writer.DefineCustomMetadata("MD2", stream.ToArray());
			}
		}

		public void Dispose()
		{
			stream.Dispose();
		}
	}
	public sealed class NativePdbReaderProvider : ISymbolReaderProvider
	{
		public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolReader)(object)new NativePdbReader(Disposable.Owned<Stream>((Stream)File.OpenRead(Mixin.GetPdbFileName(fileName))));
		}

		public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			return (ISymbolReader)(object)new NativePdbReader(Disposable.NotOwned<Stream>(symbolStream));
		}
	}
	public sealed class PdbReaderProvider : ISymbolReaderProvider
	{
		public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			if (module.HasDebugHeader && Mixin.GetEmbeddedPortablePdbEntry(module.GetDebugHeader()) != null)
			{
				return new EmbeddedPortablePdbReaderProvider().GetSymbolReader(module, fileName);
			}
			if (!Mixin.IsPortablePdb(Mixin.GetPdbFileName(fileName)))
			{
				return new NativePdbReaderProvider().GetSymbolReader(module, fileName);
			}
			return new PortablePdbReaderProvider().GetSymbolReader(module, fileName);
		}

		public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			Mixin.CheckReadSeek(symbolStream);
			if (!Mixin.IsPortablePdb(symbolStream))
			{
				return new NativePdbReaderProvider().GetSymbolReader(module, symbolStream);
			}
			return new PortablePdbReaderProvider().GetSymbolReader(module, symbolStream);
		}
	}
	public sealed class NativePdbWriterProvider : ISymbolWriterProvider
	{
		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName)
		{
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			return (ISymbolWriter)(object)new NativePdbWriter(module, CreateWriter(module, Mixin.GetPdbFileName(fileName)));
		}

		private static SymWriter CreateWriter(ModuleDefinition module, string pdb)
		{
			SymWriter symWriter = new SymWriter();
			if (File.Exists(pdb))
			{
				File.Delete(pdb);
			}
			symWriter.Initialize(new ModuleMetadata(module), pdb, fFullBuild: true);
			return symWriter;
		}

		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream)
		{
			throw new NotImplementedException();
		}
	}
	public sealed class PdbWriterProvider : ISymbolWriterProvider
	{
		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckFileName(fileName);
			if (HasPortablePdbSymbols(module))
			{
				return new PortablePdbWriterProvider().GetSymbolWriter(module, fileName);
			}
			return new NativePdbWriterProvider().GetSymbolWriter(module, fileName);
		}

		private static bool HasPortablePdbSymbols(ModuleDefinition module)
		{
			if (module.symbol_reader != null)
			{
				return module.symbol_reader is PortablePdbReader;
			}
			return false;
		}

		public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			Mixin.CheckModule(module);
			Mixin.CheckStream((object)symbolStream);
			Mixin.CheckReadSeek(symbolStream);
			if (HasPortablePdbSymbols(module))
			{
				return new PortablePdbWriterProvider().GetSymbolWriter(module, symbolStream);
			}
			return new NativePdbWriterProvider().GetSymbolWriter(module, symbolStream);
		}
	}
	internal class SymDocumentWriter
	{
		private readonly ISymUnmanagedDocumentWriter m_unmanagedDocumentWriter;

		public SymDocumentWriter(ISymUnmanagedDocumentWriter unmanagedDocumentWriter)
		{
			m_unmanagedDocumentWriter = unmanagedDocumentWriter;
		}

		public ISymUnmanagedDocumentWriter GetUnmanaged()
		{
			return m_unmanagedDocumentWriter;
		}
	}
	internal class SymWriter
	{
		private static Guid s_symUnmangedWriterIID = new Guid("0b97726e-9e6d-4f05-9a26-424022093caa");

		private static Guid s_CorSymWriter_SxS_ClassID = new Guid("108296c1-281e-11d3-bd22-0000f80849bd");

		private readonly ISymUnmanagedWriter2 m_writer;

		private readonly Collection<ISymUnmanagedDocumentWriter> documents;

		[DllImport("ole32.dll")]
		private static extern int CoCreateInstance([In] ref Guid rclsid, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, [In] uint dwClsContext, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppv);

		public SymWriter()
		{
			CoCreateInstance(ref s_CorSymWriter_SxS_ClassID, null, 1u, ref s_symUnmangedWriterIID, out var ppv);
			m_writer = (ISymUnmanagedWriter2)ppv;
			documents = new Collection<ISymUnmanagedDocumentWriter>();
		}

		public byte[] GetDebugInfo(out ImageDebugDirectory idd)
		{
			m_writer.GetDebugInfo(out idd, 0, out var pcData, null);
			byte[] array = new byte[pcData];
			m_writer.GetDebugInfo(out idd, pcData, out pcData, array);
			return array;
		}

		public void DefineLocalVariable2(string name, VariableAttributes attributes, int sigToken, int addr1, int addr2, int addr3, int startOffset, int endOffset)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected I4, but got Unknown
			m_writer.DefineLocalVariable2(name, (int)attributes, sigToken, 1, addr1, addr2, addr3, startOffset, endOffset);
		}

		public void DefineConstant2(string name, object value, int sigToken)
		{
			if (value == null)
			{
				m_writer.DefineConstant2(name, 0, sigToken);
			}
			else
			{
				m_writer.DefineConstant2(name, value, sigToken);
			}
		}

		public void Close()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			m_writer.Close();
			Marshal.ReleaseComObject(m_writer);
			Enumerator<ISymUnmanagedDocumentWriter> enumerator = documents.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					Marshal.ReleaseComObject(enumerator.Current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void CloseMethod()
		{
			m_writer.CloseMethod();
		}

		public void CloseNamespace()
		{
			m_writer.CloseNamespace();
		}

		public void CloseScope(int endOffset)
		{
			m_writer.CloseScope(endOffset);
		}

		public SymDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType)
		{
			m_writer.DefineDocument(url, ref language, ref languageVendor, ref documentType, out var pRetVal);
			documents.Add(pRetVal);
			return new SymDocumentWriter(pRetVal);
		}

		public void DefineSequencePoints(SymDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns)
		{
			m_writer.DefineSequencePoints(document.GetUnmanaged(), offsets.Length, offsets, lines, columns, endLines, endColumns);
		}

		public void Initialize(object emitter, string filename, bool fFullBuild)
		{
			m_writer.Initialize(emitter, filename, null, fFullBuild);
		}

		public void SetUserEntryPoint(int methodToken)
		{
			m_writer.SetUserEntryPoint(methodToken);
		}

		public void OpenMethod(int methodToken)
		{
			m_writer.OpenMethod(methodToken);
		}

		public void OpenNamespace(string name)
		{
			m_writer.OpenNamespace(name);
		}

		public int OpenScope(int startOffset)
		{
			m_writer.OpenScope(startOffset, out var pRetVal);
			return pRetVal;
		}

		public void UsingNamespace(string fullName)
		{
			m_writer.UsingNamespace(fullName);
		}

		public void DefineCustomMetadata(string name, byte[] metadata)
		{
			GCHandle gCHandle = GCHandle.Alloc(metadata, GCHandleType.Pinned);
			m_writer.SetSymAttribute(0u, name, (uint)metadata.Length, gCHandle.AddrOfPinnedObject());
			gCHandle.Free();
		}
	}
}
namespace Microsoft.Cci
{
	public interface ILocalScope
	{
		uint Offset { get; }

		uint Length { get; }
	}
	public interface INamespaceScope
	{
		IEnumerable<IUsedNamespace> UsedNamespaces { get; }
	}
	public interface IUsedNamespace
	{
		IName Alias { get; }

		IName NamespaceName { get; }
	}
	public interface IName
	{
		int UniqueKey { get; }

		int UniqueKeyIgnoringCase { get; }

		string Value { get; }
	}
	internal sealed class PdbIteratorScope : ILocalScope
	{
		private uint offset;

		private uint length;

		public uint Offset => offset;

		public uint Length => length;

		internal PdbIteratorScope(uint offset, uint length)
		{
			this.offset = offset;
			this.length = length;
		}
	}
}
namespace Microsoft.Cci.Pdb
{
	internal class BitAccess
	{
		private byte[] buffer;

		private int offset;

		internal byte[] Buffer => buffer;

		internal int Position
		{
			get
			{
				return offset;
			}
			set
			{
				offset = value;
			}
		}

		internal BitAccess(int capacity)
		{
			buffer = new byte[capacity];
		}

		internal void FillBuffer(Stream stream, int capacity)
		{
			MinCapacity(capacity);
			stream.Read(buffer, 0, capacity);
			offset = 0;
		}

		internal void Append(Stream stream, int count)
		{
			int num = offset + count;
			if (buffer.Length < num)
			{
				byte[] destinationArray = new byte[num];
				Array.Copy(buffer, destinationArray, buffer.Length);
				buffer = destinationArray;
			}
			stream.Read(buffer, offset, count);
			offset += count;
		}

		internal void MinCapacity(int capacity)
		{
			if (buffer.Length < capacity)
			{
				buffer = new byte[capacity];
			}
			offset = 0;
		}

		internal void Align(int alignment)
		{
			while (offset % alignment != 0)
			{
				offset++;
			}
		}

		internal void ReadInt16(out short value)
		{
			value = (short)((buffer[offset] & 0xFF) | (buffer[offset + 1] << 8));
			offset += 2;
		}

		internal void ReadInt8(out sbyte value)
		{
			value = (sbyte)buffer[offset];
			offset++;
		}

		internal void ReadInt32(out int value)
		{
			value = (buffer[offset] & 0xFF) | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24);
			offset += 4;
		}

		internal void ReadInt64(out long value)
		{
			value = ((long)buffer[offset] & 0xFFL) | (long)((ulong)buffer[offset + 1] << 8) | (long)((ulong)buffer[offset + 2] << 16) | (long)((ulong)buffer[offset + 3] << 24) | (long)((ulong)buffer[offset + 4] << 32) | (long)((ulong)buffer[offset + 5] << 40) | (long)((ulong)buffer[offset + 6] << 48) | (long)((ulong)buffer[offset + 7] << 56);
			offset += 8;
		}

		internal void ReadUInt16(out ushort value)
		{
			value = (ushort)((buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8));
			offset += 2;
		}

		internal void ReadUInt8(out byte value)
		{
			value = (byte)(buffer[offset] & 0xFFu);
			offset++;
		}

		internal void ReadUInt32(out uint value)
		{
			value = (buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8) | (uint)(buffer[offset + 2] << 16) | (uint)(buffer[offset + 3] << 24);
			offset += 4;
		}

		internal void ReadUInt64(out ulong value)
		{
			value = ((ulong)buffer[offset] & 0xFFuL) | ((ulong)buffer[offset + 1] << 8) | ((ulong)buffer[offset + 2] << 16) | ((ulong)buffer[offset + 3] << 24) | ((ulong)buffer[offset + 4] << 32) | ((ulong)buffer[offset + 5] << 40) | ((ulong)buffer[offset + 6] << 48) | ((ulong)buffer[offset + 7] << 56);
			offset += 8;
		}

		internal void ReadInt32(int[] values)
		{
			for (int i = 0; i < values.Length; i++)
			{
				ReadInt32(out values[i]);
			}
		}

		internal void ReadUInt32(uint[] values)
		{
			for (int i = 0; i < values.Length; i++)
			{
				ReadUInt32(out values[i]);
			}
		}

		internal void ReadBytes(byte[] bytes)
		{
			for (int i = 0; i < bytes.Length; i++)
			{
				bytes[i] = buffer[offset++];
			}
		}

		internal float ReadFloat()
		{
			float result = BitConverter.ToSingle(buffer, offset);
			offset += 4;
			return result;
		}

		internal double ReadDouble()
		{
			double result = BitConverter.ToDouble(buffer, offset);
			offset += 8;
			return result;
		}

		internal decimal ReadDecimal()
		{
			int[] array = new int[4];
			ReadInt32(array);
			return new decimal(array[2], array[3], array[1], array[0] < 0, (byte)((array[0] & 0xFF0000) >> 16));
		}

		internal void ReadBString(out string value)
		{
			ReadUInt16(out var value2);
			value = Encoding.UTF8.GetString(buffer, offset, value2);
			offset += value2;
		}

		internal string ReadBString(int len)
		{
			string @string = Encoding.UTF8.GetString(buffer, offset, len);
			offset += len;
			return @string;
		}

		internal void ReadCString(out string value)
		{
			int i;
			for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++)
			{
			}
			value = Encoding.UTF8.GetString(buffer, offset, i);
			offset += i + 1;
		}

		internal void SkipCString(out string value)
		{
			int i;
			for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++)
			{
			}
			offset += i + 1;
			value = null;
		}

		internal void ReadGuid(out Guid guid)
		{
			ReadUInt32(out var value);
			ReadUInt16(out var value2);
			ReadUInt16(out var value3);
			ReadUInt8(out var value4);
			ReadUInt8(out var value5);
			ReadUInt8(out var value6);
			ReadUInt8(out var value7);
			ReadUInt8(out var value8);
			ReadUInt8(out var value9);
			ReadUInt8(out var value10);
			ReadUInt8(out var value11);
			guid = new Guid(value, value2, value3, value4, value5, value6, value7, value8, value9, value10, value11);
		}

		internal string ReadString()
		{
			int i;
			for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i += 2)
			{
			}
			string @string = Encoding.Unicode.GetString(buffer, offset, i);
			offset += i + 2;
			return @string;
		}
	}
	internal struct BitSet
	{
		private int size;

		private uint[] words;

		internal bool IsEmpty => size == 0;

		internal BitSet(BitAccess bits)
		{
			bits.ReadInt32(out size);
			words = new uint[size];
			bits.ReadUInt32(words);
		}

		internal bool IsSet(int index)
		{
			int num = index / 32;
			if (num >= size)
			{
				return false;
			}
			return (words[num] & GetBit(index)) != 0;
		}

		private static uint GetBit(int index)
		{
			return (uint)(1 << index % 32);
		}
	}
	internal struct FLOAT10
	{
		internal byte Data_0;

		internal byte Data_1;

		internal byte Data_2;

		internal byte Data_3;

		internal byte Data_4;

		internal byte Data_5;

		internal byte Data_6;

		internal byte Data_7;

		internal byte Data_8;

		internal byte Data_9;
	}
	internal enum CV_SIGNATURE
	{
		C6 = 0,
		C7 = 1,
		C11 = 2,
		C13 = 4,
		RESERVERD = 5
	}
	internal enum CV_prmode
	{
		CV_TM_DIRECT = 0,
		CV_TM_NPTR32 = 4,
		CV_TM_NPTR64 = 6,
		CV_TM_NPTR128 = 7
	}
	internal enum CV_type
	{
		CV_SPECIAL = 0,
		CV_SIGNED = 1,
		CV_UNSIGNED = 2,
		CV_BOOLEAN = 3,
		CV_REAL = 4,
		CV_COMPLEX = 5,
		CV_SPECIAL2 = 6,
		CV_INT = 7,
		CV_CVRESERVED = 15
	}
	internal enum CV_special
	{
		CV_SP_NOTYPE,
		CV_SP_ABS,
		CV_SP_SEGMENT,
		CV_SP_VOID,
		CV_SP_CURRENCY,
		CV_SP_NBASICSTR,
		CV_SP_FBASICSTR,
		CV_SP_NOTTRANS,
		CV_SP_HRESULT
	}
	internal enum CV_special2
	{
		CV_S2_BIT,
		CV_S2_PASCHAR
	}
	internal enum CV_integral
	{
		CV_IN_1BYTE,
		CV_IN_2BYTE,
		CV_IN_4BYTE,
		CV_IN_8BYTE,
		CV_IN_16BYTE
	}
	internal enum CV_real
	{
		CV_RC_REAL32,
		CV_RC_REAL64,
		CV_RC_REAL80,
		CV_RC_REAL128
	}
	internal enum CV_int
	{
		CV_RI_CHAR = 0,
		CV_RI_INT1 = 0,
		CV_RI_WCHAR = 1,
		CV_RI_UINT1 = 1,
		CV_RI_INT2 = 2,
		CV_RI_UINT2 = 3,
		CV_RI_INT4 = 4,
		CV_RI_UINT4 = 5,
		CV_RI_INT8 = 6,
		CV_RI_UINT8 = 7,
		CV_RI_INT16 = 8,
		CV_RI_UINT16 = 9
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	internal struct CV_PRIMITIVE_TYPE
	{
		private const uint CV_MMASK = 1792u;

		private const uint CV_TMASK = 240u;

		private const uint CV_SMASK = 15u;

		private const int CV_MSHIFT = 8;

		private const int CV_TSHIFT = 4;

		private const int CV_SSHIFT = 0;

		private const uint CV_FIRST_NONPRIM = 4096u;
	}
	internal enum TYPE_ENUM
	{
		T_NOTYPE = 0,
		T_ABS = 1,
		T_SEGMENT = 2,
		T_VOID = 3,
		T_HRESULT = 8,
		T_32PHRESULT = 1032,
		T_64PHRESULT = 1544,
		T_PVOID = 259,
		T_PFVOID = 515,
		T_PHVOID = 771,
		T_32PVOID = 1027,
		T_64PVOID = 1539,
		T_CURRENCY = 4,
		T_NOTTRANS = 7,
		T_BIT = 96,
		T_PASCHAR = 97,
		T_CHAR = 16,
		T_32PCHAR = 1040,
		T_64PCHAR = 1552,
		T_UCHAR = 32,
		T_32PUCHAR = 1056,
		T_64PUCHAR = 1568,
		T_RCHAR = 112,
		T_32PRCHAR = 1136,
		T_64PRCHAR = 1648,
		T_WCHAR = 113,
		T_32PWCHAR = 1137,
		T_64PWCHAR = 1649,
		T_INT1 = 104,
		T_32PINT1 = 1128,
		T_64PINT1 = 1640,
		T_UINT1 = 105,
		T_32PUINT1 = 1129,
		T_64PUINT1 = 1641,
		T_SHORT = 17,
		T_32PSHORT = 1041,
		T_64PSHORT = 1553,
		T_USHORT = 33,
		T_32PUSHORT = 1057,
		T_64PUSHORT = 1569,
		T_INT2 = 114,
		T_32PINT2 = 1138,
		T_64PINT2 = 1650,
		T_UINT2 = 115,
		T_32PUINT2 = 1139,
		T_64PUINT2 = 1651,
		T_LONG = 18,
		T_ULONG = 34,
		T_32PLONG = 1042,
		T_32PULONG = 1058,
		T_64PLONG = 1554,
		T_64PULONG = 1570,
		T_INT4 = 116,
		T_32PINT4 = 1140,
		T_64PINT4 = 1652,
		T_UINT4 = 117,
		T_32PUINT4 = 1141,
		T_64PUINT4 = 1653,
		T_QUAD = 19,
		T_32PQUAD = 1043,
		T_64PQUAD = 1555,
		T_UQUAD = 35,
		T_32PUQUAD = 1059,
		T_64PUQUAD = 1571,
		T_INT8 = 118,
		T_32PINT8 = 1142,
		T_64PINT8 = 1654,
		T_UINT8 = 119,
		T_32PUINT8 = 1143,
		T_64PUINT8 = 1655,
		T_OCT = 20,
		T_32POCT = 1044,
		T_64POCT = 1556,
		T_UOCT = 36,
		T_32PUOCT = 1060,
		T_64PUOCT = 1572,
		T_INT16 = 120,
		T_32PINT16 = 1144,
		T_64PINT16 = 1656,
		T_UINT16 = 121,
		T_32PUINT16 = 1145,
		T_64PUINT16 = 1657,
		T_REAL32 = 64,
		T_32PREAL32 = 1088,
		T_64PREAL32 = 1600,
		T_REAL64 = 65,
		T_32PREAL64 = 1089,
		T_64PREAL64 = 1601,
		T_REAL80 = 66,
		T_32PREAL80 = 1090,
		T_64PREAL80 = 1602,
		T_REAL128 = 67,
		T_32PREAL128 = 1091,
		T_64PREAL128 = 1603,
		T_CPLX32 = 80,
		T_32PCPLX32 = 1104,
		T_64PCPLX32 = 1616,
		T_CPLX64 = 81,
		T_32PCPLX64 = 1105,
		T_64PCPLX64 = 1617,
		T_CPLX80 = 82,
		T_32PCPLX80 = 1106,
		T_64PCPLX80 = 1618,
		T_CPLX128 = 83,
		T_32PCPLX128 = 1107,
		T_64PCPLX128 = 1619,
		T_BOOL08 = 48,
		T_32PBOOL08 = 1072,
		T_64PBOOL08 = 1584,
		T_BOOL16 = 49,
		T_32PBOOL16 = 1073,
		T_64PBOOL16 = 1585,
		T_BOOL32 = 50,
		T_32PBOOL32 = 1074,
		T_64PBOOL32 = 1586,
		T_BOOL64 = 51,
		T_32PBOOL64 = 1075,
		T_64PBOOL64 = 1587
	}
	internal enum LEAF
	{
		LF_VTSHAPE = 10,
		LF_COBOL1 = 12,
		LF_LABEL = 14,
		LF_NULL = 15,
		LF_NOTTRAN = 16,
		LF_ENDPRECOMP = 20,
		LF_TYPESERVER_ST = 22,
		LF_LIST = 515,
		LF_REFSYM = 524,
		LF_ENUMERATE_ST = 1027,
		LF_TI16_MAX = 4096,
		LF_MODIFIER = 4097,
		LF_POINTER = 4098,
		LF_ARRAY_ST = 4099,
		LF_CLASS_ST = 4100,
		LF_STRUCTURE_ST = 4101,
		LF_UNION_ST = 4102,
		LF_ENUM_ST = 4103,
		LF_PROCEDURE = 4104,
		LF_MFUNCTION = 4105,
		LF_COBOL0 = 4106,
		LF_BARRAY = 4107,
		LF_DIMARRAY_ST = 4108,
		LF_VFTPATH = 4109,
		LF_PRECOMP_ST = 4110,
		LF_OEM = 4111,
		LF_ALIAS_ST = 4112,
		LF_OEM2 = 4113,
		LF_SKIP = 4608,
		LF_ARGLIST = 4609,
		LF_DEFARG_ST = 4610,
		LF_FIELDLIST = 4611,
		LF_DERIVED = 4612,
		LF_BITFIELD = 4613,
		LF_METHODLIST = 4614,
		LF_DIMCONU = 4615,
		LF_DIMCONLU = 4616,
		LF_DIMVARU = 4617,
		LF_DIMVARLU = 4618,
		LF_BCLASS = 5120,
		LF_VBCLASS = 5121,
		LF_IVBCLASS = 5122,
		LF_FRIENDFCN_ST = 5123,
		LF_INDEX = 5124,
		LF_MEMBER_ST = 5125,
		LF_STMEMBER_ST = 5126,
		LF_METHOD_ST = 5127,
		LF_NESTTYPE_ST = 5128,
		LF_VFUNCTAB = 5129,
		LF_FRIENDCLS = 5130,
		LF_ONEMETHOD_ST = 5131,
		LF_VFUNCOFF = 5132,
		LF_NESTTYPEEX_ST = 5133,
		LF_MEMBERMODIFY_ST = 5134,
		LF_MANAGED_ST = 5135,
		LF_ST_MAX = 5376,
		LF_TYPESERVER = 5377,
		LF_ENUMERATE = 5378,
		LF_ARRAY = 5379,
		LF_CLASS = 5380,
		LF_STRUCTURE = 5381,
		LF_UNION = 5382,
		LF_ENUM = 5383,
		LF_DIMARRAY = 5384,
		LF_PRECOMP = 5385,
		LF_ALIAS = 5386,
		LF_DEFARG = 5387,
		LF_FRIENDFCN = 5388,
		LF_MEMBER = 5389,
		LF_STMEMBER = 5390,
		LF_METHOD = 5391,
		LF_NESTTYPE = 5392,
		LF_ONEMETHOD = 5393,
		LF_NESTTYPEEX = 5394,
		LF_MEMBERMODIFY = 5395,
		LF_MANAGED = 5396,
		LF_TYPESERVER2 = 5397,
		LF_NUMERIC = 32768,
		LF_CHAR = 32768,
		LF_SHORT = 32769,
		LF_USHORT = 32770,
		LF_LONG = 32771,
		LF_ULONG = 32772,
		LF_REAL32 = 32773,
		LF_REAL64 = 32774,
		LF_REAL80 = 32775,
		LF_REAL128 = 32776,
		LF_QUADWORD = 32777,
		LF_UQUADWORD = 32778,
		LF_COMPLEX32 = 32780,
		LF_COMPLEX64 = 32781,
		LF_COMPLEX80 = 32782,
		LF_COMPLEX128 = 32783,
		LF_VARSTRING = 32784,
		LF_OCTWORD = 32791,
		LF_UOCTWORD = 32792,
		LF_DECIMAL = 32793,
		LF_DATE = 32794,
		LF_UTF8STRING = 32795,
		LF_PAD0 = 240,
		LF_PAD1 = 241,
		LF_PAD2 = 242,
		LF_PAD3 = 243,
		LF_PAD4 = 244,
		LF_PAD5 = 245,
		LF_PAD6 = 246,
		LF_PAD7 = 247,
		LF_PAD8 = 248,
		LF_PAD9 = 249,
		LF_PAD10 = 250,
		LF_PAD11 = 251,
		LF_PAD12 = 252,
		LF_PAD13 = 253,
		LF_PAD14 = 254,
		LF_PAD15 = 255
	}
	internal enum CV_ptrtype
	{
		CV_PTR_BASE_SEG = 3,
		CV_PTR_BASE_VAL = 4,
		CV_PTR_BASE_SEGVAL = 5,
		CV_PTR_BASE_ADDR = 6,
		CV_PTR_BASE_SEGADDR = 7,
		CV_PTR_BASE_TYPE = 8,
		CV_PTR_BASE_SELF = 9,
		CV_PTR_NEAR32 = 10,
		CV_PTR_64 = 12,
		CV_PTR_UNUSEDPTR = 13
	}
	internal enum CV_ptrmode
	{
		CV_PTR_MODE_PTR,
		CV_PTR_MODE_REF,
		CV_PTR_MODE_PMEM,
		CV_PTR_MODE_PMFUNC,
		CV_PTR_MODE_RESERVED
	}
	internal enum CV_pmtype
	{
		CV_PMTYPE_Undef,
		CV_PMTYPE_D_Single,
		CV_PMTYPE_D_Multiple,
		CV_PMTYPE_D_Virtual,
		CV_PMTYPE_D_General,
		CV_PMTYPE_F_Single,
		CV_PMTYPE_F_Multiple,
		CV_PMTYPE_F_Virtual,
		CV_PMTYPE_F_General
	}
	internal enum CV_methodprop
	{
		CV_MTvanilla,
		CV_MTvirtual,
		CV_MTstatic,
		CV_MTfriend,
		CV_MTintro,
		CV_MTpurevirt,
		CV_MTpureintro
	}
	internal enum CV_VTS_desc
	{
		CV_VTS_near,
		CV_VTS_far,
		CV_VTS_thin,
		CV_VTS_outer,
		CV_VTS_meta,
		CV_VTS_near32,
		CV_VTS_far32,
		CV_VTS_unused
	}
	internal enum CV_LABEL_TYPE
	{
		CV_LABEL_NEAR = 0,
		CV_LABEL_FAR = 4
	}
	[Flags]
	internal enum CV_modifier : ushort
	{
		MOD_const = 1,
		MOD_volatile = 2,
		MOD_unaligned = 4
	}
	[Flags]
	internal enum CV_prop : ushort
	{
		packed = 1,
		ctor = 2,
		ovlops = 4,
		isnested = 8,
		cnested = 0x10,
		opassign = 0x20,
		opcast = 0x40,
		fwdref = 0x80,
		scoped = 0x100
	}
	[Flags]
	internal enum CV_fldattr
	{
		access = 3,
		mprop = 0x1C,
		pseudo = 0x20,
		noinherit = 0x40,
		noconstruct = 0x80,
		compgenx = 0x100
	}
	internal struct TYPTYPE
	{
		internal ushort len;

		internal ushort leaf;
	}
	internal struct CV_PDMR32_NVVFCN
	{
		internal int mdisp;
	}
	internal struct CV_PDMR32_VBASE
	{
		internal int mdisp;

		internal int pdisp;

		internal int vdisp;
	}
	internal struct CV_PMFR32_NVSA
	{
		internal uint off;
	}
	internal struct CV_PMFR32_NVMA
	{
		internal uint off;

		internal int disp;
	}
	internal struct CV_PMFR32_VBASE
	{
		internal uint off;

		internal int mdisp;

		internal int pdisp;

		internal int vdisp;
	}
	internal struct LeafModifier
	{
		internal uint type;

		internal CV_modifier attr;
	}
	[Flags]
	internal enum LeafPointerAttr : uint
	{
		ptrtype = 0x1Fu,
		ptrmode = 0xE0u,
		isflat32 = 0x100u,
		isvolatile = 0x200u,
		isconst = 0x400u,
		isunaligned = 0x800u,
		isrestrict = 0x1000u
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	internal struct LeafPointer
	{
		internal struct LeafPointerBody
		{
			internal uint utype;

			internal LeafPointerAttr attr;
		}
	}
	internal struct LeafArray
	{
		internal uint elemtype;

		internal uint idxtype;

		internal byte[] data;

		internal string name;
	}
	internal struct LeafClass
	{
		internal ushort count;

		internal ushort property;

		internal uint field;

		internal uint derived;

		internal uint vshape;

		internal byte[] data;

		internal string name;
	}
	internal struct LeafUnion
	{
		internal ushort count;

		internal ushort property;

		internal uint field;

		internal byte[] data;

		internal string name;
	}
	internal struct LeafAlias
	{
		internal uint utype;

		internal string name;
	}
	internal struct LeafManaged
	{
		internal string name;
	}
	internal struct LeafEnum
	{
		internal ushort count;

		internal ushort property;

		internal uint utype;

		internal uint field;

		internal string name;
	}
	internal struct LeafProc
	{
		internal uint rvtype;

		internal byte calltype;

		internal byte reserved;

		internal ushort parmcount;

		internal uint arglist;
	}
	internal struct LeafMFunc
	{
		internal uint rvtype;

		internal uint classtype;

		internal uint thistype;

		internal byte calltype;

		internal byte reserved;

		internal ushort parmcount;

		internal uint arglist;

		internal int thisadjust;
	}
	internal struct LeafVTShape
	{
		internal ushort count;

		internal byte[] desc;
	}
	internal struct LeafCobol0
	{
		internal uint type;

		internal byte[] data;
	}
	internal struct LeafCobol1
	{
		internal byte[] data;
	}
	internal struct LeafBArray
	{
		internal uint utype;
	}
	internal struct LeafLabel
	{
		internal ushort mode;
	}
	internal struct LeafDimArray
	{
		internal uint utype;

		internal uint diminfo;

		internal string name;
	}
	internal struct LeafVFTPath
	{
		internal uint count;

		internal uint[] bases;
	}
	internal struct LeafPreComp
	{
		internal uint start;

		internal uint count;

		internal uint signature;

		internal string name;
	}
	internal struct LeafEndPreComp
	{
		internal uint signature;
	}
	internal struct LeafOEM
	{
		internal ushort cvOEM;

		internal ushort recOEM;

		internal uint count;

		internal uint[] index;
	}
	internal enum OEM_ID
	{
		OEM_MS_FORTRAN90 = 61584,
		OEM_ODI = 16,
		OEM_THOMSON_SOFTWARE = 21587,
		OEM_ODI_REC_BASELIST = 0
	}
	internal struct LeafOEM2
	{
		internal Guid idOem;

		internal uint count;

		internal uint[] index;
	}
	internal struct LeafTypeServer
	{
		internal uint signature;

		internal uint age;

		internal string name;
	}
	internal struct LeafTypeServer2
	{
		internal Guid sig70;

		internal uint age;

		internal string name;
	}
	internal struct LeafSkip
	{
		internal uint type;

		internal byte[] data;
	}
	internal struct LeafArgList
	{
		internal uint count;

		internal uint[] arg;
	}
	internal struct LeafDerived
	{
		internal uint count;

		internal uint[] drvdcls;
	}
	internal struct LeafDefArg
	{
		internal uint type;

		internal byte[] expr;
	}
	internal struct LeafList
	{
		internal byte[] data;
	}
	internal struct LeafFieldList
	{
		internal char[] data;
	}
	internal struct mlMethod
	{
		internal ushort attr;

		internal ushort pad0;

		internal uint index;

		internal uint[] vbaseoff;
	}
	internal struct LeafMethodList
	{
		internal byte[] mList;
	}
	internal struct LeafBitfield
	{
		internal uint type;

		internal byte length;

		internal byte position;
	}
	internal struct LeafDimCon
	{
		internal uint typ;

		internal ushort rank;

		internal byte[] dim;
	}
	internal struct LeafDimVar
	{
		internal uint rank;

		internal uint typ;

		internal uint[] dim;
	}
	internal struct LeafRefSym
	{
		internal byte[] Sym;
	}
	internal struct LeafChar
	{
		internal sbyte val;
	}
	internal struct LeafShort
	{
		internal short val;
	}
	internal struct LeafUShort
	{
		internal ushort val;
	}
	internal struct LeafLong
	{
		internal int val;
	}
	internal struct LeafULong
	{
		internal uint val;
	}
	internal struct LeafQuad
	{
		internal long val;
	}
	internal struct LeafUQuad
	{
		internal ulong val;
	}
	internal struct LeafOct
	{
		internal ulong val0;

		internal ulong val1;
	}
	internal struct LeafUOct
	{
		internal ulong val0;

		internal ulong val1;
	}
	internal struct LeafReal32
	{
		internal float val;
	}
	internal struct LeafReal64
	{
		internal double val;
	}
	internal struct LeafReal80
	{
		internal FLOAT10 val;
	}
	internal struct LeafReal128
	{
		internal ulong val0;

		internal ulong val1;
	}
	internal struct LeafCmplx32
	{
		internal float val_real;

		internal float val_imag;
	}
	internal struct LeafCmplx64
	{
		internal double val_real;

		internal double val_imag;
	}
	internal struct LeafCmplx80
	{
		internal FLOAT10 val_real;

		internal FLOAT10 val_imag;
	}
	internal struct LeafCmplx128
	{
		internal ulong val0_real;

		internal ulong val1_real;

		internal ulong val0_imag;

		internal ulong val1_imag;
	}
	internal struct LeafVarString
	{
		internal ushort len;

		internal byte[] value;
	}
	internal struct LeafIndex
	{
		internal ushort pad0;

		internal uint index;
	}
	internal struct LeafBClass
	{
		internal ushort attr;

		internal uint index;

		internal byte[] offset;
	}
	internal struct LeafVBClass
	{
		internal ushort attr;

		internal uint index;

		internal uint vbptr;

		internal byte[] vbpoff;
	}
	internal struct LeafFriendCls
	{
		internal ushort pad0;

		internal uint index;
	}
	internal struct LeafFriendFcn
	{
		internal ushort pad0;

		internal uint index;

		internal string name;
	}
	internal struct LeafMember
	{
		internal ushort attr;

		internal uint index;

		internal byte[] offset;

		internal string name;
	}
	internal struct LeafSTMember
	{
		internal ushort attr;

		internal uint index;

		internal string name;
	}
	internal struct LeafVFuncTab
	{
		internal ushort pad0;

		internal uint type;
	}
	internal struct LeafVFuncOff
	{
		internal ushort pad0;

		internal uint type;

		internal int offset;
	}
	internal struct LeafMethod
	{
		internal ushort count;

		internal uint mList;

		internal string name;
	}
	internal struct LeafOneMethod
	{
		internal ushort attr;

		internal uint index;

		internal uint[] vbaseoff;

		internal string name;
	}
	internal struct LeafEnumerate
	{
		internal ushort attr;

		internal byte[] value;

		internal string name;
	}
	internal struct LeafNestType
	{
		internal ushort pad0;

		internal uint index;

		internal string name;
	}
	internal struct LeafNestTypeEx
	{
		internal ushort attr;

		internal uint index;

		internal string name;
	}
	internal struct LeafMemberModify
	{
		internal ushort

FrozenDevv-ModPack-1.1.0/BepInEx/core/Mono.Cecil.Rocks.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using Mono.Cecil.Cil;
using Mono.Cecil.PE;
using Mono.Collections.Generic;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyProduct("Mono.Cecil")]
[assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")]
[assembly: ComVisible(false)]
[assembly: AssemblyFileVersion("0.10.4.0")]
[assembly: AssemblyInformationalVersion("0.10.4.0")]
[assembly: AssemblyTitle("Mono.Cecil.Rocks")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyVersion("0.10.4.0")]
namespace Mono.Cecil.Rocks;

public class DocCommentId
{
	private StringBuilder id;

	private DocCommentId()
	{
		id = new StringBuilder();
	}

	private void WriteField(FieldDefinition field)
	{
		WriteDefinition('F', (IMemberDefinition)(object)field);
	}

	private void WriteEvent(EventDefinition @event)
	{
		WriteDefinition('E', (IMemberDefinition)(object)@event);
	}

	private void WriteType(TypeDefinition type)
	{
		id.Append('T').Append(':');
		WriteTypeFullName((TypeReference)(object)type);
	}

	private void WriteMethod(MethodDefinition method)
	{
		WriteDefinition('M', (IMemberDefinition)(object)method);
		if (((MethodReference)method).HasGenericParameters)
		{
			id.Append('`').Append('`');
			id.Append(((MethodReference)method).GenericParameters.Count);
		}
		if (((MethodReference)method).HasParameters)
		{
			WriteParameters((IList<ParameterDefinition>)((MethodReference)method).Parameters);
		}
		if (IsConversionOperator(method))
		{
			WriteReturnType(method);
		}
	}

	private static bool IsConversionOperator(MethodDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (self.IsSpecialName)
		{
			if (!(((MemberReference)self).Name == "op_Explicit"))
			{
				return ((MemberReference)self).Name == "op_Implicit";
			}
			return true;
		}
		return false;
	}

	private void WriteReturnType(MethodDefinition method)
	{
		id.Append('~');
		WriteTypeSignature(((MethodReference)method).ReturnType);
	}

	private void WriteProperty(PropertyDefinition property)
	{
		WriteDefinition('P', (IMemberDefinition)(object)property);
		if (property.HasParameters)
		{
			WriteParameters((IList<ParameterDefinition>)((PropertyReference)property).Parameters);
		}
	}

	private void WriteParameters(IList<ParameterDefinition> parameters)
	{
		id.Append('(');
		WriteList(parameters, delegate(ParameterDefinition p)
		{
			WriteTypeSignature(((ParameterReference)p).ParameterType);
		});
		id.Append(')');
	}

	private void WriteTypeSignature(TypeReference type)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: 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_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Expected I4, but got Unknown
		//IL_010c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Expected O, but got Unknown
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Expected O, but got Unknown
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Expected I4, but got Unknown
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Expected O, but got Unknown
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Expected O, but got Unknown
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Expected O, but got Unknown
		MetadataType metadataType = type.MetadataType;
		switch (metadataType - 15)
		{
		default:
			switch (metadataType - 27)
			{
			case 0:
				WriteFunctionPointerTypeSignature((FunctionPointerType)type);
				return;
			case 3:
				id.Append('`').Append('`');
				id.Append(((GenericParameter)type).Position);
				return;
			case 5:
				WriteModiferTypeSignature((IModifierType)(OptionalModifierType)type, '!');
				return;
			case 4:
				WriteModiferTypeSignature((IModifierType)(RequiredModifierType)type, '|');
				return;
			}
			break;
		case 5:
			WriteArrayTypeSignature((ArrayType)type);
			return;
		case 1:
			WriteTypeSignature(((TypeSpecification)(ByReferenceType)type).ElementType);
			id.Append('@');
			return;
		case 6:
			WriteGenericInstanceTypeSignature((GenericInstanceType)type);
			return;
		case 4:
			id.Append('`');
			id.Append(((GenericParameter)type).Position);
			return;
		case 0:
			WriteTypeSignature(((TypeSpecification)(PointerType)type).ElementType);
			id.Append('*');
			return;
		case 2:
		case 3:
			break;
		}
		WriteTypeFullName(type);
	}

	private void WriteGenericInstanceTypeSignature(GenericInstanceType type)
	{
		if (Mixin.IsTypeSpecification(((TypeSpecification)type).ElementType))
		{
			throw new NotSupportedException();
		}
		WriteTypeFullName(((TypeSpecification)type).ElementType, stripGenericArity: true);
		id.Append('{');
		WriteList((IList<TypeReference>)type.GenericArguments, WriteTypeSignature);
		id.Append('}');
	}

	private void WriteList<T>(IList<T> list, Action<T> action)
	{
		for (int i = 0; i < list.Count; i++)
		{
			if (i > 0)
			{
				id.Append(',');
			}
			action(list[i]);
		}
	}

	private void WriteModiferTypeSignature(IModifierType type, char id)
	{
		WriteTypeSignature(type.ElementType);
		this.id.Append(id);
		WriteTypeSignature(type.ModifierType);
	}

	private void WriteFunctionPointerTypeSignature(FunctionPointerType type)
	{
		id.Append("=FUNC:");
		WriteTypeSignature(type.ReturnType);
		if (type.HasParameters)
		{
			WriteParameters((IList<ParameterDefinition>)type.Parameters);
		}
	}

	private void WriteArrayTypeSignature(ArrayType type)
	{
		WriteTypeSignature(((TypeSpecification)type).ElementType);
		if (type.IsVector)
		{
			id.Append("[]");
			return;
		}
		id.Append("[");
		WriteList((IList<ArrayDimension>)type.Dimensions, delegate(ArrayDimension dimension)
		{
			if (((ArrayDimension)(ref dimension)).LowerBound.HasValue)
			{
				id.Append(((ArrayDimension)(ref dimension)).LowerBound.Value);
			}
			id.Append(':');
			if (((ArrayDimension)(ref dimension)).UpperBound.HasValue)
			{
				id.Append(((ArrayDimension)(ref dimension)).UpperBound.Value - (((ArrayDimension)(ref dimension)).LowerBound.GetValueOrDefault() + 1));
			}
		});
		id.Append("]");
	}

	private void WriteDefinition(char id, IMemberDefinition member)
	{
		this.id.Append(id).Append(':');
		WriteTypeFullName((TypeReference)(object)member.DeclaringType);
		this.id.Append('.');
		WriteItemName(member.Name);
	}

	private void WriteTypeFullName(TypeReference type, bool stripGenericArity = false)
	{
		if (((MemberReference)type).DeclaringType != null)
		{
			WriteTypeFullName(((MemberReference)type).DeclaringType);
			id.Append('.');
		}
		if (!string.IsNullOrEmpty(type.Namespace))
		{
			id.Append(type.Namespace);
			id.Append('.');
		}
		string text = ((MemberReference)type).Name;
		if (stripGenericArity)
		{
			int num = text.LastIndexOf('`');
			if (num > 0)
			{
				text = text.Substring(0, num);
			}
		}
		id.Append(text);
	}

	private void WriteItemName(string name)
	{
		id.Append(name.Replace('.', '#').Replace('<', '{').Replace('>', '}'));
	}

	public override string ToString()
	{
		return id.ToString();
	}

	public static string GetDocCommentId(IMemberDefinition member)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: 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_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Invalid comparison between Unknown and I4
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Invalid comparison between Unknown and I4
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Invalid comparison between Unknown and I4
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0071: Expected O, but got Unknown
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Invalid comparison between Unknown and I4
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Expected O, but got Unknown
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Invalid comparison between Unknown and I4
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Expected O, but got Unknown
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Invalid comparison between Unknown and I4
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected O, but got Unknown
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Expected O, but got Unknown
		if (member == null)
		{
			throw new ArgumentNullException("member");
		}
		DocCommentId docCommentId = new DocCommentId();
		MetadataToken metadataToken = ((IMetadataTokenProvider)member).MetadataToken;
		TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType;
		if ((int)tokenType <= 67108864)
		{
			if ((int)tokenType != 33554432)
			{
				if ((int)tokenType != 67108864)
				{
					goto IL_009d;
				}
				docCommentId.WriteField((FieldDefinition)member);
			}
			else
			{
				docCommentId.WriteType((TypeDefinition)member);
			}
		}
		else if ((int)tokenType != 100663296)
		{
			if ((int)tokenType != 335544320)
			{
				if ((int)tokenType != 385875968)
				{
					goto IL_009d;
				}
				docCommentId.WriteProperty((PropertyDefinition)member);
			}
			else
			{
				docCommentId.WriteEvent((EventDefinition)member);
			}
		}
		else
		{
			docCommentId.WriteMethod((MethodDefinition)member);
		}
		return docCommentId.ToString();
		IL_009d:
		throw new NotSupportedException(member.FullName);
	}
}
internal static class Functional
{
	public static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)
	{
		Func<A, R> g = null;
		g = f((A a) => g(a));
		return g;
	}

	public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource element)
	{
		if (source == null)
		{
			throw new ArgumentNullException("source");
		}
		return PrependIterator(source, element);
	}

	private static IEnumerable<TSource> PrependIterator<TSource>(IEnumerable<TSource> source, TSource element)
	{
		yield return element;
		foreach (TSource item in source)
		{
			yield return item;
		}
	}
}
public interface IILVisitor
{
	void OnInlineNone(OpCode opcode);

	void OnInlineSByte(OpCode opcode, sbyte value);

	void OnInlineByte(OpCode opcode, byte value);

	void OnInlineInt32(OpCode opcode, int value);

	void OnInlineInt64(OpCode opcode, long value);

	void OnInlineSingle(OpCode opcode, float value);

	void OnInlineDouble(OpCode opcode, double value);

	void OnInlineString(OpCode opcode, string value);

	void OnInlineBranch(OpCode opcode, int offset);

	void OnInlineSwitch(OpCode opcode, int[] offsets);

	void OnInlineVariable(OpCode opcode, VariableDefinition variable);

	void OnInlineArgument(OpCode opcode, ParameterDefinition parameter);

	void OnInlineSignature(OpCode opcode, CallSite callSite);

	void OnInlineType(OpCode opcode, TypeReference type);

	void OnInlineField(OpCode opcode, FieldReference field);

	void OnInlineMethod(OpCode opcode, MethodReference method);
}
public static class ILParser
{
	private class ParseContext
	{
		public CodeReader Code { get; set; }

		public int Position { get; set; }

		public MetadataReader Metadata { get; set; }

		public Collection<VariableDefinition> Variables { get; set; }

		public IILVisitor Visitor { get; set; }
	}

	public static void Parse(MethodDefinition method, IILVisitor visitor)
	{
		if (method == null)
		{
			throw new ArgumentNullException("method");
		}
		if (visitor == null)
		{
			throw new ArgumentNullException("visitor");
		}
		if (!method.HasBody || !((MemberReference)method).HasImage)
		{
			throw new ArgumentException();
		}
		((MemberReference)method).Module.Read<MethodDefinition, bool>(method, (Func<MethodDefinition, MetadataReader, bool>)delegate(MethodDefinition m, MetadataReader _)
		{
			ParseMethod(m, visitor);
			return true;
		});
	}

	private static void ParseMethod(MethodDefinition method, IILVisitor visitor)
	{
		ParseContext parseContext = CreateContext(method, visitor);
		CodeReader code = parseContext.Code;
		byte b = ((BinaryReader)(object)code).ReadByte();
		switch (b & 3)
		{
		case 2:
			ParseCode(b >> 2, parseContext);
			break;
		case 3:
			((BinaryStreamReader)code).Advance(-1);
			ParseFatMethod(parseContext);
			break;
		default:
			throw new NotSupportedException();
		}
		code.MoveBackTo(parseContext.Position);
	}

	private static ParseContext CreateContext(MethodDefinition method, IILVisitor visitor)
	{
		CodeReader val = ((MemberReference)method).Module.Read<MethodDefinition, CodeReader>(method, (Func<MethodDefinition, MetadataReader, CodeReader>)((MethodDefinition _, MetadataReader reader) => reader.code));
		int position = val.MoveTo(method);
		return new ParseContext
		{
			Code = val,
			Position = position,
			Metadata = val.reader,
			Visitor = visitor
		};
	}

	private static void ParseFatMethod(ParseContext context)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		CodeReader code = context.Code;
		((BinaryStreamReader)code).Advance(4);
		int code_size = ((BinaryReader)(object)code).ReadInt32();
		MetadataToken val = code.ReadToken();
		if (val != MetadataToken.Zero)
		{
			context.Variables = (Collection<VariableDefinition>)(object)code.ReadVariables(val);
		}
		ParseCode(code_size, context);
	}

	private static void ParseCode(int code_size, ParseContext context)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Expected I4, but got Unknown
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_0240: Unknown result type (might be due to invalid IL or missing references)
		//IL_024e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0253: Unknown result type (might be due to invalid IL or missing references)
		//IL_0257: Unknown result type (might be due to invalid IL or missing references)
		//IL_025c: Unknown result type (might be due to invalid IL or missing references)
		//IL_025e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0265: Invalid comparison between Unknown and I4
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_0196: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0226: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: 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_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0183: Unknown result type (might be due to invalid IL or missing references)
		//IL_020d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01db: Unknown result type (might be due to invalid IL or missing references)
		//IL_0287: Unknown result type (might be due to invalid IL or missing references)
		//IL_028e: Invalid comparison between Unknown and I4
		//IL_0267: Unknown result type (might be due to invalid IL or missing references)
		//IL_026e: Invalid comparison between Unknown and I4
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ab: Invalid comparison between Unknown and I4
		//IL_0290: Unknown result type (might be due to invalid IL or missing references)
		//IL_0297: Invalid comparison between Unknown and I4
		//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c7: Expected O, but got Unknown
		//IL_0270: Unknown result type (might be due to invalid IL or missing references)
		//IL_0277: Invalid comparison between Unknown and I4
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b4: Invalid comparison between Unknown and I4
		//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d8: Expected O, but got Unknown
		//IL_0299: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a0: Invalid comparison between Unknown and I4
		//IL_0279: Unknown result type (might be due to invalid IL or missing references)
		//IL_0280: Invalid comparison between Unknown and I4
		//IL_02db: Unknown result type (might be due to invalid IL or missing references)
		//IL_02df: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e9: Expected O, but got Unknown
		//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0312: Unknown result type (might be due to invalid IL or missing references)
		CodeReader code = context.Code;
		MetadataReader metadata = context.Metadata;
		IILVisitor visitor = context.Visitor;
		int num = ((BinaryStreamReader)code).Position + code_size;
		while (((BinaryStreamReader)code).Position < num)
		{
			byte b = ((BinaryReader)(object)code).ReadByte();
			OpCode val = ((b != 254) ? OpCodes.OneByteOpCode[b] : OpCodes.TwoBytesOpCode[((BinaryReader)(object)code).ReadByte()]);
			OperandType operandType = ((OpCode)(ref val)).OperandType;
			IMetadataTokenProvider val2;
			switch ((int)operandType)
			{
			case 5:
				visitor.OnInlineNone(val);
				break;
			case 10:
			{
				int num2 = ((BinaryReader)(object)code).ReadInt32();
				int[] array = new int[num2];
				for (int i = 0; i < num2; i++)
				{
					array[i] = ((BinaryReader)(object)code).ReadInt32();
				}
				visitor.OnInlineSwitch(val, array);
				break;
			}
			case 15:
				visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadSByte());
				break;
			case 0:
				visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadInt32());
				break;
			case 16:
				if (val == OpCodes.Ldc_I4_S)
				{
					visitor.OnInlineSByte(val, ((BinaryReader)(object)code).ReadSByte());
				}
				else
				{
					visitor.OnInlineByte(val, ((BinaryReader)(object)code).ReadByte());
				}
				break;
			case 2:
				visitor.OnInlineInt32(val, ((BinaryReader)(object)code).ReadInt32());
				break;
			case 3:
				visitor.OnInlineInt64(val, ((BinaryReader)(object)code).ReadInt64());
				break;
			case 17:
				visitor.OnInlineSingle(val, ((BinaryReader)(object)code).ReadSingle());
				break;
			case 7:
				visitor.OnInlineDouble(val, ((BinaryReader)(object)code).ReadDouble());
				break;
			case 8:
				visitor.OnInlineSignature(val, code.GetCallSite(code.ReadToken()));
				break;
			case 9:
				visitor.OnInlineString(val, code.GetString(code.ReadToken()));
				break;
			case 19:
				visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadByte()));
				break;
			case 14:
				visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadInt16()));
				break;
			case 18:
				visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadByte()));
				break;
			case 13:
				visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadInt16()));
				break;
			case 1:
			case 4:
			case 11:
			case 12:
				{
					val2 = metadata.LookupToken(code.ReadToken());
					MetadataToken metadataToken = val2.MetadataToken;
					TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType;
					if ((int)tokenType <= 67108864)
					{
						if ((int)tokenType != 16777216 && (int)tokenType != 33554432)
						{
							if ((int)tokenType == 67108864)
							{
								visitor.OnInlineField(val, (FieldReference)val2);
							}
							break;
						}
						goto IL_02b8;
					}
					if ((int)tokenType <= 167772160)
					{
						if ((int)tokenType != 100663296)
						{
							if ((int)tokenType != 167772160)
							{
								break;
							}
							FieldReference val3 = (FieldReference)(object)((val2 is FieldReference) ? val2 : null);
							if (val3 != null)
							{
								visitor.OnInlineField(val, val3);
								break;
							}
							MethodReference val4 = (MethodReference)(object)((val2 is MethodReference) ? val2 : null);
							if (val4 != null)
							{
								visitor.OnInlineMethod(val, val4);
								break;
							}
							throw new InvalidOperationException();
						}
					}
					else
					{
						if ((int)tokenType == 452984832)
						{
							goto IL_02b8;
						}
						if ((int)tokenType != 721420288)
						{
							break;
						}
					}
					visitor.OnInlineMethod(val, (MethodReference)val2);
					break;
				}
				IL_02b8:
				visitor.OnInlineType(val, (TypeReference)val2);
				break;
			}
		}
	}

	private static VariableDefinition GetVariable(ParseContext context, int index)
	{
		return context.Variables[index];
	}
}
public static class MethodBodyRocks
{
	public static void SimplifyMacros(this MethodBody self)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Invalid comparison between Unknown and I4
		//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_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Expected I4, but got Unknown
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_017c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0193: Unknown result type (might be due to invalid IL or missing references)
		//IL_01af: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0203: Unknown result type (might be due to invalid IL or missing references)
		//IL_021f: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0257: Unknown result type (might be due to invalid IL or missing references)
		//IL_0273: Unknown result type (might be due to invalid IL or missing references)
		//IL_0283: Unknown result type (might be due to invalid IL or missing references)
		//IL_0293: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0315: Unknown result type (might be due to invalid IL or missing references)
		//IL_032b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0341: Unknown result type (might be due to invalid IL or missing references)
		//IL_0357: Unknown result type (might be due to invalid IL or missing references)
		//IL_036d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0383: Unknown result type (might be due to invalid IL or missing references)
		//IL_0399: Unknown result type (might be due to invalid IL or missing references)
		//IL_03af: Unknown result type (might be due to invalid IL or missing references)
		//IL_03cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_03df: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_040f: Unknown result type (might be due to invalid IL or missing references)
		//IL_041c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0429: Unknown result type (might be due to invalid IL or missing references)
		//IL_0436: Unknown result type (might be due to invalid IL or missing references)
		//IL_0443: Unknown result type (might be due to invalid IL or missing references)
		//IL_0450: Unknown result type (might be due to invalid IL or missing references)
		//IL_045d: Unknown result type (might be due to invalid IL or missing references)
		//IL_046a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0477: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Invalid comparison between Unknown and I4
		//IL_0484: Unknown result type (might be due to invalid IL or missing references)
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				OpCode opCode = current.OpCode;
				if ((int)((OpCode)(ref opCode)).OpCodeType != 1)
				{
					continue;
				}
				opCode = current.OpCode;
				Code code = ((OpCode)(ref opCode)).Code;
				switch (code - 2)
				{
				case 0:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 0));
					continue;
				case 1:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 1));
					continue;
				case 2:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 2));
					continue;
				case 3:
					ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 3));
					continue;
				case 4:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[0]);
					continue;
				case 5:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[1]);
					continue;
				case 6:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[2]);
					continue;
				case 7:
					ExpandMacro(current, OpCodes.Ldloc, self.Variables[3]);
					continue;
				case 8:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[0]);
					continue;
				case 9:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[1]);
					continue;
				case 10:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[2]);
					continue;
				case 11:
					ExpandMacro(current, OpCodes.Stloc, self.Variables[3]);
					continue;
				case 12:
					current.OpCode = OpCodes.Ldarg;
					continue;
				case 13:
					current.OpCode = OpCodes.Ldarga;
					continue;
				case 14:
					current.OpCode = OpCodes.Starg;
					continue;
				case 15:
					current.OpCode = OpCodes.Ldloc;
					continue;
				case 16:
					current.OpCode = OpCodes.Ldloca;
					continue;
				case 17:
					current.OpCode = OpCodes.Stloc;
					continue;
				case 19:
					ExpandMacro(current, OpCodes.Ldc_I4, -1);
					continue;
				case 20:
					ExpandMacro(current, OpCodes.Ldc_I4, 0);
					continue;
				case 21:
					ExpandMacro(current, OpCodes.Ldc_I4, 1);
					continue;
				case 22:
					ExpandMacro(current, OpCodes.Ldc_I4, 2);
					continue;
				case 23:
					ExpandMacro(current, OpCodes.Ldc_I4, 3);
					continue;
				case 24:
					ExpandMacro(current, OpCodes.Ldc_I4, 4);
					continue;
				case 25:
					ExpandMacro(current, OpCodes.Ldc_I4, 5);
					continue;
				case 26:
					ExpandMacro(current, OpCodes.Ldc_I4, 6);
					continue;
				case 27:
					ExpandMacro(current, OpCodes.Ldc_I4, 7);
					continue;
				case 28:
					ExpandMacro(current, OpCodes.Ldc_I4, 8);
					continue;
				case 29:
					ExpandMacro(current, OpCodes.Ldc_I4, (int)(sbyte)current.Operand);
					continue;
				case 40:
					current.OpCode = OpCodes.Br;
					continue;
				case 41:
					current.OpCode = OpCodes.Brfalse;
					continue;
				case 42:
					current.OpCode = OpCodes.Brtrue;
					continue;
				case 43:
					current.OpCode = OpCodes.Beq;
					continue;
				case 44:
					current.OpCode = OpCodes.Bge;
					continue;
				case 45:
					current.OpCode = OpCodes.Bgt;
					continue;
				case 46:
					current.OpCode = OpCodes.Ble;
					continue;
				case 47:
					current.OpCode = OpCodes.Blt;
					continue;
				case 48:
					current.OpCode = OpCodes.Bne_Un;
					continue;
				case 49:
					current.OpCode = OpCodes.Bge_Un;
					continue;
				case 50:
					current.OpCode = OpCodes.Bgt_Un;
					continue;
				case 51:
					current.OpCode = OpCodes.Ble_Un;
					continue;
				case 52:
					current.OpCode = OpCodes.Blt_Un;
					continue;
				case 18:
				case 30:
				case 31:
				case 32:
				case 33:
				case 34:
				case 35:
				case 36:
				case 37:
				case 38:
				case 39:
					continue;
				}
				if ((int)code == 188)
				{
					current.OpCode = OpCodes.Leave;
				}
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static void ExpandMacro(Instruction instruction, OpCode opcode, object operand)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		instruction.OpCode = opcode;
		instruction.Operand = operand;
	}

	private static void MakeMacro(Instruction instruction, OpCode opcode)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		instruction.OpCode = opcode;
		instruction.Operand = null;
	}

	public static void Optimize(this MethodBody self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		self.OptimizeLongs();
		self.OptimizeMacros();
	}

	private static void OptimizeLongs(this MethodBody self)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Invalid comparison between Unknown and I4
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < self.Instructions.Count; i++)
		{
			Instruction val = self.Instructions[i];
			OpCode opCode = val.OpCode;
			if ((int)((OpCode)(ref opCode)).Code == 33)
			{
				long num = (long)val.Operand;
				if (num < int.MaxValue && num > int.MinValue)
				{
					ExpandMacro(val, OpCodes.Ldc_I4, (int)num);
					self.Instructions.Insert(++i, Instruction.Create(OpCodes.Conv_I8));
				}
			}
		}
	}

	public static void OptimizeMacros(this MethodBody self)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: 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)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Invalid comparison between Unknown and I4
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Expected I4, but got Unknown
		//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_030a: Unknown result type (might be due to invalid IL or missing references)
		//IL_031a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0327: Unknown result type (might be due to invalid IL or missing references)
		//IL_0334: Unknown result type (might be due to invalid IL or missing references)
		//IL_0341: Unknown result type (might be due to invalid IL or missing references)
		//IL_034e: Unknown result type (might be due to invalid IL or missing references)
		//IL_035b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0368: Unknown result type (might be due to invalid IL or missing references)
		//IL_0375: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_028c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ae: 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_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_0168: Unknown result type (might be due to invalid IL or missing references)
		//IL_0178: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0202: Unknown result type (might be due to invalid IL or missing references)
		//IL_0391: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: 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)
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_0271: Unknown result type (might be due to invalid IL or missing references)
		//IL_0193: Unknown result type (might be due to invalid IL or missing references)
		//IL_021d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		MethodDefinition method = self.Method;
		Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				OpCode opCode = current.OpCode;
				Code code = ((OpCode)(ref opCode)).Code;
				if ((int)code != 32)
				{
					switch (code - 199)
					{
					case 0:
					{
						int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index;
						if (index == -1 && current.Operand == self.ThisParameter)
						{
							index = 0;
						}
						else if (((MethodReference)method).HasThis)
						{
							index++;
						}
						switch (index)
						{
						case 0:
							MakeMacro(current, OpCodes.Ldarg_0);
							break;
						case 1:
							MakeMacro(current, OpCodes.Ldarg_1);
							break;
						case 2:
							MakeMacro(current, OpCodes.Ldarg_2);
							break;
						case 3:
							MakeMacro(current, OpCodes.Ldarg_3);
							break;
						default:
							if (index < 256)
							{
								ExpandMacro(current, OpCodes.Ldarg_S, current.Operand);
							}
							break;
						}
						break;
					}
					case 3:
					{
						int index = ((VariableReference)(VariableDefinition)current.Operand).Index;
						switch (index)
						{
						case 0:
							MakeMacro(current, OpCodes.Ldloc_0);
							break;
						case 1:
							MakeMacro(current, OpCodes.Ldloc_1);
							break;
						case 2:
							MakeMacro(current, OpCodes.Ldloc_2);
							break;
						case 3:
							MakeMacro(current, OpCodes.Ldloc_3);
							break;
						default:
							if (index < 256)
							{
								ExpandMacro(current, OpCodes.Ldloc_S, current.Operand);
							}
							break;
						}
						break;
					}
					case 5:
					{
						int index = ((VariableReference)(VariableDefinition)current.Operand).Index;
						switch (index)
						{
						case 0:
							MakeMacro(current, OpCodes.Stloc_0);
							break;
						case 1:
							MakeMacro(current, OpCodes.Stloc_1);
							break;
						case 2:
							MakeMacro(current, OpCodes.Stloc_2);
							break;
						case 3:
							MakeMacro(current, OpCodes.Stloc_3);
							break;
						default:
							if (index < 256)
							{
								ExpandMacro(current, OpCodes.Stloc_S, current.Operand);
							}
							break;
						}
						break;
					}
					case 1:
					{
						int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index;
						if (index == -1 && current.Operand == self.ThisParameter)
						{
							index = 0;
						}
						else if (((MethodReference)method).HasThis)
						{
							index++;
						}
						if (index < 256)
						{
							ExpandMacro(current, OpCodes.Ldarga_S, current.Operand);
						}
						break;
					}
					case 4:
						if (((VariableReference)(VariableDefinition)current.Operand).Index < 256)
						{
							ExpandMacro(current, OpCodes.Ldloca_S, current.Operand);
						}
						break;
					}
					continue;
				}
				int num = (int)current.Operand;
				switch (num)
				{
				case -1:
					MakeMacro(current, OpCodes.Ldc_I4_M1);
					continue;
				case 0:
					MakeMacro(current, OpCodes.Ldc_I4_0);
					continue;
				case 1:
					MakeMacro(current, OpCodes.Ldc_I4_1);
					continue;
				case 2:
					MakeMacro(current, OpCodes.Ldc_I4_2);
					continue;
				case 3:
					MakeMacro(current, OpCodes.Ldc_I4_3);
					continue;
				case 4:
					MakeMacro(current, OpCodes.Ldc_I4_4);
					continue;
				case 5:
					MakeMacro(current, OpCodes.Ldc_I4_5);
					continue;
				case 6:
					MakeMacro(current, OpCodes.Ldc_I4_6);
					continue;
				case 7:
					MakeMacro(current, OpCodes.Ldc_I4_7);
					continue;
				case 8:
					MakeMacro(current, OpCodes.Ldc_I4_8);
					continue;
				}
				if (num >= -128 && num < 128)
				{
					ExpandMacro(current, OpCodes.Ldc_I4_S, (sbyte)num);
				}
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
		OptimizeBranches(self);
	}

	private static void OptimizeBranches(MethodBody body)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: 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_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		ComputeOffsets(body);
		Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				OpCode opCode = current.OpCode;
				if ((int)((OpCode)(ref opCode)).OperandType == 0 && OptimizeBranch(current))
				{
					ComputeOffsets(body);
				}
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static bool OptimizeBranch(Instruction instruction)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Expected I4, but got Unknown
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: 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_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Invalid comparison between Unknown and I4
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		int offset = ((Instruction)instruction.Operand).Offset;
		int offset2 = instruction.Offset;
		OpCode opCode = instruction.OpCode;
		int num = offset - (offset2 + ((OpCode)(ref opCode)).Size + 4);
		if (num < -128 || num > 127)
		{
			return false;
		}
		opCode = instruction.OpCode;
		Code code = ((OpCode)(ref opCode)).Code;
		switch (code - 55)
		{
		default:
			if ((int)code == 187)
			{
				instruction.OpCode = OpCodes.Leave_S;
			}
			break;
		case 0:
			instruction.OpCode = OpCodes.Br_S;
			break;
		case 1:
			instruction.OpCode = OpCodes.Brfalse_S;
			break;
		case 2:
			instruction.OpCode = OpCodes.Brtrue_S;
			break;
		case 3:
			instruction.OpCode = OpCodes.Beq_S;
			break;
		case 4:
			instruction.OpCode = OpCodes.Bge_S;
			break;
		case 5:
			instruction.OpCode = OpCodes.Bgt_S;
			break;
		case 6:
			instruction.OpCode = OpCodes.Ble_S;
			break;
		case 7:
			instruction.OpCode = OpCodes.Blt_S;
			break;
		case 8:
			instruction.OpCode = OpCodes.Bne_Un_S;
			break;
		case 9:
			instruction.OpCode = OpCodes.Bge_Un_S;
			break;
		case 10:
			instruction.OpCode = OpCodes.Bgt_Un_S;
			break;
		case 11:
			instruction.OpCode = OpCodes.Ble_Un_S;
			break;
		case 12:
			instruction.OpCode = OpCodes.Blt_Un_S;
			break;
		}
		return true;
	}

	private static void ComputeOffsets(MethodBody body)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		int num = 0;
		Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				Instruction current = enumerator.Current;
				current.Offset = num;
				num += current.GetSize();
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}
}
public static class MethodDefinitionRocks
{
	public static MethodDefinition GetBaseMethod(this MethodDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.IsVirtual)
		{
			return self;
		}
		if (self.IsNewSlot)
		{
			return self;
		}
		for (TypeDefinition val = ResolveBaseType(self.DeclaringType); val != null; val = ResolveBaseType(val))
		{
			MethodDefinition matchingMethod = GetMatchingMethod(val, self);
			if (matchingMethod != null)
			{
				return matchingMethod;
			}
		}
		return self;
	}

	public static MethodDefinition GetOriginalBaseMethod(this MethodDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		while (true)
		{
			MethodDefinition baseMethod = self.GetBaseMethod();
			if (baseMethod == self)
			{
				break;
			}
			self = baseMethod;
		}
		return self;
	}

	private static TypeDefinition ResolveBaseType(TypeDefinition type)
	{
		if (type == null)
		{
			return null;
		}
		TypeReference baseType = type.BaseType;
		if (baseType == null)
		{
			return null;
		}
		return baseType.Resolve();
	}

	private static MethodDefinition GetMatchingMethod(TypeDefinition type, MethodDefinition method)
	{
		return MetadataResolver.GetMethod(type.Methods, (MethodReference)(object)method);
	}
}
public static class ModuleDefinitionRocks
{
	public static IEnumerable<TypeDefinition> GetAllTypes(this ModuleDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		return ((IEnumerable<TypeDefinition>)self.Types).SelectMany(Functional.Y((Func<TypeDefinition, IEnumerable<TypeDefinition>> f) => (TypeDefinition type) => ((IEnumerable<TypeDefinition>)type.NestedTypes).SelectMany(f).Prepend(type)));
	}
}
public static class ParameterReferenceRocks
{
	public static int GetSequence(this ParameterReference self)
	{
		return self.Index + 1;
	}
}
public static class SecurityDeclarationRocks
{
	public static PermissionSet ToPermissionSet(this SecurityDeclaration self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (TryProcessPermissionSetAttribute(self, out var set))
		{
			return set;
		}
		return CreatePermissionSet(self);
	}

	private static bool TryProcessPermissionSetAttribute(SecurityDeclaration declaration, out PermissionSet set)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Expected I4, but got Unknown
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Expected O, but got Unknown
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		set = null;
		if (!declaration.HasSecurityAttributes && declaration.SecurityAttributes.Count != 1)
		{
			return false;
		}
		SecurityAttribute val = declaration.SecurityAttributes[0];
		if (!Mixin.IsTypeOf(val.AttributeType, "System.Security.Permissions", "PermissionSetAttribute"))
		{
			return false;
		}
		PermissionSetAttribute val2 = new PermissionSetAttribute((SecurityAction)declaration.Action);
		CustomAttributeNamedArgument val3 = val.Properties[0];
		CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref val3)).Argument;
		string text = (string)((CustomAttributeArgument)(ref argument)).Value;
		string name = ((CustomAttributeNamedArgument)(ref val3)).Name;
		if (!(name == "XML"))
		{
			if (!(name == "Name"))
			{
				throw new NotImplementedException(((CustomAttributeNamedArgument)(ref val3)).Name);
			}
			val2.Name = text;
		}
		else
		{
			val2.XML = text;
		}
		set = val2.CreatePermissionSet();
		return true;
	}

	private static PermissionSet CreatePermissionSet(SecurityDeclaration declaration)
	{
		//IL_000d: 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)
		PermissionSet permissionSet = new PermissionSet(PermissionState.None);
		Enumerator<SecurityAttribute> enumerator = declaration.SecurityAttributes.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				SecurityAttribute current = enumerator.Current;
				IPermission perm = CreatePermission(declaration, current);
				permissionSet.AddPermission(perm);
			}
			return permissionSet;
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static IPermission CreatePermission(SecurityDeclaration declaration, SecurityAttribute attribute)
	{
		SecurityAttribute obj = CreateSecurityAttribute(Type.GetType(((MemberReference)attribute.AttributeType).FullName) ?? throw new ArgumentException("attribute"), declaration) ?? throw new InvalidOperationException();
		CompleteSecurityAttribute(obj, attribute);
		return obj.CreatePermission();
	}

	private static void CompleteSecurityAttribute(SecurityAttribute security_attribute, SecurityAttribute attribute)
	{
		if (attribute.HasFields)
		{
			CompleteSecurityAttributeFields(security_attribute, attribute);
		}
		if (attribute.HasProperties)
		{
			CompleteSecurityAttributeProperties(security_attribute, attribute);
		}
	}

	private static void CompleteSecurityAttributeFields(SecurityAttribute security_attribute, SecurityAttribute attribute)
	{
		//IL_000d: 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)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		Type type = security_attribute.GetType();
		Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Fields.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				CustomAttributeNamedArgument current = enumerator.Current;
				FieldInfo? field = type.GetField(((CustomAttributeNamedArgument)(ref current)).Name);
				CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument;
				field.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value);
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static void CompleteSecurityAttributeProperties(SecurityAttribute security_attribute, SecurityAttribute attribute)
	{
		//IL_000d: 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)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		Type type = security_attribute.GetType();
		Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Properties.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				CustomAttributeNamedArgument current = enumerator.Current;
				PropertyInfo? property = type.GetProperty(((CustomAttributeNamedArgument)(ref current)).Name);
				CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument;
				property.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value, null);
			}
		}
		finally
		{
			((IDisposable)enumerator).Dispose();
		}
	}

	private static SecurityAttribute CreateSecurityAttribute(Type attribute_type, SecurityDeclaration declaration)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Expected I4, but got Unknown
		try
		{
			return (SecurityAttribute)Activator.CreateInstance(attribute_type, (SecurityAction)declaration.Action);
		}
		catch (MissingMethodException)
		{
			return (SecurityAttribute)Activator.CreateInstance(attribute_type, new object[0]);
		}
	}

	public static SecurityDeclaration ToSecurityDeclaration(this PermissionSet self, SecurityAction action, ModuleDefinition module)
	{
		//IL_001c: 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_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Expected O, but got Unknown
		//IL_005e: 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)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Expected O, but got Unknown
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (module == null)
		{
			throw new ArgumentNullException("module");
		}
		SecurityDeclaration val = new SecurityDeclaration(action);
		SecurityAttribute val2 = new SecurityAttribute(module.TypeSystem.LookupType("System.Security.Permissions", "PermissionSetAttribute"));
		val2.Properties.Add(new CustomAttributeNamedArgument("XML", new CustomAttributeArgument(module.TypeSystem.String, (object)self.ToXml().ToString())));
		val.SecurityAttributes.Add(val2);
		return val;
	}
}
public static class TypeDefinitionRocks
{
	public static IEnumerable<MethodDefinition> GetConstructors(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.HasMethods)
		{
			return Empty<MethodDefinition>.Array;
		}
		return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => method.IsConstructor);
	}

	public static MethodDefinition GetStaticConstructor(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.HasMethods)
		{
			return null;
		}
		return self.GetConstructors().FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition ctor) => ctor.IsStatic));
	}

	public static IEnumerable<MethodDefinition> GetMethods(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.HasMethods)
		{
			return Empty<MethodDefinition>.Array;
		}
		return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => !method.IsConstructor);
	}

	public static TypeReference GetEnumUnderlyingType(this TypeDefinition self)
	{
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (!self.IsEnum)
		{
			throw new ArgumentException();
		}
		return Mixin.GetEnumUnderlyingType(self);
	}
}
public static class TypeReferenceRocks
{
	public static ArrayType MakeArrayType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new ArrayType(self);
	}

	public static ArrayType MakeArrayType(this TypeReference self, int rank)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Expected O, but got Unknown
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		if (rank == 0)
		{
			throw new ArgumentOutOfRangeException("rank");
		}
		ArrayType val = new ArrayType(self);
		for (int i = 1; i < rank; i++)
		{
			val.Dimensions.Add(default(ArrayDimension));
		}
		return val;
	}

	public static PointerType MakePointerType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new PointerType(self);
	}

	public static ByReferenceType MakeByReferenceType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new ByReferenceType(self);
	}

	public static OptionalModifierType MakeOptionalModifierType(this TypeReference self, TypeReference modifierType)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		return new OptionalModifierType(modifierType, self);
	}

	public static RequiredModifierType MakeRequiredModifierType(this TypeReference self, TypeReference modifierType)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Expected O, but got Unknown
		return new RequiredModifierType(modifierType, self);
	}

	public static GenericInstanceType MakeGenericInstanceType(this TypeReference self, params TypeReference[] arguments)
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Expected O, but got Unknown
		if (self == null)
		{
			throw new ArgumentNullException("self");
		}
		if (arguments == null)
		{
			throw new ArgumentNullException("arguments");
		}
		if (arguments.Length == 0)
		{
			throw new ArgumentException();
		}
		if (self.GenericParameters.Count != arguments.Length)
		{
			throw new ArgumentException();
		}
		GenericInstanceType val = new GenericInstanceType(self);
		foreach (TypeReference val2 in arguments)
		{
			val.GenericArguments.Add(val2);
		}
		return val;
	}

	public static PinnedType MakePinnedType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new PinnedType(self);
	}

	public static SentinelType MakeSentinelType(this TypeReference self)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		return new SentinelType(self);
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/patchers/BepInEx.MonoMod.HookGenPatcher/BepInEx.MonoMod.HookGenPatcher.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using BepInEx.Configuration;
using BepInEx.Logging;
using Mono.Cecil;
using MonoMod;
using MonoMod.RuntimeDetour.HookGen;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Bepinex.Monomod.HookGenPatcher")]
[assembly: AssemblyDescription("Runtime HookGen for BepInEx")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HarbingerOfMe")]
[assembly: AssemblyProduct("Bepinex.Monomod.HookGenPatcher")]
[assembly: AssemblyCopyright("HarbingerOfMe-2022")]
[assembly: AssemblyTrademark("MIT")]
[assembly: ComVisible(false)]
[assembly: Guid("12032e45-9577-4195-8f4f-a729911b2f08")]
[assembly: AssemblyFileVersion("1.2.1.0")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("1.2.1.0")]
namespace BepInEx.MonoMod.HookGenPatcher;

public static class HookGenPatcher
{
	internal static ManualLogSource Logger = Logger.CreateLogSource("HookGenPatcher");

	private const string CONFIG_FILE_NAME = "HookGenPatcher.cfg";

	private static readonly ConfigFile Config = new ConfigFile(Path.Combine(Paths.ConfigPath, "HookGenPatcher.cfg"), true);

	private const char EntrySeparator = ',';

	private static readonly ConfigEntry<string> AssemblyNamesToHookGenPatch = Config.Bind<string>("General", "MMHOOKAssemblyNames", "Assembly-CSharp.dll", $"Assembly names to make mmhooks for, separate entries with : {','} ");

	private static readonly ConfigEntry<bool> preciseHash = Config.Bind<bool>("General", "Preciser filehashing", false, "Hash file using contents instead of size. Minor perfomance impact.");

	private static bool skipHashing => !preciseHash.Value;

	public static IEnumerable<string> TargetDLLs { get; } = new string[0];


	public static void Initialize()
	{
		//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cf: Expected O, but got Unknown
		//IL_0237: Unknown result type (might be due to invalid IL or missing references)
		//IL_023e: Expected O, but got Unknown
		//IL_0278: Unknown result type (might be due to invalid IL or missing references)
		//IL_0282: Expected O, but got Unknown
		//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ce: Expected O, but got Unknown
		string[] array = AssemblyNamesToHookGenPatch.Value.Split(new char[1] { ',' });
		string text = Path.Combine(Paths.PluginPath, "MMHOOK");
		string[] array2 = array;
		foreach (string text2 in array2)
		{
			string text3 = "MMHOOK_" + text2;
			string text4 = Path.Combine(Paths.ManagedPath, text2);
			string text5 = Path.Combine(text, text3);
			bool flag = true;
			string[] files = Directory.GetFiles(Paths.PluginPath, text3, SearchOption.AllDirectories);
			foreach (string text6 in files)
			{
				if (Path.GetFileName(text6).Equals(text3))
				{
					text5 = text6;
					Logger.LogInfo((object)"Previous MMHOOK location found. Using that location to save instead.");
					flag = false;
					break;
				}
			}
			if (flag)
			{
				Directory.CreateDirectory(text);
			}
			FileInfo fileInfo = new FileInfo(text4);
			long length = fileInfo.Length;
			long num = 0L;
			if (File.Exists(text5))
			{
				try
				{
					AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text5);
					try
					{
						if (val.MainModule.GetType("BepHookGen.size" + length) != null)
						{
							if (skipHashing)
							{
								Logger.LogInfo((object)"Already ran for this version, reusing that file.");
								continue;
							}
							num = fileInfo.makeHash();
							if (val.MainModule.GetType("BepHookGen.content" + num) != null)
							{
								Logger.LogInfo((object)"Already ran for this version, reusing that file.");
								continue;
							}
						}
					}
					finally
					{
						((IDisposable)val)?.Dispose();
					}
				}
				catch (BadImageFormatException)
				{
					Logger.LogWarning((object)("Failed to read " + Path.GetFileName(text5) + ", probably corrupted, remaking one."));
				}
			}
			Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1");
			Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0");
			MonoModder val2 = new MonoModder
			{
				InputPath = text4,
				OutputPath = text5,
				ReadingMode = (ReadingMode)2
			};
			try
			{
				IAssemblyResolver assemblyResolver = val2.AssemblyResolver;
				IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
				if (obj != null)
				{
					((BaseAssemblyResolver)obj).AddSearchDirectory(Paths.BepInExAssemblyDirectory);
				}
				val2.Read();
				val2.MapDependencies();
				if (File.Exists(text5))
				{
					Logger.LogDebug((object)("Clearing " + text5));
					File.Delete(text5);
				}
				Logger.LogInfo((object)"Starting HookGenerator");
				HookGenerator val3 = new HookGenerator(val2, Path.GetFileName(text5));
				ModuleDefinition outputModule = val3.OutputModule;
				try
				{
					val3.Generate();
					outputModule.Types.Add(new TypeDefinition("BepHookGen", "size" + length, (TypeAttributes)1, outputModule.TypeSystem.Object));
					if (!skipHashing)
					{
						outputModule.Types.Add(new TypeDefinition("BepHookGen", "content" + ((num == 0L) ? fileInfo.makeHash() : num), (TypeAttributes)1, outputModule.TypeSystem.Object));
					}
					outputModule.Write(text5);
				}
				finally
				{
					((IDisposable)outputModule)?.Dispose();
				}
				Logger.LogInfo((object)"Done.");
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}
	}

	public static void Patch(AssemblyDefinition _)
	{
	}

	private static long makeHash(this FileInfo fileInfo)
	{
		FileStream inputStream = fileInfo.OpenRead();
		byte[] value = null;
		using (MD5 mD = new MD5CryptoServiceProvider())
		{
			value = mD.ComputeHash(inputStream);
		}
		long num = BitConverter.ToInt64(value, 0);
		if (num == 0L)
		{
			return 1L;
		}
		return num;
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/patchers/BepInEx.MonoMod.HookGenPatcher/MonoMod.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Mdb;
using Mono.Cecil.Pdb;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.InlineRT;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2021 0x0ade")]
[assembly: AssemblyDescription("General purpose .NET assembly modding \"basework\". This package contains the core IL patcher and relinker.")]
[assembly: AssemblyFileVersion("21.8.5.1")]
[assembly: AssemblyInformationalVersion("21.08.05.01")]
[assembly: AssemblyProduct("MonoMod")]
[assembly: AssemblyTitle("MonoMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("21.8.5.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	[MonoMod__SafeToCopy__]
	public class MonoModAdded : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModConstructor : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModCustomAttributeAttribute : Attribute
	{
		public MonoModCustomAttributeAttribute(string h)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModCustomMethodAttributeAttribute : Attribute
	{
		public MonoModCustomMethodAttributeAttribute(string h)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModEnumReplace : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModForceCall : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModForceCallvirt : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	[Obsolete("Use MonoModLinkFrom or RuntimeDetour / HookGen instead.")]
	public class MonoModHook : Attribute
	{
		public string FindableID;

		public Type Type;

		public MonoModHook(string findableID)
		{
			FindableID = findableID;
		}

		public MonoModHook(Type type)
		{
			Type = type;
			FindableID = type.FullName;
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModIfFlag : Attribute
	{
		public MonoModIfFlag(string key)
		{
		}

		public MonoModIfFlag(string key, bool fallback)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModIgnore : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	public class MonoModLinkFrom : Attribute
	{
		public string FindableID;

		public Type Type;

		public MonoModLinkFrom(string findableID)
		{
			FindableID = findableID;
		}

		public MonoModLinkFrom(Type type)
		{
			Type = type;
			FindableID = type.FullName;
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModLinkTo : Attribute
	{
		public MonoModLinkTo(string t)
		{
		}

		public MonoModLinkTo(Type t)
		{
		}

		public MonoModLinkTo(string t, string n)
		{
		}

		public MonoModLinkTo(Type t, string n)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModNoNew : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOnPlatform : Attribute
	{
		public MonoModOnPlatform(params Platform[] p)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOriginal : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModOriginalName : Attribute
	{
		public MonoModOriginalName(string n)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModPatch : Attribute
	{
		public MonoModPatch(string name)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	public class MonoModPublic : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModRemove : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModReplace : Attribute
	{
	}
	[MonoMod__SafeToCopy__]
	public class MonoModTargetModule : Attribute
	{
		public MonoModTargetModule(string name)
		{
		}
	}
	[MonoMod__SafeToCopy__]
	internal class MonoMod__SafeToCopy__ : Attribute
	{
	}
	public delegate bool MethodParser(MonoModder modder, MethodBody body, Instruction instr, ref int instri);
	public delegate void MethodRewriter(MonoModder modder, MethodDefinition method);
	public delegate void MethodBodyRewriter(MonoModder modder, MethodBody body, Instruction instr, int instri);
	public delegate ModuleDefinition MissingDependencyResolver(MonoModder modder, ModuleDefinition main, string name, string fullName);
	public delegate void PostProcessor(MonoModder modder);
	public delegate void ModReadEventHandler(MonoModder modder, ModuleDefinition mod);
	public class RelinkMapEntry
	{
		public string Type;

		public string FindableID;

		public RelinkMapEntry()
		{
		}

		public RelinkMapEntry(string type, string findableID)
		{
			Type = type;
			FindableID = findableID;
		}
	}
	public enum DebugSymbolFormat
	{
		Auto,
		MDB,
		PDB
	}
	public class MonoModder : IDisposable
	{
		public static readonly bool IsMono = (object)Type.GetType("Mono.Runtime") != null;

		public static readonly Version Version = typeof(MonoModder).Assembly.GetName().Version;

		public Dictionary<string, object> SharedData = new Dictionary<string, object>();

		public Dictionary<string, object> RelinkMap = new Dictionary<string, object>();

		public Dictionary<string, ModuleDefinition> RelinkModuleMap = new Dictionary<string, ModuleDefinition>();

		public HashSet<string> SkipList = new HashSet<string>(EqualityComparer<string>.Default);

		public Dictionary<string, IMetadataTokenProvider> RelinkMapCache = new Dictionary<string, IMetadataTokenProvider>();

		public Dictionary<string, TypeReference> RelinkModuleMapCache = new Dictionary<string, TypeReference>();

		public Dictionary<string, OpCode> ForceCallMap = new Dictionary<string, OpCode>();

		public ModReadEventHandler OnReadMod;

		public PostProcessor PostProcessors;

		public Dictionary<string, Action<object, object[]>> CustomAttributeHandlers = new Dictionary<string, Action<object, object[]>> { 
		{
			"MonoMod.MonoModPublic",
			delegate
			{
			}
		} };

		public Dictionary<string, Action<object, object[]>> CustomMethodAttributeHandlers = new Dictionary<string, Action<object, object[]>>();

		public MissingDependencyResolver MissingDependencyResolver;

		public MethodParser MethodParser;

		public MethodRewriter MethodRewriter;

		public MethodBodyRewriter MethodBodyRewriter;

		public Stream Input;

		public string InputPath;

		public Stream Output;

		public string OutputPath;

		public List<string> DependencyDirs = new List<string>();

		public ModuleDefinition Module;

		public Dictionary<ModuleDefinition, List<ModuleDefinition>> DependencyMap = new Dictionary<ModuleDefinition, List<ModuleDefinition>>();

		public Dictionary<string, ModuleDefinition> DependencyCache = new Dictionary<string, ModuleDefinition>();

		public Func<ICustomAttributeProvider, TypeReference, bool> ShouldCleanupAttrib;

		public bool LogVerboseEnabled;

		public bool CleanupEnabled;

		public bool PublicEverything;

		public List<ModuleReference> Mods = new List<ModuleReference>();

		public bool Strict;

		public bool MissingDependencyThrow;

		public bool RemovePatchReferences;

		public bool PreventInline;

		public bool? UpgradeMSCORLIB;

		public ReadingMode ReadingMode = (ReadingMode)1;

		public DebugSymbolFormat DebugSymbolOutputFormat;

		public int CurrentRID;

		protected IAssemblyResolver _assemblyResolver;

		protected ReaderParameters _readerParameters;

		protected WriterParameters _writerParameters;

		public bool GACEnabled;

		private string[] _GACPathsNone = new string[0];

		protected string[] _GACPaths;

		protected MethodDefinition _mmOriginalCtor;

		protected MethodDefinition _mmOriginalNameCtor;

		protected MethodDefinition _mmAddedCtor;

		protected MethodDefinition _mmPatchCtor;

		public virtual IAssemblyResolver AssemblyResolver
		{
			get
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Expected O, but got Unknown
				if (_assemblyResolver == null)
				{
					DefaultAssemblyResolver val = new DefaultAssemblyResolver();
					foreach (string dependencyDir in DependencyDirs)
					{
						((BaseAssemblyResolver)val).AddSearchDirectory(dependencyDir);
					}
					_assemblyResolver = (IAssemblyResolver)(object)val;
				}
				return _assemblyResolver;
			}
			set
			{
				_assemblyResolver = value;
			}
		}

		public virtual ReaderParameters ReaderParameters
		{
			get
			{
				//IL_000a: 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)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Expected O, but got Unknown
				if (_readerParameters == null)
				{
					_readerParameters = new ReaderParameters(ReadingMode)
					{
						AssemblyResolver = AssemblyResolver,
						ReadSymbols = true
					};
				}
				return _readerParameters;
			}
			set
			{
				_readerParameters = value;
			}
		}

		public virtual WriterParameters WriterParameters
		{
			get
			{
				//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_0043: 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_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_005c: Expected O, but got Unknown
				//IL_0067: Expected O, but got Unknown
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0053: Expected O, but got Unknown
				if (_writerParameters == null)
				{
					bool flag = DebugSymbolOutputFormat == DebugSymbolFormat.PDB;
					bool flag2 = DebugSymbolOutputFormat == DebugSymbolFormat.MDB;
					if (DebugSymbolOutputFormat == DebugSymbolFormat.Auto)
					{
						if ((PlatformHelper.Current & 0x25) == 37)
						{
							flag = true;
						}
						else
						{
							flag2 = true;
						}
					}
					WriterParameters val = new WriterParameters
					{
						WriteSymbols = true
					};
					object symbolWriterProvider;
					if (!flag)
					{
						if (!flag2)
						{
							symbolWriterProvider = null;
						}
						else
						{
							ISymbolWriterProvider val2 = (ISymbolWriterProvider)new MdbWriterProvider();
							symbolWriterProvider = val2;
						}
					}
					else
					{
						ISymbolWriterProvider val2 = (ISymbolWriterProvider)new NativePdbWriterProvider();
						symbolWriterProvider = val2;
					}
					val.SymbolWriterProvider = (ISymbolWriterProvider)symbolWriterProvider;
					_writerParameters = val;
				}
				return _writerParameters;
			}
			set
			{
				_writerParameters = value;
			}
		}

		public string[] GACPaths
		{
			get
			{
				if (!GACEnabled)
				{
					return _GACPathsNone;
				}
				if (_GACPaths != null)
				{
					return _GACPaths;
				}
				if (!IsMono)
				{
					string environmentVariable = Environment.GetEnvironmentVariable("windir");
					if (string.IsNullOrEmpty(environmentVariable))
					{
						return _GACPaths = _GACPathsNone;
					}
					environmentVariable = Path.Combine(environmentVariable, "Microsoft.NET");
					environmentVariable = Path.Combine(environmentVariable, "assembly");
					_GACPaths = new string[3]
					{
						Path.Combine(environmentVariable, "GAC_32"),
						Path.Combine(environmentVariable, "GAC_64"),
						Path.Combine(environmentVariable, "GAC_MSIL")
					};
				}
				else
				{
					List<string> list = new List<string>();
					string text = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName)), "gac");
					if (Directory.Exists(text))
					{
						list.Add(text);
					}
					string environmentVariable2 = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX");
					if (!string.IsNullOrEmpty(environmentVariable2))
					{
						string[] array = environmentVariable2.Split(new char[1] { Path.PathSeparator });
						foreach (string text2 in array)
						{
							if (!string.IsNullOrEmpty(text2))
							{
								string path = text2;
								path = Path.Combine(path, "lib");
								path = Path.Combine(path, "mono");
								path = Path.Combine(path, "gac");
								if (Directory.Exists(path) && !list.Contains(path))
								{
									list.Add(path);
								}
							}
						}
					}
					_GACPaths = list.ToArray();
				}
				return _GACPaths;
			}
			set
			{
				GACEnabled = true;
				_GACPaths = value;
			}
		}

		public MonoModder()
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			MethodParser = DefaultParser;
			MissingDependencyResolver = DefaultMissingDependencyResolver;
			PostProcessors = (PostProcessor)Delegate.Combine(PostProcessors, new PostProcessor(DefaultPostProcessor));
			string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DEPDIRS");
			if (!string.IsNullOrEmpty(environmentVariable))
			{
				foreach (string item in from dir in environmentVariable.Split(new char[1] { Path.PathSeparator })
					select dir.Trim())
				{
					IAssemblyResolver assemblyResolver = AssemblyResolver;
					IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
					if (obj != null)
					{
						((BaseAssemblyResolver)obj).AddSearchDirectory(item);
					}
					DependencyDirs.Add(item);
				}
			}
			LogVerboseEnabled = Environment.GetEnvironmentVariable("MONOMOD_LOG_VERBOSE") == "1";
			CleanupEnabled = Environment.GetEnvironmentVariable("MONOMOD_CLEANUP") != "0";
			PublicEverything = Environment.GetEnvironmentVariable("MONOMOD_PUBLIC_EVERYTHING") == "1";
			PreventInline = Environment.GetEnvironmentVariable("MONOMOD_PREVENTINLINE") == "1";
			Strict = Environment.GetEnvironmentVariable("MONOMOD_STRICT") == "1";
			MissingDependencyThrow = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") != "0";
			RemovePatchReferences = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_REMOVE_PATCH") != "0";
			string environmentVariable2 = Environment.GetEnvironmentVariable("MONOMOD_DEBUG_FORMAT");
			if (environmentVariable2 != null)
			{
				environmentVariable2 = environmentVariable2.ToLowerInvariant();
				if (environmentVariable2 == "pdb")
				{
					DebugSymbolOutputFormat = DebugSymbolFormat.PDB;
				}
				else if (environmentVariable2 == "mdb")
				{
					DebugSymbolOutputFormat = DebugSymbolFormat.MDB;
				}
			}
			string environmentVariable3 = Environment.GetEnvironmentVariable("MONOMOD_MSCORLIB_UPGRADE");
			UpgradeMSCORLIB = (string.IsNullOrEmpty(environmentVariable3) ? null : new bool?(environmentVariable3 != "0"));
			GACEnabled = Environment.GetEnvironmentVariable("MONOMOD_GAC_ENABLED") != "0";
			MonoModRulesManager.Register(this);
		}

		public virtual void ClearCaches(bool all = false, bool shareable = false, bool moduleSpecific = false)
		{
			if (all || shareable)
			{
				foreach (KeyValuePair<string, ModuleDefinition> item in DependencyCache)
				{
					item.Value.Dispose();
				}
				DependencyCache.Clear();
			}
			if (all || moduleSpecific)
			{
				RelinkMapCache.Clear();
				RelinkModuleMapCache.Clear();
			}
		}

		public virtual void Dispose()
		{
			//IL_004e: 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)
			ClearCaches(all: true);
			ModuleDefinition module = Module;
			if (module != null)
			{
				module.Dispose();
			}
			Module = null;
			((IDisposable)AssemblyResolver)?.Dispose();
			AssemblyResolver = null;
			foreach (ModuleDefinition mod in Mods)
			{
				if ((int)mod != 0)
				{
					mod.Dispose();
				}
			}
			foreach (List<ModuleDefinition> value in DependencyMap.Values)
			{
				foreach (ModuleDefinition item in value)
				{
					if (item != null)
					{
						item.Dispose();
					}
				}
			}
			DependencyMap.Clear();
			Input?.Dispose();
			Output?.Dispose();
		}

		public virtual void Log(object value)
		{
			Log(value.ToString());
		}

		public virtual void Log(string text)
		{
			Console.Write("[MonoMod] ");
			Console.WriteLine(text);
		}

		public virtual void LogVerbose(object value)
		{
			if (LogVerboseEnabled)
			{
				Log(value);
			}
		}

		public virtual void LogVerbose(string text)
		{
			if (LogVerboseEnabled)
			{
				Log(text);
			}
		}

		private static ModuleDefinition _ReadModule(Stream input, ReaderParameters args)
		{
			if (args.ReadSymbols)
			{
				try
				{
					return ModuleDefinition.ReadModule(input, args);
				}
				catch
				{
					args.ReadSymbols = false;
					input.Seek(0L, SeekOrigin.Begin);
				}
			}
			return ModuleDefinition.ReadModule(input, args);
		}

		private static ModuleDefinition _ReadModule(string input, ReaderParameters args)
		{
			if (args.ReadSymbols)
			{
				try
				{
					return ModuleDefinition.ReadModule(input, args);
				}
				catch
				{
					args.ReadSymbols = false;
				}
			}
			return ModuleDefinition.ReadModule(input, args);
		}

		public virtual void Read()
		{
			if (Module != null)
			{
				return;
			}
			if (Input != null)
			{
				Log("Reading input stream into module.");
				Module = _ReadModule(Input, GenReaderParameters(mainModule: true));
			}
			else if (InputPath != null)
			{
				Log("Reading input file into module.");
				IAssemblyResolver assemblyResolver = AssemblyResolver;
				IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
				if (obj != null)
				{
					((BaseAssemblyResolver)obj).AddSearchDirectory(Path.GetDirectoryName(InputPath));
				}
				DependencyDirs.Add(Path.GetDirectoryName(InputPath));
				Module = _ReadModule(InputPath, GenReaderParameters(mainModule: true, InputPath));
			}
			string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_MODS");
			if (string.IsNullOrEmpty(environmentVariable))
			{
				return;
			}
			foreach (string item in from path in environmentVariable.Split(new char[1] { Path.PathSeparator })
				select path.Trim())
			{
				ReadMod(item);
			}
		}

		public virtual void MapDependencies()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			foreach (ModuleDefinition mod in Mods)
			{
				ModuleDefinition main = mod;
				MapDependencies(main);
			}
			MapDependencies(Module);
		}

		public virtual void MapDependencies(ModuleDefinition main)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (DependencyMap.ContainsKey(main))
			{
				return;
			}
			DependencyMap[main] = new List<ModuleDefinition>();
			Enumerator<AssemblyNameReference> enumerator = main.AssemblyReferences.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					AssemblyNameReference current = enumerator.Current;
					MapDependency(main, current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void MapDependency(ModuleDefinition main, AssemblyNameReference depRef)
		{
			MapDependency(main, depRef.Name, depRef.FullName, depRef);
		}

		public virtual void MapDependency(ModuleDefinition main, string name, string fullName = null, AssemblyNameReference depRef = null)
		{
			if (!DependencyMap.TryGetValue(main, out var value))
			{
				value = (DependencyMap[main] = new List<ModuleDefinition>());
			}
			if (fullName != null && (DependencyCache.TryGetValue(fullName, out var value2) || DependencyCache.TryGetValue(fullName + " [RT:" + main.RuntimeVersion + "]", out value2)))
			{
				LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) from cache");
				value.Add(value2);
				MapDependencies(value2);
				return;
			}
			if (DependencyCache.TryGetValue(name, out value2) || DependencyCache.TryGetValue(name + " [RT:" + main.RuntimeVersion + "]", out value2))
			{
				LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " (" + name + ") from cache");
				value.Add(value2);
				MapDependencies(value2);
				return;
			}
			string text = Path.GetExtension(name).ToLowerInvariant();
			bool flag = text == "pdb" || text == "mdb";
			string text2 = null;
			foreach (string dependencyDir in DependencyDirs)
			{
				text2 = Path.Combine(dependencyDir, name + ".dll");
				if (!File.Exists(text2))
				{
					text2 = Path.Combine(dependencyDir, name + ".exe");
				}
				if (!File.Exists(text2) && !flag)
				{
					text2 = Path.Combine(dependencyDir, name);
				}
				if (File.Exists(text2))
				{
					break;
				}
				text2 = null;
			}
			if (text2 == null && depRef != null)
			{
				try
				{
					AssemblyDefinition obj = AssemblyResolver.Resolve(depRef);
					value2 = ((obj != null) ? obj.MainModule : null);
				}
				catch
				{
				}
				if (value2 != null)
				{
					text2 = value2.FileName;
				}
			}
			if (text2 == null)
			{
				string[] gACPaths = GACPaths;
				for (int i = 0; i < gACPaths.Length; i++)
				{
					text2 = Path.Combine(gACPaths[i], name);
					if (Directory.Exists(text2))
					{
						string[] directories = Directory.GetDirectories(text2);
						int num = 0;
						int num2 = 0;
						for (int j = 0; j < directories.Length; j++)
						{
							string text3 = directories[j];
							if (text3.StartsWith(text2))
							{
								text3 = text3.Substring(text2.Length + 1);
							}
							Match match = Regex.Match(text3, "\\d+");
							if (match.Success)
							{
								int num3 = int.Parse(match.Value);
								if (num3 > num)
								{
									num = num3;
									num2 = j;
								}
							}
						}
						text2 = Path.Combine(directories[num2], name + ".dll");
						break;
					}
					text2 = null;
				}
			}
			if (text2 == null)
			{
				try
				{
					AssemblyDefinition obj3 = AssemblyResolver.Resolve(AssemblyNameReference.Parse(fullName ?? name));
					value2 = ((obj3 != null) ? obj3.MainModule : null);
				}
				catch
				{
				}
				if (value2 != null)
				{
					text2 = value2.FileName;
				}
			}
			if (value2 == null)
			{
				if (text2 != null && File.Exists(text2))
				{
					value2 = _ReadModule(text2, GenReaderParameters(mainModule: false, text2));
				}
				else if ((value2 = MissingDependencyResolver?.Invoke(this, main, name, fullName)) == null)
				{
					return;
				}
			}
			LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) loaded");
			value.Add(value2);
			if (fullName == null)
			{
				fullName = value2.Assembly.FullName;
			}
			DependencyCache[fullName] = value2;
			DependencyCache[name] = value2;
			MapDependencies(value2);
		}

		public virtual ModuleDefinition DefaultMissingDependencyResolver(MonoModder mod, ModuleDefinition main, string name, string fullName)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (MissingDependencyThrow && Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") == "0")
			{
				Log("[MissingDependencyResolver] [WARNING] Use MMILRT.Modder.MissingDependencyThrow instead of setting the env var MONOMOD_DEPENDENCY_MISSING_THROW");
				MissingDependencyThrow = false;
			}
			if (MissingDependencyThrow || Strict)
			{
				throw new RelinkTargetNotFoundException("MonoMod cannot map dependency " + ((ModuleReference)main).Name + " -> ((" + fullName + "), (" + name + ")) - not found", (IMetadataTokenProvider)(object)main, (IMetadataTokenProvider)null);
			}
			return null;
		}

		public virtual void Write(Stream output = null, string outputPath = null)
		{
			output = output ?? Output;
			outputPath = outputPath ?? OutputPath;
			PatchRefsInType(PatchWasHere());
			if (output != null)
			{
				Log("[Write] Writing modded module into output stream.");
				Module.Write(output, WriterParameters);
			}
			else
			{
				Log("[Write] Writing modded module into output file.");
				Module.Write(outputPath, WriterParameters);
			}
		}

		public virtual ReaderParameters GenReaderParameters(bool mainModule, string path = null)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			ReaderParameters readerParameters = ReaderParameters;
			ReaderParameters val = new ReaderParameters(readerParameters.ReadingMode);
			val.AssemblyResolver = readerParameters.AssemblyResolver;
			val.MetadataResolver = readerParameters.MetadataResolver;
			val.InMemory = readerParameters.InMemory;
			val.MetadataImporterProvider = readerParameters.MetadataImporterProvider;
			val.ReflectionImporterProvider = readerParameters.ReflectionImporterProvider;
			val.ThrowIfSymbolsAreNotMatching = readerParameters.ThrowIfSymbolsAreNotMatching;
			val.ApplyWindowsRuntimeProjections = readerParameters.ApplyWindowsRuntimeProjections;
			val.SymbolStream = readerParameters.SymbolStream;
			val.SymbolReaderProvider = readerParameters.SymbolReaderProvider;
			val.ReadSymbols = readerParameters.ReadSymbols;
			if (path != null && !File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
			{
				val.ReadSymbols = false;
			}
			return val;
		}

		public virtual void ReadMod(string path)
		{
			if (Directory.Exists(path))
			{
				Log("[ReadMod] Loading mod dir: " + path);
				string text = ((ModuleReference)Module).Name.Substring(0, ((ModuleReference)Module).Name.Length - 3);
				string value = text.Replace(" ", "");
				if (!DependencyDirs.Contains(path))
				{
					IAssemblyResolver assemblyResolver = AssemblyResolver;
					IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null);
					if (obj != null)
					{
						((BaseAssemblyResolver)obj).AddSearchDirectory(path);
					}
					DependencyDirs.Add(path);
				}
				string[] files = Directory.GetFiles(path);
				foreach (string text2 in files)
				{
					if ((Path.GetFileName(text2).StartsWith(text) || Path.GetFileName(text2).StartsWith(value)) && text2.ToLower().EndsWith(".mm.dll"))
					{
						ReadMod(text2);
					}
				}
				return;
			}
			Log("[ReadMod] Loading mod: " + path);
			ModuleDefinition val = _ReadModule(path, GenReaderParameters(mainModule: false, path));
			string directoryName = Path.GetDirectoryName(path);
			if (!DependencyDirs.Contains(directoryName))
			{
				IAssemblyResolver assemblyResolver2 = AssemblyResolver;
				IAssemblyResolver obj2 = ((assemblyResolver2 is BaseAssemblyResolver) ? assemblyResolver2 : null);
				if (obj2 != null)
				{
					((BaseAssemblyResolver)obj2).AddSearchDirectory(directoryName);
				}
				DependencyDirs.Add(directoryName);
			}
			Mods.Add((ModuleReference)(object)val);
			OnReadMod?.Invoke(this, val);
		}

		public virtual void ReadMod(Stream stream)
		{
			Log($"[ReadMod] Loading mod: stream#{(uint)stream.GetHashCode()}");
			ModuleDefinition val = _ReadModule(stream, GenReaderParameters(mainModule: false));
			Mods.Add((ModuleReference)(object)val);
			OnReadMod?.Invoke(this, val);
		}

		public virtual void ParseRules(ModuleDefinition mod)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			TypeDefinition type = mod.GetType("MonoMod.MonoModRules");
			Type rulesTypeMMILRT = null;
			if (type != null)
			{
				rulesTypeMMILRT = this.ExecuteRules(type);
				mod.Types.Remove(type);
			}
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					ParseRulesInType(current, rulesTypeMMILRT);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void ParseRulesInType(TypeDefinition type, Type rulesTypeMMILRT = null)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_0377: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_0431: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			Extensions.GetPatchFullName((MemberReference)(object)type);
			if (!MatchingConditionals((ICustomAttributeProvider)(object)type, Module))
			{
				return;
			}
			CustomAttribute customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomAttributeAttribute");
			CustomAttributeArgument val;
			if (customAttribute != null)
			{
				val = customAttribute.ConstructorArguments[0];
				MethodInfo method2 = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value);
				CustomAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
				{
					method2.Invoke(self, args);
				};
			}
			customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomMethodAttributeAttribute");
			if (customAttribute != null)
			{
				val = customAttribute.ConstructorArguments[0];
				MethodInfo method = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value);
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length == 2 && Extensions.IsCompatible(parameters[0].ParameterType, typeof(ILContext)))
				{
					CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
					{
						//IL_0024: Unknown result type (might be due to invalid IL or missing references)
						//IL_002e: Expected O, but got Unknown
						//IL_0029: Unknown result type (might be due to invalid IL or missing references)
						//IL_0033: Expected O, but got Unknown
						//IL_0040: Unknown result type (might be due to invalid IL or missing references)
						//IL_004a: Expected O, but got Unknown
						ILContext il = new ILContext((MethodDefinition)args[0]);
						il.Invoke((Manipulator)delegate
						{
							method.Invoke(self, new object[2]
							{
								il,
								args[1]
							});
						});
						if (il.IsReadOnly)
						{
							il.Dispose();
						}
					};
				}
				else
				{
					CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args)
					{
						method.Invoke(self, args);
					};
				}
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModHook"))
			{
				ParseLinkFrom((MemberReference)(object)type, val2);
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
			{
				ParseLinkFrom((MemberReference)(object)type, val2);
			}
			for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
			{
				ParseLinkTo((MemberReference)(object)type, val2);
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore"))
			{
				return;
			}
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current, val2);
						}
						if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCall"))
						{
							ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Call;
						}
						else if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCallvirt"))
						{
							ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Callvirt;
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<FieldDefinition> enumerator2 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					FieldDefinition current2 = enumerator2.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current2, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current2, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current2, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current2, val2);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<PropertyDefinition> enumerator3 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					PropertyDefinition current3 = enumerator3.Current;
					if (MatchingConditionals((ICustomAttributeProvider)(object)current3, Module))
					{
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModHook"))
						{
							ParseLinkFrom((MemberReference)(object)current3, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkFrom"))
						{
							ParseLinkFrom((MemberReference)(object)current3, val2);
						}
						for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkTo"))
						{
							ParseLinkTo((MemberReference)(object)current3, val2);
						}
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<TypeDefinition> enumerator4 = type.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					TypeDefinition current4 = enumerator4.Current;
					ParseRulesInType(current4, rulesTypeMMILRT);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
		}

		public virtual void ParseLinkFrom(MemberReference target, CustomAttribute hook)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			CustomAttributeArgument val = hook.ConstructorArguments[0];
			string key = (string)((CustomAttributeArgument)(ref val)).Value;
			object value;
			if (target is TypeReference)
			{
				value = Extensions.GetPatchFullName((MemberReference)(TypeReference)target);
			}
			else if (target is MethodReference)
			{
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(MethodReference)target).DeclaringType), Extensions.GetID((MethodReference)target, (string)null, (string)null, false, false));
			}
			else if (target is FieldReference)
			{
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(FieldReference)target).DeclaringType), ((MemberReference)(FieldReference)target).Name);
			}
			else
			{
				if (!(target is PropertyReference))
				{
					return;
				}
				value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(PropertyReference)target).DeclaringType), ((MemberReference)(PropertyReference)target).Name);
			}
			RelinkMap[key] = value;
		}

		public virtual void ParseLinkTo(MemberReference from, CustomAttribute hook)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			MemberReference obj = ((from is MethodReference) ? from : null);
			string key = ((obj != null) ? Extensions.GetID((MethodReference)(object)obj, (string)null, (string)null, true, false) : null) ?? Extensions.GetPatchFullName(from);
			CustomAttributeArgument val;
			if (hook.ConstructorArguments.Count == 1)
			{
				Dictionary<string, object> relinkMap = RelinkMap;
				val = hook.ConstructorArguments[0];
				relinkMap[key] = (string)((CustomAttributeArgument)(ref val)).Value;
			}
			else
			{
				Dictionary<string, object> relinkMap2 = RelinkMap;
				val = hook.ConstructorArguments[0];
				string type = (string)((CustomAttributeArgument)(ref val)).Value;
				val = hook.ConstructorArguments[1];
				relinkMap2[key] = new RelinkMapEntry(type, (string)((CustomAttributeArgument)(ref val)).Value);
			}
		}

		public virtual void RunCustomAttributeHandlers(ICustomAttributeProvider cap)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			if (!cap.HasCustomAttributes)
			{
				return;
			}
			CustomAttribute[] array = cap.CustomAttributes.ToArray();
			foreach (CustomAttribute val in array)
			{
				if (CustomAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out var value))
				{
					value?.Invoke(null, new object[2] { cap, val });
				}
				if (cap is MethodReference && CustomMethodAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out value))
				{
					value?.Invoke(null, new object[2]
					{
						(object)(MethodDefinition)cap,
						val
					});
				}
			}
		}

		public virtual void AutoPatch()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: 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
			Log("[AutoPatch] Parsing rules in loaded mods");
			foreach (ModuleDefinition mod4 in Mods)
			{
				ModuleDefinition mod = mod4;
				ParseRules(mod);
			}
			Log("[AutoPatch] PrePatch pass");
			foreach (ModuleDefinition mod5 in Mods)
			{
				ModuleDefinition mod2 = mod5;
				PrePatchModule(mod2);
			}
			Log("[AutoPatch] Patch pass");
			foreach (ModuleDefinition mod6 in Mods)
			{
				ModuleDefinition mod3 = mod6;
				PatchModule(mod3);
			}
			Log("[AutoPatch] PatchRefs pass");
			PatchRefs();
			if (PostProcessors != null)
			{
				Delegate[] invocationList = PostProcessors.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Log($"[PostProcessor] PostProcessor pass #{i + 1}");
					((PostProcessor)invocationList[i])?.Invoke(this);
				}
			}
		}

		public virtual IMetadataTokenProvider Relinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return PostRelinker(MainRelinker(mtp, context) ?? mtp, context) ?? throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context);
			}
			catch (Exception ex)
			{
				throw new RelinkFailedException((string)null, ex, mtp, (IMetadataTokenProvider)(object)context);
			}
		}

		public virtual IMetadataTokenProvider MainRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			TypeReference val = (TypeReference)(object)((mtp is TypeReference) ? mtp : null);
			if (val != null)
			{
				if (((MemberReference)val).Module == Module)
				{
					return (IMetadataTokenProvider)(object)val;
				}
				if (((MemberReference)val).Module != null && !Mods.Contains((ModuleReference)(object)((MemberReference)val).Module))
				{
					return (IMetadataTokenProvider)(object)Module.ImportReference(val);
				}
				val = (TypeReference)(((object)Extensions.SafeResolve(val)) ?? ((object)val));
				TypeReference val2 = FindTypeDeep(Extensions.GetPatchFullName((MemberReference)(object)val));
				if (val2 == null)
				{
					if (RelinkMap.ContainsKey(((MemberReference)val).FullName))
					{
						return null;
					}
					throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context);
				}
				return (IMetadataTokenProvider)(object)Module.ImportReference(val2);
			}
			if (mtp is FieldReference || mtp is MethodReference || mtp is PropertyReference || mtp is EventReference)
			{
				return Extensions.ImportReference(Module, mtp);
			}
			throw new InvalidOperationException($"MonoMod default relinker can't handle metadata token providers of the type {((object)mtp).GetType()}");
		}

		public virtual IMetadataTokenProvider PostRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context)
		{
			return ResolveRelinkTarget(mtp) ?? mtp;
		}

		public virtual IMetadataTokenProvider ResolveRelinkTarget(IMetadataTokenProvider mtp, bool relink = true, bool relinkModule = true)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0031: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_027b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Expected O, but got Unknown
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_0237: Expected O, but got Unknown
			//IL_023c: Expected O, but got Unknown
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			string text = null;
			string text2;
			if (mtp is TypeReference)
			{
				text2 = ((MemberReference)(TypeReference)mtp).FullName;
			}
			else if (mtp is MethodReference)
			{
				text2 = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, false);
				text = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, true);
			}
			else if (mtp is FieldReference)
			{
				text2 = ((MemberReference)(FieldReference)mtp).FullName;
			}
			else
			{
				if (!(mtp is PropertyReference))
				{
					return null;
				}
				text2 = ((MemberReference)(PropertyReference)mtp).FullName;
			}
			if (RelinkMapCache.TryGetValue(text2, out var value))
			{
				return value;
			}
			if (relink && (RelinkMap.TryGetValue(text2, out var value2) || (text != null && RelinkMap.TryGetValue(text, out value2))))
			{
				if (value2 is IMetadataTokenProvider)
				{
					return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2);
				}
				if (value2 is RelinkMapEntry)
				{
					string type = ((RelinkMapEntry)value2).Type;
					string findableID = ((RelinkMapEntry)value2).FindableID;
					TypeReference obj = FindTypeDeep(type);
					TypeDefinition val2 = ((obj != null) ? Extensions.SafeResolve(obj) : null);
					if (val2 == null)
					{
						return RelinkMapCache[text2] = ResolveRelinkTarget(mtp, relink: false, relinkModule);
					}
					value2 = Extensions.FindMethod(val2, findableID, true) ?? ((object)Extensions.FindField(val2, findableID)) ?? ((object)(Extensions.FindProperty(val2, findableID) ?? null));
					if (value2 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} ({1}, {2}) (remap: {3})", "MonoMod relinker failed finding", type, findableID, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2);
				}
				if (value2 is string && mtp is TypeReference)
				{
					IMetadataTokenProvider val5 = (IMetadataTokenProvider)(object)FindTypeDeep((string)value2);
					if (val5 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", value2, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					value2 = Extensions.ImportReference(Module, ResolveRelinkTarget(val5, relink: false, relinkModule) ?? val5);
				}
				if (value2 is IMetadataTokenProvider)
				{
					Dictionary<string, IMetadataTokenProvider> relinkMapCache = RelinkMapCache;
					string key = text2;
					IMetadataTokenProvider val6 = (IMetadataTokenProvider)value2;
					IMetadataTokenProvider result = val6;
					relinkMapCache[key] = val6;
					return result;
				}
				throw new InvalidOperationException($"MonoMod doesn't support RelinkMap value of type {value2.GetType()} (remap: {mtp})");
			}
			if (relinkModule && mtp is TypeReference)
			{
				if (RelinkModuleMapCache.TryGetValue(text2, out var value3))
				{
					return (IMetadataTokenProvider)(object)value3;
				}
				value3 = (TypeReference)mtp;
				if (RelinkModuleMap.TryGetValue(value3.Scope.Name, out var value4))
				{
					TypeReference type2 = (TypeReference)(object)value4.GetType(((MemberReference)value3).FullName);
					if (type2 == null)
					{
						if (Strict)
						{
							throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", ((MemberReference)value3).FullName, mtp), mtp, (IMetadataTokenProvider)null);
						}
						return null;
					}
					return (IMetadataTokenProvider)(object)(RelinkModuleMapCache[text2] = Module.ImportReference(type2));
				}
				return (IMetadataTokenProvider)(object)Module.ImportReference(value3);
			}
			return null;
		}

		public virtual bool DefaultParser(MonoModder mod, MethodBody body, Instruction instr, ref int instri)
		{
			return true;
		}

		public virtual TypeReference FindType(string name)
		{
			return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, false);
		}

		public virtual TypeReference FindType(string name, bool runtimeName)
		{
			return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, runtimeName);
		}

		protected virtual TypeReference FindType(ModuleDefinition main, string fullName, Stack<ModuleDefinition> crawled)
		{
			TypeReference type;
			if ((type = main.GetType(fullName, false)) != null)
			{
				return type;
			}
			if (fullName.StartsWith("<PrivateImplementationDetails>/"))
			{
				return null;
			}
			if (crawled.Contains(main))
			{
				return null;
			}
			crawled.Push(main);
			foreach (ModuleDefinition item in DependencyMap[main])
			{
				if ((!RemovePatchReferences || !((AssemblyNameReference)item.Assembly.Name).Name.EndsWith(".mm")) && (type = FindType(item, fullName, crawled)) != null)
				{
					return type;
				}
			}
			return null;
		}

		public virtual TypeReference FindTypeDeep(string name)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			TypeReference val = FindType(name, runtimeName: false);
			if (val != null)
			{
				return val;
			}
			Stack<ModuleDefinition> crawled = new Stack<ModuleDefinition>();
			val = null;
			foreach (ModuleDefinition mod in Mods)
			{
				ModuleDefinition key = mod;
				foreach (ModuleDefinition item in DependencyMap[key])
				{
					if ((val = FindType(item, name, crawled)) != null)
					{
						IMetadataScope scope = val.Scope;
						AssemblyNameReference dllRef = (AssemblyNameReference)(object)((scope is AssemblyNameReference) ? scope : null);
						if (dllRef != null && !((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference n) => n.Name == dllRef.Name))
						{
							Module.AssemblyReferences.Add(dllRef);
						}
						return Module.ImportReference(val);
					}
				}
			}
			return null;
		}

		public virtual void PrePatchModule(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PrePatchType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<ModuleReference> enumerator2 = mod.ModuleReferences.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					ModuleReference current2 = enumerator2.Current;
					if (!Module.ModuleReferences.Contains(current2))
					{
						Module.ModuleReferences.Add(current2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<Resource> enumerator3 = mod.Resources.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					Resource current3 = enumerator3.Current;
					if (current3 is EmbeddedResource)
					{
						Module.Resources.Add((Resource)new EmbeddedResource(current3.Name.StartsWith(((AssemblyNameReference)mod.Assembly.Name).Name) ? (((AssemblyNameReference)Module.Assembly.Name).Name + current3.Name.Substring(((AssemblyNameReference)mod.Assembly.Name).Name.Length)) : current3.Name, current3.Attributes, ((EmbeddedResource)current3).GetResourceData()));
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
		}

		public virtual void PrePatchType(TypeDefinition type, bool forceAdd = false)
		{
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Expected O, but got Unknown
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Expected O, but got Unknown
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type);
			if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module) || (((MemberReference)type).FullName == "MonoMod.MonoModRules" && !forceAdd))
			{
				return;
			}
			TypeReference val = (forceAdd ? null : Module.GetType(patchFullName, false));
			TypeDefinition val2 = ((val != null) ? Extensions.SafeResolve(val) : null);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModReplace") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove"))
			{
				if (val2 != null)
				{
					if (val2.DeclaringType == null)
					{
						Module.Types.Remove(val2);
					}
					else
					{
						val2.DeclaringType.NestedTypes.Remove(val2);
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			else if (val != null)
			{
				PrePatchNested(type);
				return;
			}
			LogVerbose("[PrePatchType] Adding " + patchFullName + " to the target module.");
			TypeDefinition val3 = new TypeDefinition(((TypeReference)type).Namespace, ((MemberReference)type).Name, type.Attributes, type.BaseType);
			Enumerator<GenericParameter> enumerator = ((TypeReference)type).GenericParameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					GenericParameter current = enumerator.Current;
					((TypeReference)val3).GenericParameters.Add(Extensions.Clone(current));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<InterfaceImplementation> enumerator2 = type.Interfaces.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					InterfaceImplementation current2 = enumerator2.Current;
					val3.Interfaces.Add(current2);
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			val3.ClassSize = type.ClassSize;
			if (type.DeclaringType != null)
			{
				val3.DeclaringType = Extensions.Relink((TypeReference)(object)type.DeclaringType, new Relinker(Relinker), (IGenericParameterProvider)(object)val3).Resolve();
				val3.DeclaringType.NestedTypes.Add(val3);
			}
			else
			{
				Module.Types.Add(val3);
			}
			val3.PackingSize = type.PackingSize;
			Extensions.AddRange<SecurityDeclaration>(val3.SecurityDeclarations, (IEnumerable<SecurityDeclaration>)type.SecurityDeclarations);
			val3.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
			val = (TypeReference)(object)val3;
			PrePatchNested(type);
		}

		protected virtual void PrePatchNested(TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++)
			{
				PrePatchType(type.NestedTypes[i]);
			}
		}

		public virtual void PatchModule(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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_007c: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					if ((((TypeReference)current).Namespace == "MonoMod" || ((TypeReference)current).Namespace.StartsWith("MonoMod.")) && ((MemberReference)current.BaseType).FullName == "System.Attribute")
					{
						PatchType(current);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current2 = enumerator.Current;
					if ((!(((TypeReference)current2).Namespace == "MonoMod") && !((TypeReference)current2).Namespace.StartsWith("MonoMod.")) || !(((MemberReference)current2.BaseType).FullName == "System.Attribute"))
					{
						PatchType(current2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchType(TypeDefinition type)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type);
			TypeReference type2 = Module.GetType(patchFullName, false);
			if (type2 == null)
			{
				return;
			}
			TypeDefinition val = ((type2 != null) ? Extensions.SafeResolve(type2) : null);
			Enumerator<CustomAttribute> enumerator;
			if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module))
			{
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore") && val != null)
				{
					enumerator = type.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				PatchNested(type);
				return;
			}
			if (patchFullName == ((MemberReference)type).FullName)
			{
				LogVerbose("[PatchType] Patching type " + patchFullName);
			}
			else
			{
				LogVerbose("[PatchType] Patching type " + patchFullName + " (prefixed: " + ((MemberReference)type).FullName + ")");
			}
			enumerator = type.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current2 = enumerator.Current;
					if (!Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)val, ((MemberReference)current2.AttributeType).FullName))
					{
						val.CustomAttributes.Add(Extensions.Clone(current2));
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			HashSet<MethodDefinition> hashSet = new HashSet<MethodDefinition>();
			Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					PropertyDefinition current3 = enumerator2.Current;
					PatchProperty(val, current3, hashSet);
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			HashSet<MethodDefinition> hashSet2 = new HashSet<MethodDefinition>();
			Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					EventDefinition current4 = enumerator3.Current;
					PatchEvent(val, current4, hashSet2);
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodDefinition current5 = enumerator4.Current;
					if (!hashSet.Contains(current5) && !hashSet2.Contains(current5))
					{
						PatchMethod(val, current5);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModEnumReplace"))
			{
				int num = 0;
				while (num < val.Fields.Count)
				{
					if (((MemberReference)val.Fields[num]).Name == "value__")
					{
						num++;
					}
					else
					{
						val.Fields.RemoveAt(num);
					}
				}
			}
			Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator5.MoveNext())
				{
					FieldDefinition current6 = enumerator5.Current;
					PatchField(val, current6);
				}
			}
			finally
			{
				((IDisposable)enumerator5).Dispose();
			}
			PatchNested(type);
		}

		protected virtual void PatchNested(TypeDefinition type)
		{
			for (int i = 0; i < type.NestedTypes.Count; i++)
			{
				PatchType(type.NestedTypes[i]);
			}
		}

		public virtual void PatchProperty(TypeDefinition targetType, PropertyDefinition prop, HashSet<MethodDefinition> propMethods = null)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Expected O, but got Unknown
			//IL_022b: Expected O, but got Unknown
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Expected O, but got Unknown
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: 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_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Expected O, but got Unknown
			//IL_02b5: Expected O, but got Unknown
			//IL_0363: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			if (!MatchingConditionals((ICustomAttributeProvider)(object)prop, Module))
			{
				return;
			}
			((MemberReference)prop).Name = Extensions.GetPatchName((MemberReference)(object)prop);
			PropertyDefinition val = Extensions.FindProperty(targetType, ((MemberReference)prop).Name);
			string text = "<" + ((MemberReference)prop).Name + ">__BackingField";
			FieldDefinition val2 = Extensions.FindField(prop.DeclaringType, text);
			FieldDefinition val3 = Extensions.FindField(targetType, text);
			Enumerator<CustomAttribute> enumerator;
			Enumerator<MethodDefinition> enumerator2;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModIgnore"))
			{
				if (val != null)
				{
					enumerator = prop.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (val2 != null)
				{
					val2.DeclaringType.Fields.Remove(val2);
				}
				if (prop.GetMethod != null)
				{
					propMethods?.Add(prop.GetMethod);
				}
				if (prop.SetMethod != null)
				{
					propMethods?.Add(prop.SetMethod);
				}
				enumerator2 = prop.OtherMethods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						propMethods?.Add(current2);
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModReplace"))
			{
				if (val != null)
				{
					targetType.Properties.Remove(val);
					if (val3 != null)
					{
						targetType.Fields.Remove(val3);
					}
					if (val.GetMethod != null)
					{
						targetType.Methods.Remove(val.GetMethod);
					}
					if (val.SetMethod != null)
					{
						targetType.Methods.Remove(val.SetMethod);
					}
					enumerator2 = val.OtherMethods.GetEnumerator();
					try
					{
						while (enumerator2.MoveNext())
						{
							MethodDefinition current3 = enumerator2.Current;
							targetType.Methods.Remove(current3);
						}
					}
					finally
					{
						((IDisposable)enumerator2).Dispose();
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			if (val == null)
			{
				PropertyDefinition val4 = new PropertyDefinition(((MemberReference)prop).Name, prop.Attributes, ((PropertyReference)prop).PropertyType);
				val = val4;
				PropertyDefinition val5 = val4;
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				Enumerator<ParameterDefinition> enumerator3 = ((PropertyReference)prop).Parameters.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						ParameterDefinition current4 = enumerator3.Current;
						((PropertyReference)val5).Parameters.Add(Extensions.Clone(current4));
					}
				}
				finally
				{
					((IDisposable)enumerator3).Dispose();
				}
				val5.DeclaringType = targetType;
				targetType.Properties.Add(val5);
				if (val2 != null)
				{
					FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType);
					val3 = val6;
					FieldDefinition val7 = val6;
					targetType.Fields.Add(val7);
				}
			}
			enumerator = prop.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current5 = enumerator.Current;
					val.CustomAttributes.Add(Extensions.Clone(current5));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodDefinition getMethod = prop.GetMethod;
			MethodDefinition getMethod2;
			if (getMethod != null && (getMethod2 = PatchMethod(targetType, getMethod)) != null)
			{
				val.GetMethod = getMethod2;
				propMethods?.Add(getMethod);
			}
			MethodDefinition setMethod = prop.SetMethod;
			if (setMethod != null && (getMethod2 = PatchMethod(targetType, setMethod)) != null)
			{
				val.SetMethod = getMethod2;
				propMethods?.Add(setMethod);
			}
			enumerator2 = prop.OtherMethods.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					MethodDefinition current6 = enumerator2.Current;
					if ((getMethod2 = PatchMethod(targetType, current6)) != null)
					{
						val.OtherMethods.Add(getMethod2);
						propMethods?.Add(current6);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
		}

		public virtual void PatchEvent(TypeDefinition targetType, EventDefinition srcEvent, HashSet<MethodDefinition> propMethods = null)
		{
			//IL_005e: 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)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Expected O, but got Unknown
			//IL_0252: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Expected O, but got Unknown
			//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)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			((MemberReference)srcEvent).Name = Extensions.GetPatchName((MemberReference)(object)srcEvent);
			EventDefinition val = Extensions.FindEvent(targetType, ((MemberReference)srcEvent).Name);
			string text = "<" + ((MemberReference)srcEvent).Name + ">__BackingField";
			FieldDefinition val2 = Extensions.FindField(srcEvent.DeclaringType, text);
			FieldDefinition val3 = Extensions.FindField(targetType, text);
			Enumerator<CustomAttribute> enumerator;
			Enumerator<MethodDefinition> enumerator2;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModIgnore"))
			{
				if (val != null)
				{
					enumerator = srcEvent.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				if (val2 != null)
				{
					val2.DeclaringType.Fields.Remove(val2);
				}
				if (srcEvent.AddMethod != null)
				{
					propMethods?.Add(srcEvent.AddMethod);
				}
				if (srcEvent.RemoveMethod != null)
				{
					propMethods?.Add(srcEvent.RemoveMethod);
				}
				if (srcEvent.InvokeMethod != null)
				{
					propMethods?.Add(srcEvent.InvokeMethod);
				}
				enumerator2 = srcEvent.OtherMethods.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodDefinition current2 = enumerator2.Current;
						propMethods?.Add(current2);
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModReplace"))
			{
				if (val != null)
				{
					targetType.Events.Remove(val);
					if (val3 != null)
					{
						targetType.Fields.Remove(val3);
					}
					if (val.AddMethod != null)
					{
						targetType.Methods.Remove(val.AddMethod);
					}
					if (val.RemoveMethod != null)
					{
						targetType.Methods.Remove(val.RemoveMethod);
					}
					if (val.InvokeMethod != null)
					{
						targetType.Methods.Remove(val.InvokeMethod);
					}
					if (val.OtherMethods != null)
					{
						enumerator2 = val.OtherMethods.GetEnumerator();
						try
						{
							while (enumerator2.MoveNext())
							{
								MethodDefinition current3 = enumerator2.Current;
								targetType.Methods.Remove(current3);
							}
						}
						finally
						{
							((IDisposable)enumerator2).Dispose();
						}
					}
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			if (val == null)
			{
				EventDefinition val4 = new EventDefinition(((MemberReference)srcEvent).Name, srcEvent.Attributes, ((EventReference)srcEvent).EventType);
				val = val4;
				EventDefinition val5 = val4;
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				val5.DeclaringType = targetType;
				targetType.Events.Add(val5);
				if (val2 != null)
				{
					FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType);
					targetType.Fields.Add(val6);
				}
			}
			enumerator = srcEvent.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current4 = enumerator.Current;
					val.CustomAttributes.Add(Extensions.Clone(current4));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			MethodDefinition addMethod = srcEvent.AddMethod;
			MethodDefinition addMethod2;
			if (addMethod != null && (addMethod2 = PatchMethod(targetType, addMethod)) != null)
			{
				val.AddMethod = addMethod2;
				propMethods?.Add(addMethod);
			}
			MethodDefinition removeMethod = srcEvent.RemoveMethod;
			if (removeMethod != null && (addMethod2 = PatchMethod(targetType, removeMethod)) != null)
			{
				val.RemoveMethod = addMethod2;
				propMethods?.Add(removeMethod);
			}
			MethodDefinition invokeMethod = srcEvent.InvokeMethod;
			if (invokeMethod != null && (addMethod2 = PatchMethod(targetType, invokeMethod)) != null)
			{
				val.InvokeMethod = addMethod2;
				propMethods?.Add(invokeMethod);
			}
			enumerator2 = srcEvent.OtherMethods.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					MethodDefinition current5 = enumerator2.Current;
					if ((addMethod2 = PatchMethod(targetType, current5)) != null)
					{
						val.OtherMethods.Add(addMethod2);
						propMethods?.Add(current5);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
		}

		public virtual void PatchField(TypeDefinition targetType, FieldDefinition field)
		{
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Expected O, but got Unknown
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)field.DeclaringType);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModNoNew") || SkipList.Contains(patchFullName + "::" + ((MemberReference)field).Name) || !MatchingConditionals((ICustomAttributeProvider)(object)field, Module))
			{
				return;
			}
			((MemberReference)field).Name = Extensions.GetPatchName((MemberReference)(object)field);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModReplace"))
			{
				FieldDefinition val = Extensions.FindField(targetType, ((MemberReference)field).Name);
				if (val != null)
				{
					targetType.Fields.Remove(val);
				}
				if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove"))
				{
					return;
				}
			}
			FieldDefinition val2 = Extensions.FindField(targetType, ((MemberReference)field).Name);
			Enumerator<CustomAttribute> enumerator;
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModIgnore") && val2 != null)
			{
				enumerator = field.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
						{
							val2.CustomAttributes.Add(Extensions.Clone(current));
						}
					}
					return;
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
			}
			if (val2 == null)
			{
				val2 = new FieldDefinition(((MemberReference)field).Name, field.Attributes, ((FieldReference)field).FieldType);
				val2.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				val2.InitialValue = field.InitialValue;
				if (field.HasConstant)
				{
					val2.Constant = field.Constant;
				}
				targetType.Fields.Add(val2);
			}
			enumerator = field.CustomAttributes.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					CustomAttribute current2 = enumerator.Current;
					val2.CustomAttributes.Add(Extensions.Clone(current2));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual MethodDefinition PatchMethod(TypeDefinition targetType, MethodDefinition method)
		{
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_049f: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bb: Expected O, but got Unknown
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0504: Unknown result type (might be due to invalid IL or missing references)
			//IL_0511: Unknown result type (might be due to invalid IL or missing references)
			//IL_0564: Unknown result type (might be due to invalid IL or missing references)
			//IL_0569: Unknown result type (might be due to invalid IL or missing references)
			//IL_0453: Unknown result type (might be due to invalid IL or missing references)
			//IL_0458: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d8: Expected O, but got Unknown
			//IL_05a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_069a: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a1: Expected O, but got Unknown
			//IL_06be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0630: Unknown result type (might be due to invalid IL or missing references)
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_0676: Unknown result type (might be due to invalid IL or missing references)
			//IL_0680: Expected O, but got Unknown
			if (((MemberReference)method).Name.StartsWith("orig_") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginal"))
			{
				return null;
			}
			if (!AllowedSpecialName(method, targetType) || !MatchingConditionals((ICustomAttributeProvider)(object)method, Module))
			{
				return null;
			}
			string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)targetType);
			if (SkipList.Contains(Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false)))
			{
				return null;
			}
			((MemberReference)method).Name = Extensions.GetPatchName((MemberReference)(object)method);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor"))
			{
				if (!method.IsSpecialName && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginalName"))
				{
					CustomAttribute val = new CustomAttribute(GetMonoModOriginalNameCtor());
					val.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)("orig_" + ((MemberReference)method).Name)));
					method.CustomAttributes.Add(val);
				}
				((MemberReference)method).Name = (method.IsStatic ? ".cctor" : ".ctor");
				method.IsSpecialName = true;
				method.IsRuntimeSpecialName = true;
			}
			MethodDefinition val2 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false), true);
			MethodDefinition obj = method;
			string text = patchFullName;
			MethodDefinition val3 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)obj, method.GetOriginalName(), text, true, false), true);
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModIgnore"))
			{
				if (val2 != null)
				{
					Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName))
							{
								val2.CustomAttributes.Add(Extensions.Clone(current));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				return null;
			}
			if (val2 == null && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModNoNew"))
			{
				return null;
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModRemove"))
			{
				if (val2 != null)
				{
					targetType.Methods.Remove(val2);
				}
				return null;
			}
			if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModReplace"))
			{
				if (val2 != null)
				{
					val2.CustomAttributes.Clear();
					val2.Attributes = method.Attributes;
					val2.IsPInvokeImpl = method.IsPInvokeImpl;
					val2.ImplAttributes = method.ImplAttributes;
				}
			}
			else if (val2 != null && val3 == null)
			{
				val3 = Extensions.Clone(val2, (MethodDefinition)null);
				((MemberReference)val3).Name = method.GetOriginalName();
				val3.Attributes = (MethodAttributes)(val2.Attributes & 0xF7FF & 0xEFFF);
				((MemberReference)val3).MetadataToken = GetMetadataToken((TokenType)100663296);
				val3.IsVirtual = false;
				val3.Overrides.Clear();
				Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodReference current2 = enumerator2.Current;
						val3.Overrides.Add(current2);
					}
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
				val3.CustomAttributes.Add(new CustomAttribute(GetMonoModOriginalCtor()));
				MethodDefinition val4 = Extensions.FindMethod(method.DeclaringType, Extensions.GetID((MethodReference)(object)method, method.GetOriginalName(), (string)null, true, false), true);
				if (val4 != null)
				{
					Enumerator<CustomAttribute> enumerator = val4.CustomAttributes.GetEnumerator();
					try
					{
						while (enumerator.MoveNext())
						{
							CustomAttribute current3 = enumerator.Current;
							if (CustomAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName))
							{
								val3.CustomAttributes.Add(Extensions.Clone(current3));
							}
						}
					}
					finally
					{
						((IDisposable)enumerator).Dispose();
					}
				}
				targetType.Methods.Add(val3);
			}
			if (val3 != null && method.IsConstructor && method.IsStatic && method.HasBody && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor"))
			{
				Collection<Instruction> instructions = method.Body.Instructions;
				ILProcessor iLProcessor = method.Body.GetILProcessor();
				iLProcessor.InsertBefore(instructions[instructions.Count - 1], iLProcessor.Create(OpCodes.Call, (MethodReference)(object)val3));
			}
			if (val2 != null)
			{
				val2.Body = Extensions.Clone(method.Body, val2);
				val2.IsManaged = method.IsManaged;
				val2.IsIL = method.IsIL;
				val2.IsNative = method.IsNative;
				val2.PInvokeInfo = method.PInvokeInfo;
				val2.IsPreserveSig = method.IsPreserveSig;
				val2.IsInternalCall = method.IsInternalCall;
				val2.IsPInvokeImpl = method.IsPInvokeImpl;
				Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current4 = enumerator.Current;
						val2.CustomAttributes.Add(Extensions.Clone(current4));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				method = val2;
			}
			else
			{
				MethodDefinition val5 = new MethodDefinition(((MemberReference)method).Name, method.Attributes, Module.TypeSystem.Void);
				((MemberReference)val5).MetadataToken = GetMetadataToken((TokenType)100663296);
				((MethodReference)val5).CallingConvention = ((MethodReference)method).CallingConvention;
				((MethodReference)val5).ExplicitThis = ((MethodReference)method).ExplicitThis;
				((MethodReference)val5).MethodReturnType = ((MethodReference)method).MethodReturnType;
				val5.Attributes = method.Attributes;
				val5.ImplAttributes = method.ImplAttributes;
				val5.SemanticsAttributes = method.SemanticsAttributes;
				val5.DeclaringType = targetType;
				((MethodReference)val5).ReturnType = ((MethodReference)method).ReturnType;
				val5.Body = Extensions.Clone(method.Body, val5);
				val5.PInvokeInfo = method.PInvokeInfo;
				val5.IsPInvokeImpl = method.IsPInvokeImpl;
				Enumerator<GenericParameter> enumerator3 = ((MethodReference)method).GenericParameters.GetEnumerator();
				try
				{
					while (enumerator3.MoveNext())
					{
						GenericParameter current5 = enumerator3.Current;
						((MethodReference)val5).GenericParameters.Add(Extensions.Clone(current5));
					}
				}
				finally
				{
					((IDisposable)enumerator3).Dispose();
				}
				Enumerator<ParameterDefinition> enumerator4 = ((MethodReference)method).Parameters.GetEnumerator();
				try
				{
					while (enumerator4.MoveNext())
					{
						ParameterDefinition current6 = enumerator4.Current;
						((MethodReference)val5).Parameters.Add(Extensions.Clone(current6));
					}
				}
				finally
				{
					((IDisposable)enumerator4).Dispose();
				}
				Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current7 = enumerator.Current;
						val5.CustomAttributes.Add(Extensions.Clone(current7));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator();
				try
				{
					while (enumerator2.MoveNext())
					{
						MethodReference current8 = enumerator2.Current;
						val5.Overrides.Add(current8);
					}
				}
				finally
				{
					((IDisposable)enumerator2).Dispose();
				}
				val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor()));
				targetType.Methods.Add(val5);
				method = val5;
			}
			if (val3 != null)
			{
				CustomAttribute val6 = new CustomAttribute(GetMonoModOriginalNameCtor());
				val6.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)((MemberReference)val3).Name));
				method.CustomAttributes.Add(val6);
			}
			return method;
		}

		public virtual void PatchRefs()
		{
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			if (!UpgradeMSCORLIB.HasValue)
			{
				Version fckUnity = new Version(2, 0, 5, 0);
				UpgradeMSCORLIB = ((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference x) => x.Version == fckUnity);
			}
			if (UpgradeMSCORLIB.Value)
			{
				List<AssemblyNameReference> list = new List<AssemblyNameReference>();
				for (int i = 0; i < Module.AssemblyReferences.Count; i++)
				{
					AssemblyNameReference val = Module.AssemblyReferences[i];
					if (val.Name == "mscorlib")
					{
						list.Add(val);
					}
				}
				if (list.Count > 1)
				{
					AssemblyNameReference val2 = list.OrderByDescending((AssemblyNameReference x) => x.Version).First();
					if (DependencyCache.TryGetValue(val2.FullName, out var value))
					{
						for (int j = 0; j < Module.AssemblyReferences.Count; j++)
						{
							AssemblyNameReference val3 = Module.AssemblyReferences[j];
							if (val3.Name == "mscorlib" && val2.Version > val3.Version)
							{
								LogVerbose("[PatchRefs] Removing and relinking duplicate mscorlib: " + val3.Version);
								RelinkModuleMap[val3.FullName] = value;
								Module.AssemblyReferences.RemoveAt(j);
								j--;
							}
						}
					}
				}
			}
			Enumerator<TypeDefinition> enumerator = Module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PatchRefsInType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchRefs(ModuleDefinition mod)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					PatchRefsInType(current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public virtual void PatchRefsInType(TypeDefinition type)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: 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_0149: Expected O, but got Unknown
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Expected O, but got Unknown
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Expected O, but got Unknown
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Expected O, but got Unknown
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Expected O, but got Unknown
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_02df: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Expected O, but got Unknown
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Expected O, but got Unknown
			LogVerbose($"[VERBOSE] [PatchRefsInType] Patching refs in {type}");
			if (type.BaseType != null)
			{
				type.BaseType = Extensions.Relink(type.BaseType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			for (int i = 0; i < ((TypeReference)type).GenericParameters.Count; i++)
			{
				((TypeReference)type).GenericParameters[i] = Extensions.Relink(((TypeReference)type).GenericParameters[i], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			for (int j = 0; j < type.Interfaces.Count; j++)
			{
				InterfaceImplementation obj = type.Interfaces[j];
				InterfaceImplementation val = new InterfaceImplementation(Extensions.Relink(obj.InterfaceType, new Relinker(Relinker), (IGenericParameterProvider)(object)type));
				Enumerator<CustomAttribute> enumerator = obj.CustomAttributes.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						CustomAttribute current = enumerator.Current;
						val.CustomAttributes.Add(Extensions.Relink(current, new Relinker(Relinker), (IGenericParameterProvider)(object)type));
					}
				}
				finally
				{
					((IDisposable)enumerator).Dispose();
				}
				type.Interfaces[j] = val;
			}
			for (int k = 0; k < type.CustomAttributes.Count; k++)
			{
				type.CustomAttributes[k] = Extensions.Relink(type.CustomAttributes[k], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
			}
			Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					PropertyDefinition current2 = enumerator2.Current;
					((PropertyReference)current2).PropertyType = Extensions.Relink(((PropertyReference)current2).PropertyType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int l = 0; l < current2.CustomAttributes.Count; l++)
					{
						current2.CustomAttributes[l] = Extensions.Relink(current2.CustomAttributes[l], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator();
			try
			{
				while (enumerator3.MoveNext())
				{
					EventDefinition current3 = enumerator3.Current;
					((EventReference)current3).EventType = Extensions.Relink(((EventReference)current3).EventType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int m = 0; m < current3.CustomAttributes.Count; m++)
					{
						current3.CustomAttributes[m] = Extensions.Relink(current3.CustomAttributes[m], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator3).Dispose();
			}
			Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator();
			try
			{
				while (enumerator4.MoveNext())
				{
					MethodDefinition current4 = enumerator4.Current;
					PatchRefsInMethod(current4);
				}
			}
			finally
			{
				((IDisposable)enumerator4).Dispose();
			}
			Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator();
			try
			{
				while (enumerator5.MoveNext())
				{
					FieldDefinition current5 = enumerator5.Current;
					((FieldReference)current5).FieldType = Extensions.Relink(((FieldReference)current5).FieldType, new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					for (int n = 0; n < current5.CustomAttributes.Count; n++)
					{
						current5.CustomAttributes[n] = Extensions.Relink(current5.CustomAttributes[n], new Relinker(Relinker), (IGenericParameterProvider)(object)type);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator5).Dispose();
			}
			for (int num = 0; num < type.NestedTypes.Count; num++)
			{
				PatchRefsInType(type.NestedTypes[num]);
			}
		}

		public virtual void PatchRefsInMethod(MethodDefinition method)
		{
			//IL_0030: Unknown result t

FrozenDevv-ModPack-1.1.0/BepInEx/patchers/BepInEx.MonoMod.HookGenPatcher/MonoMod.RuntimeDetour.HookGen.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Utils;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("0x0ade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2021 0x0ade")]
[assembly: AssemblyDescription("Auto-generate hook helper .dlls, hook arbitrary methods via events: On.Namespace.Type.Method += YourHandlerHere;")]
[assembly: AssemblyFileVersion("21.8.5.1")]
[assembly: AssemblyInformationalVersion("21.08.05.01")]
[assembly: AssemblyProduct("MonoMod.RuntimeDetour.HookGen")]
[assembly: AssemblyTitle("MonoMod.RuntimeDetour.HookGen")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("21.8.5.1")]
[module: UnverifiableCode]
internal static class MultiTargetShims
{
	private static readonly object[] _NoArgs = new object[0];

	public static TypeReference GetConstraintType(this TypeReference type)
	{
		return type;
	}
}
namespace MonoMod
{
	internal static class MMDbgLog
	{
		public static readonly string Tag;

		public static TextWriter Writer;

		public static bool Debugging;

		static MMDbgLog()
		{
			Tag = typeof(MMDbgLog).Assembly.GetName().Name;
			if (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1" || (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG")?.ToLowerInvariant()?.Contains(Tag.ToLowerInvariant())).GetValueOrDefault())
			{
				Start();
			}
		}

		public static void WaitForDebugger()
		{
			if (!Debugging)
			{
				Debugging = true;
				Debugger.Launch();
				Thread.Sleep(6000);
				Debugger.Break();
			}
		}

		public static void Start()
		{
			if (Writer != null)
			{
				return;
			}
			string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH");
			if (text == "-")
			{
				Writer = Console.Out;
				return;
			}
			if (string.IsNullOrEmpty(text))
			{
				text = "mmdbglog.txt";
			}
			text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text));
			try
			{
				if (File.Exists(text))
				{
					File.Delete(text);
				}
			}
			catch
			{
			}
			try
			{
				string directoryName = Path.GetDirectoryName(text);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8);
			}
			catch
			{
			}
		}

		public static void Log(string str)
		{
			TextWriter writer = Writer;
			if (writer != null)
			{
				writer.WriteLine(str);
				writer.Flush();
			}
		}

		public static T Log<T>(string str, T value)
		{
			TextWriter writer = Writer;
			if (writer == null)
			{
				return value;
			}
			writer.WriteLine(string.Format(str, value));
			writer.Flush();
			return value;
		}
	}
}
namespace MonoMod.RuntimeDetour.HookGen
{
	public class HookGenerator
	{
		private const string ObsoleteMessageBackCompat = "This method only exists for backwards-compatibility purposes.";

		private static readonly Regex NameVerifyRegex;

		private static readonly Dictionary<Type, string> ReflTypeNameMap;

		private static readonly Dictionary<string, string> TypeNameMap;

		public MonoModder Modder;

		public ModuleDefinition OutputModule;

		public string Namespace;

		public string NamespaceIL;

		public bool HookOrig;

		public bool HookPrivate;

		public string HookExtName;

		public ModuleDefinition module_RuntimeDetour;

		public ModuleDefinition module_Utils;

		public TypeReference t_MulticastDelegate;

		public TypeReference t_IAsyncResult;

		public TypeReference t_AsyncCallback;

		public TypeReference t_MethodBase;

		public TypeReference t_RuntimeMethodHandle;

		public TypeReference t_EditorBrowsableState;

		public MethodReference m_Object_ctor;

		public MethodReference m_ObsoleteAttribute_ctor;

		public MethodReference m_EditorBrowsableAttribute_ctor;

		public MethodReference m_GetMethodFromHandle;

		public MethodReference m_Add;

		public MethodReference m_Remove;

		public MethodReference m_Modify;

		public MethodReference m_Unmodify;

		public TypeReference t_ILManipulator;

		static HookGenerator()
		{
			NameVerifyRegex = new Regex("[^a-zA-Z]");
			ReflTypeNameMap = new Dictionary<Type, string>
			{
				{
					typeof(string),
					"string"
				},
				{
					typeof(object),
					"object"
				},
				{
					typeof(bool),
					"bool"
				},
				{
					typeof(byte),
					"byte"
				},
				{
					typeof(char),
					"char"
				},
				{
					typeof(decimal),
					"decimal"
				},
				{
					typeof(double),
					"double"
				},
				{
					typeof(short),
					"short"
				},
				{
					typeof(int),
					"int"
				},
				{
					typeof(long),
					"long"
				},
				{
					typeof(sbyte),
					"sbyte"
				},
				{
					typeof(float),
					"float"
				},
				{
					typeof(ushort),
					"ushort"
				},
				{
					typeof(uint),
					"uint"
				},
				{
					typeof(ulong),
					"ulong"
				},
				{
					typeof(void),
					"void"
				}
			};
			TypeNameMap = new Dictionary<string, string>();
			foreach (KeyValuePair<Type, string> item in ReflTypeNameMap)
			{
				TypeNameMap[item.Key.FullName] = item.Value;
			}
		}

		public HookGenerator(MonoModder modder, string name)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Expected O, but got Unknown
			//IL_0326: Expected O, but got Unknown
			Modder = modder;
			OutputModule = ModuleDefinition.CreateModule(name, new ModuleParameters
			{
				Architecture = modder.Module.Architecture,
				AssemblyResolver = modder.Module.AssemblyResolver,
				Kind = (ModuleKind)0,
				Runtime = modder.Module.Runtime
			});
			modder.MapDependencies();
			Extensions.AddRange<AssemblyNameReference>(OutputModule.AssemblyReferences, (IEnumerable<AssemblyNameReference>)modder.Module.AssemblyReferences);
			modder.DependencyMap[OutputModule] = new List<ModuleDefinition>(modder.DependencyMap[modder.Module]);
			Namespace = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE");
			if (string.IsNullOrEmpty(Namespace))
			{
				Namespace = "On";
			}
			NamespaceIL = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL");
			if (string.IsNullOrEmpty(NamespaceIL))
			{
				NamespaceIL = "IL";
			}
			HookOrig = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG") == "1";
			HookPrivate = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE") == "1";
			modder.MapDependency(modder.Module, "MonoMod.RuntimeDetour", (string)null, (AssemblyNameReference)null);
			if (!modder.DependencyCache.TryGetValue("MonoMod.RuntimeDetour", out module_RuntimeDetour))
			{
				throw new FileNotFoundException("MonoMod.RuntimeDetour not found!");
			}
			modder.MapDependency(modder.Module, "MonoMod.Utils", (string)null, (AssemblyNameReference)null);
			if (!modder.DependencyCache.TryGetValue("MonoMod.Utils", out module_Utils))
			{
				throw new FileNotFoundException("MonoMod.Utils not found!");
			}
			t_MulticastDelegate = OutputModule.ImportReference(modder.FindType("System.MulticastDelegate"));
			t_IAsyncResult = OutputModule.ImportReference(modder.FindType("System.IAsyncResult"));
			t_AsyncCallback = OutputModule.ImportReference(modder.FindType("System.AsyncCallback"));
			t_MethodBase = OutputModule.ImportReference(modder.FindType("System.Reflection.MethodBase"));
			t_RuntimeMethodHandle = OutputModule.ImportReference(modder.FindType("System.RuntimeMethodHandle"));
			t_EditorBrowsableState = OutputModule.ImportReference(modder.FindType("System.ComponentModel.EditorBrowsableState"));
			TypeDefinition type = module_RuntimeDetour.GetType("MonoMod.RuntimeDetour.HookGen.HookEndpointManager");
			t_ILManipulator = OutputModule.ImportReference((TypeReference)(object)module_Utils.GetType("MonoMod.Cil.ILContext/Manipulator"));
			m_Object_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.Object").Resolve(), "System.Void .ctor()", true));
			m_ObsoleteAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ObsoleteAttribute").Resolve(), "System.Void .ctor(System.String,System.Boolean)", true));
			m_EditorBrowsableAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ComponentModel.EditorBrowsableAttribute").Resolve(), "System.Void .ctor(System.ComponentModel.EditorBrowsableState)", true));
			ModuleDefinition outputModule = OutputModule;
			MethodReference val = new MethodReference("GetMethodFromHandle", t_MethodBase, t_MethodBase);
			val.Parameters.Add(new ParameterDefinition(t_RuntimeMethodHandle));
			m_GetMethodFromHandle = outputModule.ImportReference(val);
			m_Add = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Add", true));
			m_Remove = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Remove", true));
			m_Modify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Modify", true));
			m_Unmodify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Unmodify", true));
		}

		public void Generate()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeDefinition> enumerator = Modder.Module.Types.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeDefinition current = enumerator.Current;
					GenerateFor(current, out var hookType, out var hookILType);
					if (hookType != null && hookILType != null && !((TypeReference)hookType).IsNested)
					{
						OutputModule.Types.Add(hookType);
						OutputModule.Types.Add(hookILType);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
		}

		public void GenerateFor(TypeDefinition type, out TypeDefinition hookType, out TypeDefinition hookILType)
		{
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			hookType = (hookILType = null);
			if (((TypeReference)type).HasGenericParameters || type.IsRuntimeSpecialName || ((MemberReference)type).Name.StartsWith("<") || (!HookPrivate && type.IsNotPublic))
			{
				return;
			}
			Modder.LogVerbose("[HookGen] Generating for type " + ((MemberReference)type).FullName);
			hookType = new TypeDefinition(((TypeReference)type).IsNested ? null : (Namespace + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object);
			hookILType = new TypeDefinition(((TypeReference)type).IsNested ? null : (NamespaceIL + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object);
			bool flag = false;
			Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					MethodDefinition current = enumerator.Current;
					flag |= GenerateFor(hookType, hookILType, current);
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			Enumerator<TypeDefinition> enumerator2 = type.NestedTypes.GetEnumerator();
			try
			{
				while (enumerator2.MoveNext())
				{
					TypeDefinition current2 = enumerator2.Current;
					GenerateFor(current2, out var hookType2, out var hookILType2);
					if (hookType2 != null && hookILType2 != null)
					{
						flag = true;
						hookType.NestedTypes.Add(hookType2);
						hookILType.NestedTypes.Add(hookILType2);
					}
				}
			}
			finally
			{
				((IDisposable)enumerator2).Dispose();
			}
			if (!flag)
			{
				hookType = (hookILType = null);
			}
		}

		public bool GenerateFor(TypeDefinition hookType, TypeDefinition hookILType, MethodDefinition method)
		{
			//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Expected O, but got Unknown
			//IL_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: 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_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_039c: Expected O, but got Unknown
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03aa: Expected O, but got Unknown
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ec: Expected O, but got Unknown
			//IL_03fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0407: Unknown result type (might be due to invalid IL or missing references)
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			//IL_044a: Expected O, but got Unknown
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			//IL_045f: Expected O, but got Unknown
			//IL_0463: Unknown result type (might be due to invalid IL or missing references)
			//IL_046d: Expected O, but got Unknown
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0487: Unknown result type (might be due to invalid IL or missing references)
			//IL_0498: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04af: Expected O, but got Unknown
			//IL_04be: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0501: Expected O, but got Unknown
			//IL_0533: Unknown result type (might be due to invalid IL or missing references)
			//IL_053a: Expected O, but got Unknown
			//IL_0549: Unknown result type (might be due to invalid IL or missing references)
			//IL_0553: Expected O, but got Unknown
			//IL_0557: Unknown result type (might be due to invalid IL or missing references)
			//IL_0561: Expected O, but got Unknown
			//IL_056e: Unknown result type (might be due to invalid IL or missing references)
			//IL_057b: Unknown result type (might be due to invalid IL or missing references)
			//IL_058c: Unknown result type (might be due to invalid IL or missing references)
			//IL_059c: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a3: Expected O, but got Unknown
			//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_05be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0601: Expected O, but got Unknown
			//IL_0610: Unknown result type (might be due to invalid IL or missing references)
			//IL_061a: Expected O, but got Unknown
			//IL_061e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0628: Expected O, but got Unknown
			//IL_0635: Unknown result type (might be due to invalid IL or missing references)
			//IL_0642: Unknown result type (might be due to invalid IL or missing references)
			//IL_0653: Unknown result type (might be due to invalid IL or missing references)
			//IL_0663: Unknown result type (might be due to invalid IL or missing references)
			//IL_066a: Expected O, but got Unknown
			//IL_0679: Unknown result type (might be due to invalid IL or missing references)
			//IL_0685: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c0: Expected O, but got Unknown
			if (((MethodReference)method).HasGenericParameters || method.IsAbstract || (method.IsSpecialName && !method.IsConstructor))
			{
				return false;
			}
			if (!HookOrig && ((MemberReference)method).Name.StartsWith("orig_"))
			{
				return false;
			}
			if (!HookPrivate && method.IsPrivate)
			{
				return false;
			}
			string name = GetFriendlyName((MethodReference)(object)method);
			bool flag = true;
			if (((MethodReference)method).Parameters.Count == 0)
			{
				flag = false;
			}
			IEnumerable<MethodDefinition> source = null;
			if (flag)
			{
				source = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name && other != method);
				if (source.Count() == 0)
				{
					flag = false;
				}
			}
			if (flag)
			{
				StringBuilder stringBuilder = new StringBuilder();
				for (int parami = 0; parami < ((MethodReference)method).Parameters.Count; parami++)
				{
					ParameterDefinition param = ((MethodReference)method).Parameters[parami];
					if (!TypeNameMap.TryGetValue(((MemberReference)((ParameterReference)param).ParameterType).FullName, out var typeName))
					{
						typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: false);
					}
					if (source.Any(delegate(MethodDefinition other)
					{
						ParameterDefinition val11 = ((IEnumerable<ParameterDefinition>)((MethodReference)other).Parameters).ElementAtOrDefault(parami);
						return val11 != null && GetFriendlyName(((ParameterReference)val11).ParameterType, full: false) == typeName && ((ParameterReference)val11).ParameterType.Namespace != ((ParameterReference)param).ParameterType.Namespace;
					}))
					{
						typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: true);
					}
					stringBuilder.Append("_");
					stringBuilder.Append(typeName.Replace(".", "").Replace("`", ""));
				}
				name += stringBuilder.ToString();
			}
			if (Extensions.FindEvent(hookType, name) != null)
			{
				int num = 1;
				string text;
				while (Extensions.FindEvent(hookType, text = name + "_" + num) != null)
				{
					num++;
				}
				name = text;
			}
			TypeDefinition val = GenerateDelegateFor(method);
			((MemberReference)val).Name = "orig_" + name;
			val.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
			hookType.NestedTypes.Add(val);
			TypeDefinition val2 = GenerateDelegateFor(method);
			((MemberReference)val2).Name = "hook_" + name;
			((MethodReference)Extensions.FindMethod(val2, "Invoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val));
			((MethodReference)Extensions.FindMethod(val2, "BeginInvoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val));
			val2.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
			hookType.NestedTypes.Add(val2);
			MethodReference val3 = OutputModule.ImportReference((MethodReference)(object)method);
			MethodDefinition val4 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val4).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2));
			val4.Body = new MethodBody(val4);
			ILProcessor iLProcessor = val4.Body.GetILProcessor();
			iLProcessor.Emit(OpCodes.Ldtoken, val3);
			iLProcessor.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor.Emit(OpCodes.Ldarg_0);
			GenericInstanceMethod val5 = new GenericInstanceMethod(m_Add);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor.Emit(OpCodes.Ret);
			hookType.Methods.Add(val4);
			MethodDefinition val6 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val6).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2));
			val6.Body = new MethodBody(val6);
			ILProcessor iLProcessor2 = val6.Body.GetILProcessor();
			iLProcessor2.Emit(OpCodes.Ldtoken, val3);
			iLProcessor2.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor2.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Remove);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor2.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor2.Emit(OpCodes.Ret);
			hookType.Methods.Add(val6);
			EventDefinition val7 = new EventDefinition(name, (EventAttributes)0, (TypeReference)(object)val2)
			{
				AddMethod = val4,
				RemoveMethod = val6
			};
			hookType.Events.Add(val7);
			MethodDefinition val8 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val8).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator));
			val8.Body = new MethodBody(val8);
			ILProcessor iLProcessor3 = val8.Body.GetILProcessor();
			iLProcessor3.Emit(OpCodes.Ldtoken, val3);
			iLProcessor3.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor3.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Modify);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor3.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor3.Emit(OpCodes.Ret);
			hookILType.Methods.Add(val8);
			MethodDefinition val9 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void);
			((MethodReference)val9).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator));
			val9.Body = new MethodBody(val9);
			ILProcessor iLProcessor4 = val9.Body.GetILProcessor();
			iLProcessor4.Emit(OpCodes.Ldtoken, val3);
			iLProcessor4.Emit(OpCodes.Call, m_GetMethodFromHandle);
			iLProcessor4.Emit(OpCodes.Ldarg_0);
			val5 = new GenericInstanceMethod(m_Unmodify);
			val5.GenericArguments.Add((TypeReference)(object)val2);
			iLProcessor4.Emit(OpCodes.Call, (MethodReference)(object)val5);
			iLProcessor4.Emit(OpCodes.Ret);
			hookILType.Methods.Add(val9);
			EventDefinition val10 = new EventDefinition(name, (EventAttributes)0, t_ILManipulator)
			{
				AddMethod = val8,
				RemoveMethod = val9
			};
			hookILType.Events.Add(val10);
			return true;
		}

		public TypeDefinition GenerateDelegateFor(MethodDefinition method)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Expected O, but got Unknown
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Expected O, but got Unknown
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Expected O, but got Unknown
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Expected O, but got Unknown
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Expected O, but got Unknown
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Expected O, but got Unknown
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Expected O, but got Unknown
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: Expected O, but got Unknown
			//IL_0300: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Expected O, but got Unknown
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Expected O, but got Unknown
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Expected O, but got Unknown
			//IL_0367: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Expected O, but got Unknown
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_037f: Expected O, but got Unknown
			string name = GetFriendlyName((MethodReference)(object)method);
			int num = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name).ToList().IndexOf(method);
			if (num != 0)
			{
				string suffix = num.ToString();
				do
				{
					name = name + "_" + suffix;
				}
				while (((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Any((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name + suffix));
			}
			name = "d_" + name;
			TypeDefinition val = new TypeDefinition((string)null, (string)null, (TypeAttributes)258, t_MulticastDelegate);
			MethodDefinition val2 = new MethodDefinition(".ctor", (MethodAttributes)6278, OutputModule.TypeSystem.Void)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.Object));
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.IntPtr));
			val2.Body = new MethodBody(val2);
			val.Methods.Add(val2);
			MethodDefinition val3 = new MethodDefinition("Invoke", (MethodAttributes)454, ImportVisible(((MethodReference)method).ReturnType))
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			if (!method.IsStatic)
			{
				TypeReference val4 = ImportVisible((TypeReference)(object)method.DeclaringType);
				if (((TypeReference)method.DeclaringType).IsValueType)
				{
					val4 = (TypeReference)new ByReferenceType(val4);
				}
				((MethodReference)val3).Parameters.Add(new ParameterDefinition("self", (ParameterAttributes)0, val4));
			}
			Enumerator<ParameterDefinition> enumerator = ((MethodReference)method).Parameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ParameterDefinition current = enumerator.Current;
					((MethodReference)val3).Parameters.Add(new ParameterDefinition(((ParameterReference)current).Name, (ParameterAttributes)(current.Attributes & 0xFFEF & 0xEFFF), ImportVisible(((ParameterReference)current).ParameterType)));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			val3.Body = new MethodBody(val3);
			val.Methods.Add(val3);
			MethodDefinition val5 = new MethodDefinition("BeginInvoke", (MethodAttributes)454, t_IAsyncResult)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			enumerator = ((MethodReference)val3).Parameters.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					ParameterDefinition current2 = enumerator.Current;
					((MethodReference)val5).Parameters.Add(new ParameterDefinition(((ParameterReference)current2).Name, current2.Attributes, ((ParameterReference)current2).ParameterType));
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			((MethodReference)val5).Parameters.Add(new ParameterDefinition("callback", (ParameterAttributes)0, t_AsyncCallback));
			((MethodReference)val5).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, OutputModule.TypeSystem.Object));
			val5.Body = new MethodBody(val5);
			val.Methods.Add(val5);
			MethodDefinition val6 = new MethodDefinition("EndInvoke", (MethodAttributes)454, OutputModule.TypeSystem.Object)
			{
				ImplAttributes = (MethodImplAttributes)3,
				HasThis = true
			};
			((MethodReference)val6).Parameters.Add(new ParameterDefinition("result", (ParameterAttributes)0, t_IAsyncResult));
			val6.Body = new MethodBody(val6);
			val.Methods.Add(val6);
			return val;
		}

		private string GetFriendlyName(MethodReference method)
		{
			string text = ((MemberReference)method).Name;
			if (text.StartsWith("."))
			{
				text = text.Substring(1);
			}
			return text.Replace('.', '_');
		}

		private string GetFriendlyName(TypeReference type, bool full)
		{
			if (type is TypeSpecification)
			{
				StringBuilder stringBuilder = new StringBuilder();
				BuildFriendlyName(stringBuilder, type, full);
				return stringBuilder.ToString();
			}
			if (!full)
			{
				return ((MemberReference)type).Name;
			}
			return ((MemberReference)type).FullName;
		}

		private void BuildFriendlyName(StringBuilder builder, TypeReference type, bool full)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (!(type is TypeSpecification))
			{
				builder.Append((full ? ((MemberReference)type).FullName : ((MemberReference)type).Name).Replace("_", ""));
				return;
			}
			if (type.IsByReference)
			{
				builder.Append("ref");
			}
			else if (type.IsPointer)
			{
				builder.Append("ptr");
			}
			BuildFriendlyName(builder, ((TypeSpecification)type).ElementType, full);
			if (type.IsArray)
			{
				builder.Append("Array");
			}
		}

		private bool IsPublic(TypeDefinition typeDef)
		{
			if (typeDef != null && (typeDef.IsNestedPublic || typeDef.IsPublic))
			{
				return !typeDef.IsNotPublic;
			}
			return false;
		}

		private bool HasPublicArgs(GenericInstanceType typeGen)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<TypeReference> enumerator = typeGen.GenericArguments.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					TypeReference current = enumerator.Current;
					if (current.IsGenericParameter)
					{
						return false;
					}
					GenericInstanceType val = (GenericInstanceType)(object)((current is GenericInstanceType) ? current : null);
					if (val != null && !HasPublicArgs(val))
					{
						return false;
					}
					if (!IsPublic(Extensions.SafeResolve(current)))
					{
						return false;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator).Dispose();
			}
			return true;
		}

		private TypeReference ImportVisible(TypeReference typeRef)
		{
			for (TypeDefinition val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null); val != null; val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null))
			{
				GenericInstanceType val2 = (GenericInstanceType)(object)((typeRef is GenericInstanceType) ? typeRef : null);
				if (val2 == null || HasPublicArgs(val2))
				{
					TypeDefinition val3 = val;
					while (true)
					{
						if (val3 != null)
						{
							if (IsPublic(val3) && (val3 == val || !((TypeReference)val3).HasGenericParameters))
							{
								val3 = val3.DeclaringType;
								continue;
							}
							if (!val.IsEnum)
							{
								break;
							}
							typeRef = ((FieldReference)Extensions.FindField(val, "value__")).FieldType;
						}
						try
						{
							return OutputModule.ImportReference(typeRef);
						}
						catch
						{
							return OutputModule.TypeSystem.Object;
						}
					}
				}
				typeRef = val.BaseType;
			}
			return OutputModule.TypeSystem.Object;
		}

		private CustomAttribute GenerateObsolete(string message, bool error)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			CustomAttribute val = new CustomAttribute(m_ObsoleteAttribute_ctor);
			val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.String, (object)message));
			val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.Boolean, (object)error));
			return val;
		}

		private CustomAttribute GenerateEditorBrowsable(EditorBrowsableState state)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//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_0028: Expected O, but got Unknown
			CustomAttribute val = new CustomAttribute(m_EditorBrowsableAttribute_ctor);
			val.ConstructorArguments.Add(new CustomAttributeArgument(t_EditorBrowsableState, (object)state));
			return val;
		}
	}
	internal class Program
	{
		private static void Main(string[] args)
		{
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Expected O, but got Unknown
			Console.WriteLine("MonoMod.RuntimeDetour.HookGen " + typeof(Program).Assembly.GetName().Version);
			Console.WriteLine("using MonoMod " + typeof(MonoModder).Assembly.GetName().Version);
			Console.WriteLine("using MonoMod.RuntimeDetour " + typeof(Detour).Assembly.GetName().Version);
			if (args.Length == 0)
			{
				Console.WriteLine("No valid arguments (assembly path) passed.");
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
				return;
			}
			int num = 0;
			for (int i = 0; i < args.Length; i++)
			{
				if (args[i] == "--namespace" && i + 2 < args.Length)
				{
					i++;
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE", args[i]);
					continue;
				}
				if (args[i] == "--namespace-il" && i + 2 < args.Length)
				{
					i++;
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL", args[i]);
					continue;
				}
				if (args[i] == "--orig")
				{
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG", "1");
					continue;
				}
				if (args[i] == "--private")
				{
					Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1");
					continue;
				}
				num = i;
				break;
			}
			if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW")))
			{
				Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0");
			}
			if (num >= args.Length)
			{
				Console.WriteLine("No assembly path passed.");
				if (Debugger.IsAttached)
				{
					Console.ReadKey();
				}
				return;
			}
			string text = args[num];
			string text2 = ((args.Length != 1 && num != args.Length - 1) ? args[^1] : null);
			text2 = text2 ?? Path.Combine(Path.GetDirectoryName(text), "MMHOOK_" + Path.ChangeExtension(Path.GetFileName(text), "dll"));
			MonoModder val = new MonoModder
			{
				InputPath = text,
				OutputPath = text2,
				ReadingMode = (ReadingMode)2
			};
			try
			{
				val.Read();
				val.MapDependencies();
				if (File.Exists(text2))
				{
					val.Log("[HookGen] Clearing " + text2);
					File.Delete(text2);
				}
				val.Log("[HookGen] Starting HookGenerator");
				HookGenerator hookGenerator = new HookGenerator(val, Path.GetFileName(text2));
				ModuleDefinition outputModule = hookGenerator.OutputModule;
				try
				{
					hookGenerator.Generate();
					outputModule.Write(text2);
				}
				finally
				{
					((IDisposable)outputModule)?.Dispose();
				}
				val.Log("[HookGen] Done.");
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			if (Debugger.IsAttached)
			{
				Console.ReadKey();
			}
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/Capydog/CapydogMod.dll

Decompiled 7 months ago
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("CapydogMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CapydogMod")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("ee756f41-a283-45b4-8eeb-02e26ee5f44f")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace CapydogMod
{
	[BepInPlugin("LoddMods.Capydog", "Capydog", "1.2.0.0")]
	public class ModBase : BaseUnityPlugin
	{
		private readonly Harmony harmony = new Harmony("LoddMods.Capydog");

		public static ModBase instance;

		public static ManualLogSource mls;

		public static AssetBundle capydogBundle;

		public static GameObject capyObj;

		private void Awake()
		{
			if ((Object)(object)instance == (Object)null)
			{
				instance = this;
			}
			mls = Logger.CreateLogSource("LoddMods.Capydog");
			mls.LogWarning((object)"Capydog successfully loaded.");
			capydogBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "capydog"));
			capyObj = capydogBundle.LoadAsset<GameObject>("Assets/CustomModels/Capybara.prefab");
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
		}
	}
	public static class PluginInfo
	{
		public const string modGUID = "LoddMods.Capydog";

		public const string modName = "Capydog";

		public const string modVers = "1.2.0.0";
	}
}
namespace CapydogMod.Patches
{
	[HarmonyPatch(typeof(MouthDogAI), "Start")]
	public class MouthdogPatch
	{
		[HarmonyPostfix]
		public static void CapydogSwap(MouthDogAI __instance)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Expected O, but got Unknown
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_0353: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_041a: Unknown result type (might be due to invalid IL or missing references)
			//IL_045a: Unknown result type (might be due to invalid IL or missing references)
			//IL_046e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0473: Unknown result type (might be due to invalid IL or missing references)
			//IL_0494: Unknown result type (might be due to invalid IL or missing references)
			ModBase.mls.LogInfo((object)"Swapping Mouthdog -> Capydog!");
			if ((Object)ModBase.capyObj == (Object)null)
			{
				ModBase.mls.LogError((object)"Could not find Capydog model!!!");
				return;
			}
			Transform val = ((Component)__instance).transform.Find("MouthDogModel");
			SkinnedMeshRenderer val2 = null;
			SkinnedMeshRenderer val3 = null;
			Transform val4 = null;
			if ((Object)(object)val != (Object)null)
			{
				Transform val5 = val.Find("ToothDogBody");
				Transform val6 = val.Find("ToothDogBodyLOD1");
				Transform val7 = val.Find("AnimContainer");
				val2 = (((Object)(object)val5 != (Object)null) ? ((Component)val5).GetComponent<SkinnedMeshRenderer>() : null);
				val3 = (((Object)(object)val6 != (Object)null) ? ((Component)val6).GetComponent<SkinnedMeshRenderer>() : null);
				val4 = (((Object)(object)val7 != (Object)null) ? val7.Find("Armature") : null);
			}
			if ((Object)val2 == (Object)null || !((Renderer)val2).enabled || (Object)val3 == (Object)null || !((Renderer)val3).enabled)
			{
				return;
			}
			((Renderer)val2).enabled = false;
			((Renderer)val3).enabled = false;
			Renderer[] componentsInChildren = ((Component)val4).gameObject.GetComponentsInChildren<Renderer>();
			Renderer[] array = componentsInChildren;
			foreach (Renderer val8 in array)
			{
				val8.enabled = false;
			}
			GameObject val9 = Object.Instantiate<GameObject>(ModBase.capyObj);
			val9.transform.SetParent(val);
			val9.transform.localPosition = Vector3.zero;
			val9.transform.localRotation = Quaternion.identity;
			val9.transform.localScale = Vector3.one;
			Transform val10 = val9.transform.Find("Capybara");
			Transform val11 = val9.transform.Find("Armature");
			val11.SetParent(val4.parent);
			((Component)val11).transform.localPosition = val4.localPosition + Vector3.up * 2f;
			((Component)val11).transform.localRotation = val4.localRotation;
			SkinnedMeshRenderer component = ((Component)val10).GetComponent<SkinnedMeshRenderer>();
			string[] array2 = new string[6] { "Torso1", "Torso1/Butt/ThighBackLeft", "Torso1/Butt/ThighBackRight", "Neck1Container/Neck1/Neck2", "Torso1/ShoulderFrontLeft", "Torso1/ShoulderFrontRight" };
			string[] array3 = new string[6] { "Torso1", "Torso1/Butt/ThighBackLeft", "Torso1/Butt/ThighBackRight", "Torso1/Neck1/Neck2", "Torso1/ShoulderFrontLeft", "Torso1/ShoulderFrontRight" };
			int num = ((array2.Length == array3.Length) ? array2.Length : 0);
			int num2 = num;
			while (num2-- > 0)
			{
				Transform val12 = val4.Find(array2[num2]);
				Transform val13 = val11.Find(array3[num2]);
				ModBase.mls.LogWarning((object)$"{num2}) DogBone \"{array2[num2]}\" -> CapyBone \"{array3[num2]}\"");
				val13.SetParent(val12);
				((Component)val13).transform.localPosition = ((Component)val12).transform.localPosition;
				((Component)val13).transform.localRotation = ((Component)val12).transform.localRotation;
				if (array3[num2].EndsWith("Torso1"))
				{
					component.rootBone = val13;
					((Component)val13).transform.localPosition = new Vector3(0f, 2.5f, -1f);
					((Component)val13).transform.localRotation = Quaternion.Euler(0f, 0f, 180f);
				}
				else if (array3[num2].EndsWith("ShoulderFrontLeft"))
				{
					((Component)val13).transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
				}
				else if (array3[num2].EndsWith("ShoulderFrontRight"))
				{
					Transform transform = ((Component)val13).transform;
					transform.localPosition += new Vector3(0.5f, 0f, -1f);
					((Component)val13).transform.localRotation = Quaternion.Euler(-30f, 0f, 0f);
				}
				else if (array3[num2].EndsWith("ThighBackLeft") || array3[num2].EndsWith("ThighBackRight"))
				{
					Transform transform2 = ((Component)val13).transform;
					transform2.localPosition += new Vector3(0f, 0f, -1f);
					((Component)val13).transform.localRotation = Quaternion.Euler(-30f, 180f, 0f);
				}
			}
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/CustomDeathMessage.dll

Decompiled 7 months ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("CustomDeathMessage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CustomDeathMessage")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("f048cd05-0a19-4f9e-8376-bc58c4518662")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace CustomDeathMessage;

[BepInPlugin("Swaggies.CustomDeathMessage", "CustomDeathMessage", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	private const string _guid = "Swaggies.CustomDeathMessage";

	private const string _name = "CustomDeathMessage";

	private const string _ver = "1.0.0";

	private readonly Harmony harmony = new Harmony("Swaggies.CustomDeathMessage");

	private static Plugin Instance;

	private static ManualLogSource logga;

	public static ConfigEntry<string> message;

	private void Awake()
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Instance = this;
		}
		logga = Logger.CreateLogSource("Swaggies.CustomDeathMessage");
		harmony.PatchAll(typeof(Plugin));
		logga.LogInfo((object)"CustomDeathMessage up and running.");
		message = ((BaseUnityPlugin)this).Config.Bind<string>("General", "DeathMessage", "[LIFE SUPPORT: OFFLINE]", "What your custom death message should be. Default value is game's default death message.");
	}

	[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
	[HarmonyPrefix]
	private static void DeathPatch()
	{
		GameObject val = GameObject.Find("Systems/UI/Canvas/DeathScreen/GameOverText");
		TextMeshProUGUI component = val.GetComponent<TextMeshProUGUI>();
		if (message.Value == "")
		{
			((TMP_Text)component).text = "[LIFE SUPPORT: OFFLINE]";
		}
		else
		{
			((TMP_Text)component).text = message.Value;
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/Diversity/Diversity.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Diversity.Items;
using Diversity.Misc;
using Diversity.Monsters;
using Diversity.Patches;
using Diversity.Player;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Audio;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Diversity")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Diversity")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("6163c54c-2d5b-4683-ac86-9337d16cc4fd")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
public enum Condition
{
	BrokenLeg,
	BrokenArm,
	FracturedLeg,
	FracturedArm,
	Bleeding,
	Blindness,
	Concussed
}
public enum DamageType
{
	GunShotted,
	Mauled,
	Electrified,
	Falling,
	Bitten,
	Concussed,
	Burned,
	Gas
}
namespace Diversity
{
	public class Configuration
	{
		public static ConfigEntry<bool> spiderRevamp;

		public static ConfigEntry<float> spiderSlowAmount;

		public static ConfigEntry<bool> crawlerRevamp;

		public static ConfigEntry<float> crawlerSlowAmount;

		public static ConfigEntry<bool> centipedeRevamp;

		public static ConfigEntry<int> clickAmount;

		public static ConfigEntry<int> hurtChance;

		public static ConfigEntry<bool> brakenRevamp;

		public static ConfigEntry<bool> brakenSpace;

		public static ConfigEntry<float> brakenRange;

		public static ConfigEntry<bool> brakenAnger;

		public static ConfigEntry<float> brakenAngerTime;

		public static ConfigEntry<int> flickerChance;

		public static ConfigEntry<int> breakerChance;

		public static ConfigEntry<bool> apparatusAnger;

		public static ConfigEntry<bool> chaseTriggerer;

		public static ConfigEntry<bool> dressGirlRevamp;

		public static ConfigEntry<float> walkieTalkieFrequency;

		public static ConfigEntry<bool> dressGirlIsolation;

		public static ConfigEntry<bool> playerConditions;

		public static ConfigEntry<bool> fullDarkness;

		public static ConfigEntry<float> fullDarknessIntensity;

		public static ConfigEntry<float> interactRange;

		public static ConfigEntry<bool> fracturedLeg;

		public static ConfigEntry<float> fracturedLegTime;

		public static ConfigEntry<bool> fracturedArm;

		public static ConfigEntry<float> fracturedArmTime;

		public static ConfigEntry<bool> brokenLeg;

		public static ConfigEntry<bool> brokenArm;

		public static ConfigEntry<bool> bleeding;

		public static ConfigEntry<float> bleedingTime;

		public static ConfigEntry<bool> blindness;

		public static ConfigEntry<float> blindnessTime;

		public static ConfigEntry<bool> concussed;

		public static void Load()
		{
			spiderRevamp = Diversity.config.Bind<bool>("Spider", "SpiderRevamp", true, "Should spider revamp be enabled?");
			spiderSlowAmount = Diversity.config.Bind<float>("Spider", "SpiderSlow", 0.8f, "How much slown should spiders be on hit?");
			crawlerRevamp = Diversity.config.Bind<bool>("Crawler", "CrawlerRevamp", true, "Should crawler revamp be enabled?");
			crawlerSlowAmount = Diversity.config.Bind<float>("Crawler", "CrawlerSlow", 0.9f, "How much slown should crawlers be on hit?");
			centipedeRevamp = Diversity.config.Bind<bool>("Centipede", "CentipedeRevamp", true, "Should centipede revamp be enabled?");
			clickAmount = Diversity.config.Bind<int>("Centipede", "ClickAmount", 30, "How many times should you have to click to remove the centipede from someone's head?");
			hurtChance = Diversity.config.Bind<int>("Centipede", "HurtChance", 10, "Chance of hurting the player when trying to free the centipede.");
			brakenRevamp = Diversity.config.Bind<bool>("Bracken", "BrakenRevamp", true, "Should Bracken revamp be enabled?");
			brakenSpace = Diversity.config.Bind<bool>("Bracken", "BrakenPersonnalSpace", true, "Should the Bracken have his own personnal space?");
			brakenRange = Diversity.config.Bind<float>("Bracken", "BrakenRange", 15f, "From how far should the Bracken be able to turn off lights?");
			brakenAnger = Diversity.config.Bind<bool>("Bracken", "BrakenAnger", true, "Should Bracken get angered from the breaker box?");
			brakenAngerTime = Diversity.config.Bind<float>("Bracken", "BrakenAngerTime", 90f, "How long should the Bracken stay angered when fully angered?");
			flickerChance = Diversity.config.Bind<int>("Bracken", "FlickerChance", 100, "Chance on flickering and turning off lights.");
			breakerChance = Diversity.config.Bind<int>("Bracken", "BreakerChance", 75, "Chance for the Bracken to turn off the breaker box.");
			apparatusAnger = Diversity.config.Bind<bool>("Bracken", "ApparatusAnger", true, "Should taking the Apparatus anger the Bracken?");
			chaseTriggerer = Diversity.config.Bind<bool>("Bracken", "ChaseTriggerer", true, "Should the Bracken chase the one who angered him?");
			dressGirlRevamp = Diversity.config.Bind<bool>("Dress Girl", "DressGirlRevamp", true, "Should Dress girl revamp be enabled?");
			walkieTalkieFrequency = Diversity.config.Bind<float>("Dress Girl", "WalkieTalkieFrequency", 1f, "How frequent should the Dress girl haunt the walkie-talkie?");
			dressGirlIsolation = Diversity.config.Bind<bool>("Dress Girl", "DressGirlIsolation", true, "Should Dress girl be able to isolate you and give you hallucinations? (Requires DressGirlRevamp to be enabled.)");
			playerConditions = Diversity.config.Bind<bool>("Player", "PlayerConditions", true, "Should players be able to gain conditions?");
			fullDarkness = Diversity.config.Bind<bool>("Player", "FullDarkness", true, "Should players with no light source be completely in the dark?");
			fullDarknessIntensity = Diversity.config.Bind<float>("Player", "FullDarknessIntensity", 1f, "How intense should full darkness be?");
			interactRange = Diversity.config.Bind<float>("Player", "InteractRange", 3f, "How far can players remove centipede from their head?");
			fracturedLeg = Diversity.config.Bind<bool>("Conditions", "Fractured Leg", true, "Can players fracture their legs? (Will also disable broken legs.)");
			fracturedLegTime = Diversity.config.Bind<float>("Conditions", "Fractured Leg Time", 60f, "How long should fractured legs last?");
			fracturedArm = Diversity.config.Bind<bool>("Conditions", "Fractured Arm", true, "Can players fracture their arms? (Will also disable broken arms.");
			fracturedArmTime = Diversity.config.Bind<float>("Conditions", "Fractured Arm Time", 60f, "How long should fractured arms last?");
			brokenLeg = Diversity.config.Bind<bool>("Conditions", "Broken Leg", true, "Can players break their legs?");
			brokenArm = Diversity.config.Bind<bool>("Conditions", "Broken Arm", true, "Can players break their arms?");
			bleeding = Diversity.config.Bind<bool>("Conditions", "Bleeding", true, "Can players bleed?");
			bleedingTime = Diversity.config.Bind<float>("Conditions", "Bleeding Time", 300f, "How long should bleeding last?");
			blindness = Diversity.config.Bind<bool>("Conditions", "Blindness", true, "Can players be blinded?");
			blindnessTime = Diversity.config.Bind<float>("Conditions", "Blindness Time", 30f, "How long should blindness last? (in seconds)");
			concussed = Diversity.config.Bind<bool>("Conditions", "Concussed", true, "Can players concussed?");
		}
	}
	public class Content
	{
		public static AssetBundle MainAssets;

		public static void TryLoadAssets()
		{
			if ((Object)(object)MainAssets == (Object)null)
			{
				MainAssets = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "diversity"));
				Diversity.mls.LogInfo((object)"Loaded asset bundle!");
			}
		}
	}
	public class DiversityAssets : MonoBehaviour
	{
		[Serializable]
		public class RandomSoundAudioClip
		{
			public DiversitySoundManager.SoundType soundType;

			public AudioClip[] audioClips;
		}

		[Serializable]
		public class SoundAudioClip
		{
			public DiversitySoundManager.SoundType soundType;

			public AudioClip audioClip;
		}

		public SoundAudioClip[] soundAudioClipArray;

		public RandomSoundAudioClip[] randomSoundAudioClipArray;

		public static DiversityAssets Instance { get; private set; }

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
				Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			}
			else
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}
	}
	public class DiversitySoundManager : MonoBehaviour
	{
		public enum SoundType
		{
			SteamLeak,
			LightOn,
			LightBuzz,
			Ambience,
			Fracture,
			BrokenBone,
			Hurt,
			BrackenScream,
			BrackenSpeech,
			DressGirlSpeech,
			DressGirlVoices,
			HeartBeat,
			DoorSlam,
			WalkerFootStep
		}

		public static GameObject oneShot;

		public static AudioSource oneShotAudio;

		public static GameObject oneShotBypass;

		public static AudioSource oneShotAudioBypass;

		public List<GameObject> current3Daudios = new List<GameObject>();

		public List<GameObject> currentGirlAudios = new List<GameObject>();

		public static DiversitySoundManager Instance { get; private set; }

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
				Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			}
			else
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}

		public static void PlaySound(SoundType soundType, bool random, float volume, float pan, bool loop, Vector3 position)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			AudioMixerGroup outputAudioMixerGroup = SoundManager.Instance.diageticMixer.FindMatchingGroups("SFX")[0];
			GameObject val = new GameObject("Sound");
			val.transform.position = position;
			AudioSource val2 = val.AddComponent<AudioSource>();
			val2.spatialBlend = 1f;
			val2.playOnAwake = false;
			val2.dopplerLevel = 0f;
			val2.spread = 70f;
			val2.reverbZoneMix = 1f;
			val2.outputAudioMixerGroup = outputAudioMixerGroup;
			val2.loop = loop;
			val2.panStereo = pan;
			if (random)
			{
				val2.clip = GetRandomAudioClipByType(soundType);
			}
			else
			{
				val2.clip = GetAudioClipByType(soundType);
			}
			val2.rolloffMode = (AudioRolloffMode)1;
			if (soundType == SoundType.LightOn)
			{
				val2.maxDistance = 100f;
			}
			else if (soundType == SoundType.SteamLeak || soundType == SoundType.LightBuzz)
			{
				val2.maxDistance = 32f;
			}
			else
			{
				val2.maxDistance = 32f;
			}
			val2.volume = volume;
			val2.Play();
			if (soundType == SoundType.DressGirlSpeech)
			{
				Instance.currentGirlAudios.Add(val);
			}
			else if (!loop)
			{
				Object.Destroy((Object)(object)val, val2.clip.length);
			}
			else
			{
				Instance.current3Daudios.Add(val);
			}
		}

		public static void PlaySound(SoundType soundType, bool random, float volume, float pan)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			AudioMixerGroup outputAudioMixerGroup = SoundManager.Instance.diageticMixer.FindMatchingGroups("SFX")[0];
			if ((Object)(object)oneShot == (Object)null)
			{
				oneShot = new GameObject("OneShotSound");
				oneShotAudio = oneShot.AddComponent<AudioSource>();
			}
			oneShotAudio.outputAudioMixerGroup = outputAudioMixerGroup;
			oneShotAudio.panStereo = pan;
			if (random)
			{
				oneShotAudio.PlayOneShot(GetRandomAudioClipByType(soundType), volume);
			}
			else
			{
				oneShotAudio.PlayOneShot(GetAudioClipByType(soundType), volume);
			}
		}

		public static void DeleteAudio(GameObject audio)
		{
			Object.Destroy((Object)(object)audio);
		}

		public static void PlaySoundBypass(SoundType soundType, bool random, float volume, float pan, bool loop, Vector3 position)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Sound");
			val.transform.position = position;
			AudioSource val2 = val.AddComponent<AudioSource>();
			val2.spatialBlend = 1f;
			val2.playOnAwake = false;
			val2.dopplerLevel = 0f;
			val2.spread = 70f;
			val2.reverbZoneMix = 1f;
			val2.bypassListenerEffects = true;
			val2.loop = loop;
			val2.panStereo = pan;
			if (random)
			{
				val2.clip = GetRandomAudioClipByType(soundType);
			}
			else
			{
				val2.clip = GetAudioClipByType(soundType);
			}
			val2.rolloffMode = (AudioRolloffMode)1;
			if (soundType == SoundType.LightOn)
			{
				val2.maxDistance = 100f;
			}
			else if (soundType == SoundType.SteamLeak || soundType == SoundType.LightBuzz)
			{
				val2.maxDistance = 32f;
			}
			else
			{
				val2.maxDistance = 32f;
			}
			val2.volume = volume;
			val2.Play();
			if (soundType == SoundType.DressGirlSpeech)
			{
				Instance.currentGirlAudios.Add(val);
			}
			else if (!loop)
			{
				Object.Destroy((Object)(object)val, val2.clip.length);
			}
			else
			{
				Instance.current3Daudios.Add(val);
			}
		}

		public static void PlaySoundBypass(SoundType soundType, bool random, float volume = 1f, float pan = 1f)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			if ((Object)(object)oneShotBypass == (Object)null)
			{
				oneShotBypass = new GameObject("OneShotSound");
				oneShotAudioBypass = oneShotBypass.AddComponent<AudioSource>();
				oneShotAudioBypass.bypassListenerEffects = true;
			}
			oneShotAudioBypass.panStereo = pan;
			if (random)
			{
				oneShotAudioBypass.PlayOneShot(GetRandomAudioClipByType(soundType), volume);
			}
			else
			{
				oneShotAudioBypass.PlayOneShot(GetAudioClipByType(soundType), volume);
			}
		}

		public static void StopSound()
		{
			if ((Object)(object)oneShot != (Object)null)
			{
				oneShotAudio.Stop();
			}
		}

		public static void StopSoundBypass()
		{
			if ((Object)(object)oneShot != (Object)null)
			{
				oneShotAudioBypass.Stop();
			}
		}

		public static Vector3 CheckPosition(PlayerControllerB player)
		{
			//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_0044: 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)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)player))
			{
				if (!player.isPlayerDead)
				{
					return ((Component)player.gameplayCamera).transform.position;
				}
				return player.spectateCameraPivot.position;
			}
			return Vector3.zero;
		}

		private static AudioClip GetAudioClipByType(SoundType soundType)
		{
			Diversity.mls.LogInfo((object)DiversityAssets.Instance.soundAudioClipArray);
			DiversityAssets.SoundAudioClip[] soundAudioClipArray = DiversityAssets.Instance.soundAudioClipArray;
			foreach (DiversityAssets.SoundAudioClip soundAudioClip in soundAudioClipArray)
			{
				if (soundAudioClip.soundType == soundType)
				{
					return soundAudioClip.audioClip;
				}
			}
			Diversity.mls.LogError((object)("No audio of type:" + soundType));
			return null;
		}

		private static AudioClip GetRandomAudioClipByType(SoundType soundType)
		{
			DiversityAssets.RandomSoundAudioClip[] randomSoundAudioClipArray = DiversityAssets.Instance.randomSoundAudioClipArray;
			foreach (DiversityAssets.RandomSoundAudioClip randomSoundAudioClip in randomSoundAudioClipArray)
			{
				if (randomSoundAudioClip.soundType == soundType)
				{
					return randomSoundAudioClip.audioClips[Random.Range(0, randomSoundAudioClip.audioClips.Length)];
				}
			}
			Diversity.mls.LogError((object)("No audio of type:" + soundType));
			return null;
		}
	}
	[BepInPlugin("Chaos.Diversity", "Diversity", "1.1.10")]
	public class Diversity : BaseUnityPlugin
	{
		private const string modGUID = "Chaos.Diversity";

		private const string modName = "Diversity";

		private const string modVersion = "1.1.10";

		private readonly Harmony harmony = new Harmony("Chaos.Diversity");

		public static Diversity Instance;

		public static ManualLogSource mls;

		public static ConfigFile config;

		public static EnemyType longBoiType;

		private void Awake()
		{
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = ((BaseUnityPlugin)this).Logger;
			config = ((BaseUnityPlugin)this).Config;
			Configuration.Load();
			Content.TryLoadAssets();
			harmony.PatchAll(typeof(BaboonBirdAIPatch));
			harmony.PatchAll(typeof(BlobAIPatch));
			harmony.PatchAll(typeof(BreakerBoxPatch));
			harmony.PatchAll(typeof(CentipedeAIPatch));
			harmony.PatchAll(typeof(CrawlerAIPatch));
			harmony.PatchAll(typeof(DressGirlAIPatch));
			harmony.PatchAll(typeof(FlashlightPatch));
			harmony.PatchAll(typeof(FlowermanAIPatch));
			harmony.PatchAll(typeof(HoarderBugAIPatch));
			harmony.PatchAll(typeof(HUDPatch));
			harmony.PatchAll(typeof(LungPropPatch));
			harmony.PatchAll(typeof(ManualCameraRendererPatch));
			harmony.PatchAll(typeof(PlayerControllerBPatch));
			harmony.PatchAll(typeof(PufferAIPatch));
			harmony.PatchAll(typeof(RadarBoosterItemPatch));
			harmony.PatchAll(typeof(RedLocustBeesPatch));
			harmony.PatchAll(typeof(RoundManagerPatch));
			harmony.PatchAll(typeof(SandSpiderAIPatch));
			harmony.PatchAll(typeof(ShipTeleporterPatch));
			harmony.PatchAll(typeof(SoundManagerPatch));
			harmony.PatchAll(typeof(SpringManAIPatch));
			harmony.PatchAll(typeof(StartOfRoundPatch));
			harmony.PatchAll(typeof(SteamValveHazardPatch));
			harmony.PatchAll(typeof(Diversity));
			longBoiType = Content.MainAssets.LoadAsset<EnemyType>("Assets/custom/diversity/walker/WalkerType.asset");
			GameObject val = new GameObject("DiversitySoundManagerAssets");
			val.AddComponent<DiversitySoundManager>();
			DiversityAssets diversityAssets = val.AddComponent<DiversityAssets>();
			diversityAssets.soundAudioClipArray = new DiversityAssets.SoundAudioClip[4];
			diversityAssets.randomSoundAudioClipArray = new DiversityAssets.RandomSoundAudioClip[6];
			DiversityAssets.SoundAudioClip soundAudioClip = new DiversityAssets.SoundAudioClip();
			soundAudioClip.soundType = DiversitySoundManager.SoundType.SteamLeak;
			soundAudioClip.audioClip = Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/bracken/rooms/audio/steam.ogg");
			DiversityAssets.SoundAudioClip soundAudioClip2 = new DiversityAssets.SoundAudioClip();
			soundAudioClip2.soundType = DiversitySoundManager.SoundType.LightOn;
			soundAudioClip2.audioClip = Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/bracken/rooms/audio/lighton.ogg");
			DiversityAssets.SoundAudioClip soundAudioClip3 = new DiversityAssets.SoundAudioClip();
			soundAudioClip3.soundType = DiversitySoundManager.SoundType.LightBuzz;
			soundAudioClip3.audioClip = Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/bracken/rooms/audio/lightbuzz.ogg");
			DiversityAssets.SoundAudioClip soundAudioClip4 = new DiversityAssets.SoundAudioClip();
			soundAudioClip4.soundType = DiversitySoundManager.SoundType.HeartBeat;
			soundAudioClip4.audioClip = Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/player/audio/heartbeat.ogg");
			DiversityAssets.RandomSoundAudioClip randomSoundAudioClip = new DiversityAssets.RandomSoundAudioClip();
			AudioClip[] audioClips = (AudioClip[])(object)new AudioClip[1] { Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/bracken/ambience.ogg") };
			randomSoundAudioClip.soundType = DiversitySoundManager.SoundType.Ambience;
			randomSoundAudioClip.audioClips = audioClips;
			DiversityAssets.RandomSoundAudioClip randomSoundAudioClip2 = new DiversityAssets.RandomSoundAudioClip();
			AudioClip[] audioClips2 = (AudioClip[])(object)new AudioClip[1] { Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/bracken/brakenScream.mp3") };
			randomSoundAudioClip2.soundType = DiversitySoundManager.SoundType.BrackenScream;
			randomSoundAudioClip2.audioClips = audioClips2;
			DiversityAssets.RandomSoundAudioClip randomSoundAudioClip3 = new DiversityAssets.RandomSoundAudioClip();
			AudioClip[] audioClips3 = (AudioClip[])(object)new AudioClip[1] { Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/bracken/you're next.mp3") };
			randomSoundAudioClip3.soundType = DiversitySoundManager.SoundType.BrackenSpeech;
			randomSoundAudioClip3.audioClips = audioClips3;
			DiversityAssets.RandomSoundAudioClip randomSoundAudioClip4 = new DiversityAssets.RandomSoundAudioClip();
			AudioClip[] audioClips4 = (AudioClip[])(object)new AudioClip[17]
			{
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 1.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 2.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 3.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 4.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 5.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 6.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 7.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 8.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 9.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 10.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 11.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 12.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 14.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 15.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 16.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 17.wav"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/girl/voice/voice_Insert 18.wav")
			};
			randomSoundAudioClip4.soundType = DiversitySoundManager.SoundType.DressGirlSpeech;
			randomSoundAudioClip4.audioClips = audioClips4;
			DiversityAssets.RandomSoundAudioClip randomSoundAudioClip5 = new DiversityAssets.RandomSoundAudioClip();
			AudioClip[] audioClips5 = (AudioClip[])(object)new AudioClip[4]
			{
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/walker/audios/footsteps/step1.ogg"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/walker/audios/footsteps/step2.ogg"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/walker/audios/footsteps/step3.ogg"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/walker/audios/footsteps/step4.ogg")
			};
			randomSoundAudioClip5.soundType = DiversitySoundManager.SoundType.WalkerFootStep;
			randomSoundAudioClip5.audioClips = audioClips5;
			DiversityAssets.RandomSoundAudioClip randomSoundAudioClip6 = new DiversityAssets.RandomSoundAudioClip();
			AudioClip[] audioClips6 = (AudioClip[])(object)new AudioClip[2]
			{
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/walker/audios/DoorBash/DoorSlam1.ogg"),
				Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/walker/audios/DoorBash/DoorSlam2.ogg")
			};
			randomSoundAudioClip6.soundType = DiversitySoundManager.SoundType.DoorSlam;
			randomSoundAudioClip6.audioClips = audioClips6;
			diversityAssets.soundAudioClipArray[0] = soundAudioClip;
			diversityAssets.soundAudioClipArray[1] = soundAudioClip2;
			diversityAssets.soundAudioClipArray[2] = soundAudioClip3;
			diversityAssets.soundAudioClipArray[3] = soundAudioClip4;
			diversityAssets.randomSoundAudioClipArray[0] = randomSoundAudioClip;
			diversityAssets.randomSoundAudioClipArray[1] = randomSoundAudioClip2;
			diversityAssets.randomSoundAudioClipArray[2] = randomSoundAudioClip3;
			diversityAssets.randomSoundAudioClipArray[3] = randomSoundAudioClip4;
			diversityAssets.randomSoundAudioClipArray[4] = randomSoundAudioClip6;
			diversityAssets.randomSoundAudioClipArray[5] = randomSoundAudioClip5;
			((Object)val).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)val);
			mls.LogInfo((object)"Diversity started.");
		}
	}
	public class DiversityBehaviour : MonoBehaviour
	{
		public int anger = 3;

		private void Update()
		{
		}
	}
}
namespace Diversity.Player
{
	public class PlayerRevamp : MonoBehaviour
	{
		public List<Condition> conditions = new List<Condition>();

		public bool isHaunted = false;

		public bool dressGirlHaunt = false;

		public Light lastLight;

		public int lastID = 0;

		public bool kidnapped = false;

		public float filter = 0f;

		public float dressGirlHauntTime = 0f;

		public float heartBeatInterval = 1f;

		public float voicesTime = 0f;

		public float voicesInterval = 1f;

		public float heartBeatTime = 0f;

		public float heartBeatCooldown = 0f;

		private static float timeElapsed;

		private bool fullDarknessSet = false;

		private bool playersHidden = false;

		public List<Vector3> nearbySounds = new List<Vector3>();

		private float timeFracturedLeg = 0f;

		private float timeFracturedArm = 0f;

		private float timeBleeding = 0f;

		private float timeBlinded = 0f;

		private float soundCheckInterval = 0f;

		private bool instanciated = false;

		public bool updated = false;

		private bool unfinished = false;

		public bool sinkingFromWalker = false;

		private bool currentlySinking = false;

		private float sinkingTime = 0f;

		public bool forceLook = false;

		public Vector3 forceLookPosition = Vector3.zero;

		public void ApplyConditions(DamageType damageType, float modifier)
		{
			Diversity.mls.LogInfo((object)("Player took damage type: " + damageType));
			if (damageType == DamageType.Falling && Configuration.fracturedLeg.Value)
			{
				float value = Random.value;
				if (value <= 0.1f * modifier)
				{
					bool flag = false;
					foreach (Condition condition in conditions)
					{
						if (condition == Condition.FracturedLeg)
						{
							flag = true;
						}
					}
					if (!flag)
					{
						conditions.Add(Condition.FracturedLeg);
						Diversity.mls.LogInfo((object)("Player just received condition:" + Condition.FracturedLeg));
					}
					else if (Configuration.brokenLeg.Value)
					{
						bool flag2 = false;
						foreach (Condition condition2 in conditions)
						{
							if (condition2 == Condition.BrokenLeg)
							{
								flag2 = true;
							}
						}
						if (!flag2)
						{
							conditions.Remove(Condition.FracturedLeg);
							Diversity.mls.LogInfo((object)("Player just lost condition:" + Condition.FracturedLeg));
							conditions.Add(Condition.BrokenLeg);
							Diversity.mls.LogInfo((object)("Player just received condition:" + Condition.BrokenLeg));
						}
					}
				}
			}
			else if ((damageType == DamageType.GunShotted || damageType == DamageType.Mauled || damageType == DamageType.Bitten) && Configuration.bleeding.Value)
			{
				float value2 = Random.value;
				if (value2 <= 0.15f * modifier || damageType == DamageType.GunShotted)
				{
					bool flag3 = false;
					foreach (Condition condition3 in conditions)
					{
						if (condition3 == Condition.Bleeding)
						{
							flag3 = true;
						}
					}
					if (!flag3)
					{
						conditions.Add(Condition.Bleeding);
						Diversity.mls.LogInfo((object)("Player just received condition:" + Condition.Bleeding));
					}
				}
			}
			if (damageType == DamageType.Mauled && Configuration.fracturedArm.Value)
			{
				float value3 = Random.value;
				if (value3 <= 0.15f * modifier)
				{
					bool flag4 = false;
					foreach (Condition condition4 in conditions)
					{
						if (condition4 == Condition.FracturedArm)
						{
							flag4 = true;
						}
					}
					if (!flag4)
					{
						conditions.Add(Condition.FracturedArm);
						Diversity.mls.LogInfo((object)("Player just received condition:" + Condition.FracturedArm));
					}
					if (flag4 && value3 <= 0.05f && Configuration.brokenArm.Value)
					{
						bool flag5 = false;
						foreach (Condition condition5 in conditions)
						{
							if (condition5 == Condition.BrokenArm)
							{
								flag5 = true;
							}
						}
						if (!flag5)
						{
							conditions.Remove(Condition.FracturedArm);
							Diversity.mls.LogInfo((object)("Player just lost condition:" + Condition.FracturedArm));
							conditions.Add(Condition.BrokenArm);
							Diversity.mls.LogInfo((object)("Player just received condition:" + Condition.BrokenArm));
						}
					}
				}
			}
			if (damageType == DamageType.Gas && Configuration.blindness.Value)
			{
				float value4 = Random.value;
				if (value4 <= 0.15f * modifier)
				{
					bool flag6 = false;
					foreach (Condition condition6 in conditions)
					{
						if (condition6 == Condition.Blindness)
						{
							flag6 = true;
						}
					}
					if (!flag6)
					{
						conditions.Add(Condition.Blindness);
						Diversity.mls.LogInfo((object)("Player just received condition:" + Condition.Blindness));
					}
				}
			}
			if (damageType != DamageType.Concussed || !Configuration.concussed.Value)
			{
				return;
			}
			float value5 = Random.value;
			if (!(value5 <= 0.35f * modifier))
			{
				return;
			}
			bool flag7 = false;
			foreach (Condition condition7 in conditions)
			{
				if (condition7 == Condition.Concussed)
				{
					flag7 = true;
				}
			}
			if (!flag7)
			{
				conditions.Add(Condition.Concussed);
				Diversity.mls.LogInfo((object)("Player just received condition:" + Condition.Concussed));
			}
		}

		public void CheckConditions(PlayerControllerB player)
		{
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			if (!Configuration.playerConditions.Value || !player.AllowPlayerDeath())
			{
				return;
			}
			using List<Condition>.Enumerator enumerator = conditions.ToList().GetEnumerator();
			while (enumerator.MoveNext())
			{
				switch (enumerator.Current)
				{
				case Condition.FracturedLeg:
					if (((NetworkBehaviour)player).IsOwner)
					{
						timeFracturedLeg += Time.deltaTime;
						if (timeFracturedLeg >= Configuration.fracturedLegTime.Value)
						{
							timeFracturedLeg = 0f;
							player.jumpForce = 13f;
							conditions.Remove(Condition.FracturedLeg);
						}
						else
						{
							player.jumpForce = 10f;
						}
					}
					break;
				case Condition.BrokenLeg:
					if (((NetworkBehaviour)player).IsOwner)
					{
						player.playerBodyAnimator.SetBool("Limp", true);
						player.jumpForce = 9f;
					}
					break;
				case Condition.FracturedArm:
					if ((Object)(object)player.currentlyHeldObject != (Object)null)
					{
						timeFracturedArm += Time.deltaTime;
						if (timeFracturedArm >= Configuration.fracturedArmTime.Value)
						{
							conditions.Remove(Condition.FracturedArm);
							timeFracturedArm = 0f;
						}
						GrabbableObject currentlyHeldObject2 = player.currentlyHeldObject;
						if (((NetworkBehaviour)player).IsOwner)
						{
							Item itemProperties3 = currentlyHeldObject2.itemProperties;
							if (itemProperties3.weight > 25f)
							{
								player.DiscardHeldObject(false, (NetworkObject)null, default(Vector3), true);
							}
						}
					}
					else
					{
						if (!((Object)(object)player.currentlyHeldObjectServer != (Object)null))
						{
							break;
						}
						GrabbableObject currentlyHeldObjectServer2 = player.currentlyHeldObjectServer;
						if (((NetworkBehaviour)player).IsOwner)
						{
							Item itemProperties4 = currentlyHeldObjectServer2.itemProperties;
							if (itemProperties4.weight > 25f)
							{
								player.DiscardHeldObject(false, (NetworkObject)null, default(Vector3), true);
							}
						}
					}
					break;
				case Condition.BrokenArm:
					if ((Object)(object)player.currentlyHeldObject != (Object)null)
					{
						GrabbableObject currentlyHeldObject = player.currentlyHeldObject;
						if (((NetworkBehaviour)player).IsOwner)
						{
							Item itemProperties = currentlyHeldObject.itemProperties;
							if (itemProperties.weight > 15f)
							{
								player.DiscardHeldObject(false, (NetworkObject)null, default(Vector3), true);
							}
						}
					}
					else
					{
						if (!((Object)(object)player.currentlyHeldObjectServer != (Object)null))
						{
							break;
						}
						GrabbableObject currentlyHeldObjectServer = player.currentlyHeldObjectServer;
						if (((NetworkBehaviour)player).IsOwner)
						{
							Item itemProperties2 = currentlyHeldObjectServer.itemProperties;
							if (itemProperties2.weight > 15f)
							{
								player.DiscardHeldObject(false, (NetworkObject)null, default(Vector3), true);
							}
						}
					}
					break;
				case Condition.Bleeding:
					if (((NetworkBehaviour)player).IsOwner)
					{
						timeBleeding += Time.deltaTime;
						if (timeBleeding >= Configuration.bleedingTime.Value)
						{
							timeBleeding = 0f;
							player.bleedingHeavily = false;
							conditions.Remove(Condition.Bleeding);
						}
						else
						{
							player.healthRegenerateTimer = 1f;
							player.bleedingHeavily = true;
						}
					}
					break;
				case Condition.Blindness:
				{
					if (!((NetworkBehaviour)player).IsOwner)
					{
						break;
					}
					PlayerControllerB localPlayerController2 = StartOfRound.Instance.localPlayerController;
					if (Object.op_Implicit((Object)(object)localPlayerController2) && (localPlayerController2.playerSteamId == player.playerSteamId || localPlayerController2.actualClientId == player.actualClientId))
					{
						HUDManagerRevamp component2 = ((Component)HUDManager.Instance).gameObject.GetComponent<HUDManagerRevamp>();
						if (!Object.op_Implicit((Object)(object)component2))
						{
							return;
						}
						timeBlinded += Time.deltaTime;
						Diversity.mls.LogInfo((object)(timeBlinded + " >= " + Configuration.blindnessTime.Value));
						if (timeBlinded >= Configuration.blindnessTime.Value)
						{
							timeBlinded = 0f;
							component2.blindnessIntensity = 0f;
							conditions.Remove(Condition.Blindness);
						}
						else
						{
							component2.blindnessIntensity = 1f;
						}
					}
					break;
				}
				case Condition.Concussed:
				{
					if (!((NetworkBehaviour)player).IsOwner)
					{
						break;
					}
					PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
					if (Object.op_Implicit((Object)(object)localPlayerController) && (localPlayerController.playerSteamId == player.playerSteamId || localPlayerController.actualClientId == player.actualClientId))
					{
						HUDManagerRevamp component = ((Component)HUDManager.Instance).gameObject.GetComponent<HUDManagerRevamp>();
						if (!Object.op_Implicit((Object)(object)component))
						{
							return;
						}
						component.concussedIntensity = 1f;
					}
					break;
				}
				}
			}
		}

		private void OnTriggerEnter(Collider col)
		{
			if (((Object)((Component)col).gameObject).name == "RoomCollider" && !updated)
			{
				BrakenRevamp[] array = Object.FindObjectsOfType<BrakenRevamp>();
				BrakenRevamp[] array2 = array;
				foreach (BrakenRevamp brakenRevamp in array2)
				{
					brakenRevamp.kidnapped = true;
				}
				kidnapped = true;
				updated = true;
			}
		}

		private void Update()
		{
			//IL_0585: Unknown result type (might be due to invalid IL or missing references)
			//IL_0595: Unknown result type (might be due to invalid IL or missing references)
			//IL_059a: Unknown result type (might be due to invalid IL or missing references)
			//IL_059f: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_05be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0707: Unknown result type (might be due to invalid IL or missing references)
			//IL_07fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0803: Unknown result type (might be due to invalid IL or missing references)
			//IL_0806: Unknown result type (might be due to invalid IL or missing references)
			//IL_080f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0720: Unknown result type (might be due to invalid IL or missing references)
			//IL_072f: Unknown result type (might be due to invalid IL or missing references)
			//IL_094a: Unknown result type (might be due to invalid IL or missing references)
			//IL_075f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0777: Unknown result type (might be due to invalid IL or missing references)
			//IL_0963: Unknown result type (might be due to invalid IL or missing references)
			//IL_0972: Unknown result type (might be due to invalid IL or missing references)
			//IL_0863: Unknown result type (might be due to invalid IL or missing references)
			//IL_087c: Unknown result type (might be due to invalid IL or missing references)
			//IL_088b: Unknown result type (might be due to invalid IL or missing references)
			//IL_08bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d3: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB component = ((Component)this).gameObject.GetComponent<PlayerControllerB>();
			PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
			HUDManagerRevamp component2 = ((Component)HUDManager.Instance).gameObject.GetComponent<HUDManagerRevamp>();
			if (!Object.op_Implicit((Object)(object)component2) || !Object.op_Implicit((Object)(object)component))
			{
				return;
			}
			if (component.isPlayerDead)
			{
				dressGirlHaunt = false;
			}
			if (Configuration.fullDarkness.Value && (Object)(object)component == (Object)(object)localPlayerController && !fullDarknessSet)
			{
				Diversity.mls.LogInfo((object)("Setting full darkness to local player: " + component.playerUsername));
				component.nightVision.intensity = 366.9317f * (1f - Configuration.fullDarknessIntensity.Value);
				fullDarknessSet = true;
			}
			if (Configuration.dressGirlRevamp.Value && Configuration.dressGirlIsolation.Value)
			{
				if (dressGirlHaunt && component.actualClientId == localPlayerController.actualClientId && !component.isPlayerDead)
				{
					heartBeatTime += Time.deltaTime;
					heartBeatCooldown += Time.deltaTime;
					dressGirlHauntTime += Time.deltaTime;
					voicesTime += Time.deltaTime;
					component2.black.weight = Mathf.Lerp(0f, 1f, dressGirlHauntTime / 19f);
					filter = Mathf.Lerp(0f, 1f, dressGirlHauntTime / 19f);
					if (!playersHidden)
					{
						PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
						foreach (PlayerControllerB val in allPlayerScripts)
						{
							if ((Object)(object)val != (Object)null && val.actualClientId != StartOfRound.Instance.localPlayerController.actualClientId)
							{
								((Component)val).gameObject.SetActive(false);
							}
						}
					}
					heartBeatInterval = Mathf.Lerp(1.5f, 0.5f, dressGirlHauntTime / 19f);
					voicesInterval = Mathf.Lerp(3f, 0.75f, dressGirlHauntTime / 19f);
					if (heartBeatTime >= heartBeatInterval)
					{
						DiversitySoundManager.PlaySoundBypass(DiversitySoundManager.SoundType.HeartBeat, random: false, 1f, 0f);
						heartBeatTime = 0f;
					}
					if (voicesTime >= voicesInterval)
					{
						DiversitySoundManager.PlaySoundBypass(DiversitySoundManager.SoundType.DressGirlSpeech, random: true, Mathf.Lerp(0.6f, 0f, dressGirlHauntTime / 15f), 0f, loop: false, RoundManager.Instance.GetRandomPositionInRadius(((Component)component).transform.position, 6f, 11f, (Random)null));
						voicesTime = 0f;
					}
					playersHidden = true;
				}
				else if ((Object)(object)component == (Object)(object)localPlayerController && !dressGirlHaunt)
				{
					dressGirlHauntTime = 0f;
					component2.black.weight = 0f;
					component2.hauntedIntensity = 0f;
					filter = 0f;
					heartBeatTime = 0f;
					heartBeatCooldown = 0f;
					heartBeatInterval = 1f;
					voicesInterval = 1f;
					voicesTime = 0f;
					if (playersHidden)
					{
						PlayerControllerB[] allPlayerScripts2 = StartOfRound.Instance.allPlayerScripts;
						foreach (PlayerControllerB val2 in allPlayerScripts2)
						{
							if ((Object)(object)val2 != (Object)null && val2.actualClientId != StartOfRound.Instance.localPlayerController.actualClientId)
							{
								((Component)val2).gameObject.SetActive(true);
							}
						}
					}
					playersHidden = false;
				}
			}
			if (sinkingFromWalker)
			{
				sinkingTime += Time.deltaTime;
				if (sinkingTime > 8f)
				{
					sinkingTime = 8f;
				}
				component2.black.weight = Mathf.Lerp(0f, 1f, sinkingTime / 8f);
				filter = Mathf.Lerp(0f, 1f, sinkingTime / 8f);
			}
			else if (!dressGirlHaunt)
			{
				sinkingTime -= Time.deltaTime;
				if (sinkingTime > 5f)
				{
					sinkingTime = 5f;
				}
				else if (sinkingTime < 0f)
				{
					sinkingTime = 0f;
				}
				component2.black.weight = Mathf.Lerp(0f, 1f, sinkingTime / 5f);
				filter = Mathf.Lerp(0f, 1f, sinkingTime / 5f);
			}
			if (!component.isPlayerControlled)
			{
				return;
			}
			if (forceLook)
			{
				Vector3 val3 = forceLookPosition - ((Component)component.gameplayCamera).transform.position;
				Vector3 val4 = ((Component)component.gameplayCamera).transform.InverseTransformDirection(val3);
				Vector2 val5 = default(Vector2);
				((Vector2)(ref val5))..ctor(val4.x, val4.y);
				component.CalculateNormalLookingInput(val5);
			}
			soundCheckInterval += Time.deltaTime;
			if (soundCheckInterval >= 0.5f)
			{
				if (!Object.op_Implicit((Object)(object)StartOfRoundRevamp.Instance) || !Object.op_Implicit((Object)(object)StartOfRound.Instance) || !Object.op_Implicit((Object)(object)StartOfRound.Instance.localPlayerController))
				{
					return;
				}
				foreach (GameObject item in StartOfRoundRevamp.Instance.steamSounds.ToList())
				{
					if (!Object.op_Implicit((Object)(object)item))
					{
						return;
					}
					bool flag = false;
					foreach (Vector3 item2 in nearbySounds.ToList())
					{
						if (item2 == item.transform.position)
						{
							flag = true;
						}
					}
					if (!flag && !instanciated)
					{
						DiversitySoundManager.CheckPosition(StartOfRound.Instance.localPlayerController);
						if (false)
						{
							return;
						}
						float num = Vector3.Distance(item.transform.position, DiversitySoundManager.CheckPosition(StartOfRound.Instance.localPlayerController));
						if (num < 32f)
						{
							DiversitySoundManager.PlaySound(DiversitySoundManager.SoundType.SteamLeak, random: false, 0.1f, 0f, loop: true, item.transform.position);
							nearbySounds.Add(item.transform.position);
							instanciated = true;
						}
					}
				}
				foreach (GameObject item3 in StartOfRoundRevamp.Instance.lightBuzz.ToList())
				{
					if (!Object.op_Implicit((Object)(object)item3))
					{
						return;
					}
					bool flag2 = false;
					foreach (Vector3 item4 in nearbySounds.ToList())
					{
						if (item4 == item3.transform.position)
						{
							flag2 = true;
						}
					}
					if (!flag2 && !instanciated)
					{
						DiversitySoundManager.CheckPosition(StartOfRound.Instance.localPlayerController);
						if (false)
						{
							return;
						}
						float num2 = Vector3.Distance(item3.transform.position, DiversitySoundManager.CheckPosition(StartOfRound.Instance.localPlayerController));
						if (num2 < 32f)
						{
							DiversitySoundManager.PlaySound(DiversitySoundManager.SoundType.LightBuzz, random: false, 0.4f, 0f, loop: true, item3.transform.position);
							nearbySounds.Add(item3.transform.position);
							instanciated = true;
						}
					}
				}
				foreach (GameObject item5 in DiversitySoundManager.Instance.current3Daudios.ToList())
				{
					if (!Object.op_Implicit((Object)(object)item5))
					{
						return;
					}
					DiversitySoundManager.CheckPosition(StartOfRound.Instance.localPlayerController);
					if (false)
					{
						return;
					}
					float num3 = Vector3.Distance(item5.transform.position, DiversitySoundManager.CheckPosition(StartOfRound.Instance.localPlayerController));
					if (num3 > 36f)
					{
						Object.Destroy((Object)(object)item5);
						DiversitySoundManager.Instance.current3Daudios.Remove(item5);
					}
				}
				soundCheckInterval = 0f;
				instanciated = false;
			}
			if (Object.op_Implicit((Object)(object)lastLight))
			{
				if (!isHaunted)
				{
					if (!unfinished)
					{
						if (timeElapsed != 1f)
						{
							timeElapsed = 1f - timeElapsed;
						}
						else
						{
							timeElapsed = 0f;
						}
						unfinished = true;
					}
					if (lastID == 0)
					{
						lastLight.intensity = Mathf.Lerp(100f, 486.8536f, timeElapsed / 1f);
					}
					else if (lastID == 1)
					{
						lastLight.intensity = Mathf.Lerp(50f, 397.9603f, timeElapsed / 1f);
					}
					timeElapsed += Time.deltaTime;
				}
				if (isHaunted)
				{
					if (unfinished)
					{
						if (timeElapsed != 1f)
						{
							timeElapsed = 1f - timeElapsed;
						}
						else
						{
							timeElapsed = 0f;
						}
						unfinished = false;
					}
					if (lastID == 0)
					{
						lastLight.intensity = Mathf.Lerp(486.8536f, 100f, timeElapsed / 1f);
					}
					else if (lastID == 1)
					{
						lastLight.intensity = Mathf.Lerp(397.9603f, 50f, timeElapsed / 1f);
					}
					timeElapsed += Time.deltaTime;
				}
				if (timeElapsed >= 1f)
				{
					timeElapsed = 1f;
				}
			}
			GrabbableObject[] itemSlots = component.ItemSlots;
			foreach (GrabbableObject val6 in itemSlots)
			{
				if ((Object)(object)val6 != (Object)null)
				{
					FlashlightRevamp component3 = ((Component)val6).gameObject.GetComponent<FlashlightRevamp>();
					if (Object.op_Implicit((Object)(object)component3))
					{
						component3.haunted = isHaunted;
					}
				}
			}
			if (sinkingFromWalker)
			{
				component.sourcesCausingSinking = 1;
				component.sinkingSpeedMultiplier = 0.1f;
			}
			else
			{
				component.sourcesCausingSinking = 0;
				component.sinkingSpeedMultiplier = 0f;
			}
			if (dressGirlHaunt)
			{
				if (component.actualClientId == localPlayerController.actualClientId || component.playerSteamId == localPlayerController.playerSteamId)
				{
					component2.hauntedIntensity = 1f;
				}
			}
			else if (component.actualClientId == localPlayerController.actualClientId || component.playerSteamId == localPlayerController.playerSteamId)
			{
				component2.hauntedIntensity = 0f;
			}
		}
	}
}
namespace Diversity.Patches
{
	[HarmonyPatch(typeof(BaboonBirdAI))]
	internal class BaboonBirdAIPatch
	{
		[HarmonyPatch(typeof(BaboonBirdAI), "OnCollideWithPlayer")]
		[HarmonyPrefix]
		private static void OnCollideWithPlayer(BaboonBirdAI __instance, Collider other)
		{
			if (__instance.timeSinceHitting < 0.5f)
			{
				return;
			}
			PlayerControllerB val = ((EnemyAI)__instance).MeetsStandardPlayerCollisionConditions(other, ((EnemyAI)__instance).inSpecialAnimation || __instance.doingKillAnimation, false);
			if ((Object)(object)val != (Object)null)
			{
				PlayerRevamp component = ((Component)val).gameObject.GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ApplyConditions(DamageType.Bitten, 1f + (1f - (float)(val.health / 100)));
				}
			}
		}
	}
	[HarmonyPatch(typeof(BlobAI))]
	internal class BlobAIPatch
	{
		[HarmonyPatch(typeof(BlobAI), "OnCollideWithPlayer")]
		[HarmonyPrefix]
		private static void OnCollideWithPlayer(BlobAI __instance, Collider other)
		{
			if (__instance.timeSinceHittingLocalPlayer < 0.25f || (__instance.tamedTimer > 0f && __instance.angeredTimer < 0f))
			{
				return;
			}
			PlayerControllerB val = ((EnemyAI)__instance).MeetsStandardPlayerCollisionConditions(other, false, false);
			if ((Object)(object)val != (Object)null)
			{
				PlayerRevamp component = ((Component)val).gameObject.GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ApplyConditions(DamageType.Burned, 1f + (1f - (float)(val.health / 100)));
				}
			}
		}
	}
	[HarmonyPatch(typeof(BreakerBox))]
	internal class BreakerBoxPatch : MonoBehaviour
	{
		[HarmonyPatch(typeof(BreakerBox), "Start")]
		[HarmonyPostfix]
		public static void Start(BreakerBox __instance)
		{
			BreakerBoxRevamp component = ((Component)__instance).gameObject.GetComponent<BreakerBoxRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				((Component)__instance).gameObject.AddComponent<BreakerBoxRevamp>();
				Diversity.mls.LogInfo((object)"Added DiversityBehaviour to the RoundManager.");
			}
		}

		[HarmonyPatch(typeof(BreakerBox), "SwitchBreaker")]
		[HarmonyPostfix]
		public static void SwitchBreaker(BreakerBox __instance)
		{
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			int num = 3;
			BreakerBoxRevamp component = ((Component)__instance).gameObject.GetComponent<BreakerBoxRevamp>();
			if (Object.op_Implicit((Object)(object)component))
			{
				num = component.anger;
			}
			Diversity.mls.LogInfo((object)("angerMax: " + num));
			if (!Configuration.brakenAnger.Value || !__instance.isPowerOn)
			{
				return;
			}
			FlowermanAI[] array = (FlowermanAI[])(object)Object.FindObjectsOfType(typeof(FlowermanAI));
			if (!Configuration.brakenRevamp.Value)
			{
				return;
			}
			FlowermanAI[] array2 = array;
			foreach (FlowermanAI val in array2)
			{
				BrakenRevamp component2 = ((Component)val).gameObject.GetComponent<BrakenRevamp>();
				if (!Object.op_Implicit((Object)(object)component2))
				{
					break;
				}
				if (component2.angerLevel < num)
				{
					component2.angerLevel++;
				}
				PlayerControllerB[] allPlayerScripts = __instance.roundManager.playersManager.allPlayerScripts;
				float num2 = 100f;
				PlayerControllerB val2 = null;
				PlayerControllerB[] array3 = allPlayerScripts;
				foreach (PlayerControllerB val3 in array3)
				{
					if ((Object)(object)val3 != (Object)null && Vector3.Distance(((Component)__instance).gameObject.transform.position, ((Component)val3).gameObject.transform.position) < num2)
					{
						num2 = Vector3.Distance(((Component)__instance).gameObject.transform.position, ((Component)val3).gameObject.transform.position);
						val2 = val3;
					}
				}
				if ((Object)(object)val2 != (Object)null)
				{
					Diversity.mls.LogInfo((object)("Closest player from breaker box is: " + ((Object)((Component)val2).gameObject).name));
				}
				component2.CheckAnger(component, __instance.roundManager, val2);
			}
		}
	}
	[HarmonyPatch(typeof(CentipedeAI))]
	internal class CentipedeAIPatch
	{
		[HarmonyPatch(typeof(CentipedeAI), "Start")]
		[HarmonyPrefix]
		public static void Start(CentipedeAI __instance)
		{
			if (Configuration.centipedeRevamp.Value)
			{
				CentipedeRevamp component = ((Component)__instance).gameObject.GetComponent<CentipedeRevamp>();
				if (!Object.op_Implicit((Object)(object)component))
				{
					((Component)__instance).gameObject.AddComponent<CentipedeRevamp>();
					Diversity.mls.LogInfo((object)("Added CentipedeRevamp to: " + ((Object)((Component)__instance).gameObject).name));
				}
			}
		}

		[HarmonyPatch(typeof(CentipedeAI), "DamagePlayerOnIntervals")]
		[HarmonyPrefix]
		private static void DamagePlayerOnIntervals(CentipedeAI __instance)
		{
			if (__instance.damagePlayerInterval <= 0f && !__instance.inDroppingOffPlayerAnim && !(((EnemyAI)__instance).stunNormalizedTimer > 0f) && (StartOfRound.Instance.connectedPlayersAmount > 0 || __instance.clingingToPlayer.health > 15 || __instance.singlePlayerSecondChanceGiven) && (Object)(object)__instance.clingingToPlayer != (Object)null)
			{
				PlayerRevamp component = ((Component)__instance.clingingToPlayer).gameObject.GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ApplyConditions(DamageType.Mauled, 1f + (1f - (float)(__instance.clingingToPlayer.health / 100)));
				}
			}
		}
	}
	[HarmonyPatch(typeof(CrawlerAI))]
	internal class CrawlerAIPatch
	{
		private static CrawlerRevamp crawler;

		[HarmonyPatch(typeof(CrawlerAI), "HitEnemy")]
		[HarmonyPrefix]
		public static void Slow(CrawlerAI __instance)
		{
			if (Configuration.crawlerRevamp.Value)
			{
				crawler = ((Component)__instance).GetComponent<CrawlerRevamp>();
				if (Object.op_Implicit((Object)(object)crawler) && !crawler.onCooldown)
				{
					crawler.hasBeenhit = true;
					crawler.onCooldown = true;
					crawler.previousAgentSpeed = ((EnemyAI)__instance).agent.speed;
					crawler.previousAgentAcceleration = ((EnemyAI)__instance).agent.acceleration;
					crawler.currentAgentSpeed = ((EnemyAI)__instance).agent.speed;
					crawler.currentAgentAcceleration = ((EnemyAI)__instance).agent.acceleration;
					Diversity.mls.LogInfo((object)"Crawler hit!");
				}
			}
		}

		[HarmonyPatch(typeof(CrawlerAI), "Start")]
		[HarmonyPrefix]
		public static void Start(CrawlerAI __instance)
		{
			if (Configuration.crawlerRevamp.Value)
			{
				crawler = ((Component)__instance).gameObject.GetComponent<CrawlerRevamp>();
				if (!Object.op_Implicit((Object)(object)crawler))
				{
					((Component)__instance).gameObject.AddComponent<CrawlerRevamp>();
					Diversity.mls.LogInfo((object)("Added CrawlerRevamp to: " + ((Object)((Component)__instance).gameObject).name));
				}
			}
		}

		[HarmonyPatch(typeof(CrawlerAI), "OnCollideWithPlayer")]
		[HarmonyPrefix]
		private static void OnCollideWithPlayer(CrawlerAI __instance, Collider other)
		{
			if (__instance.timeSinceHittingPlayer < 0.65f)
			{
				return;
			}
			PlayerControllerB val = ((EnemyAI)__instance).MeetsStandardPlayerCollisionConditions(other, false, false);
			if ((Object)(object)val != (Object)null)
			{
				PlayerRevamp component = ((Component)val).gameObject.GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ApplyConditions(DamageType.Bitten, 1f + (1f - (float)(val.health / 100)));
				}
			}
		}
	}
	[HarmonyPatch(typeof(DressGirlAI))]
	internal class DressGirlAIPatch
	{
		[HarmonyPatch(typeof(DressGirlAI), "Start")]
		[HarmonyPrefix]
		private static void Start(DressGirlAI __instance)
		{
			if (Configuration.dressGirlRevamp.Value)
			{
				DressGirlRevamp component = ((Component)__instance).gameObject.GetComponent<DressGirlRevamp>();
				if (!Object.op_Implicit((Object)(object)component))
				{
					((Component)__instance).gameObject.AddComponent<DressGirlRevamp>();
					Diversity.mls.LogInfo((object)("Added DressGirlRevamp to: " + ((Object)((Component)__instance).gameObject).name));
				}
			}
		}

		[HarmonyPatch(typeof(DressGirlAI), "Update")]
		[HarmonyPostfix]
		private static void Update(DressGirlAI __instance)
		{
			if (Configuration.dressGirlRevamp.Value)
			{
				DressGirlRevamp component = ((Component)__instance).gameObject.GetComponent<DressGirlRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.timeElapsed += Time.deltaTime;
					component.TryWalkieTalkie(__instance.hauntingPlayer);
				}
			}
		}

		[HarmonyPatch(typeof(DressGirlAI), "BeginChasing")]
		[HarmonyPostfix]
		private static void BeginChasing(DressGirlAI __instance)
		{
			if (Configuration.dressGirlRevamp.Value && Configuration.dressGirlIsolation.Value && !((Object)(object)__instance.hauntingPlayer == (Object)null))
			{
				PlayerRevamp component = ((Component)__instance.hauntingPlayer).GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.dressGirlHaunt = true;
				}
			}
		}

		[HarmonyPatch(typeof(DressGirlAI), "StopChasing")]
		[HarmonyPostfix]
		private static void StopChasing(DressGirlAI __instance)
		{
			if (!Configuration.dressGirlRevamp.Value || !Configuration.dressGirlIsolation.Value || (Object)(object)__instance.hauntingPlayer == (Object)null)
			{
				return;
			}
			PlayerRevamp component = ((Component)__instance.hauntingPlayer).GetComponent<PlayerRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return;
			}
			component.dressGirlHaunt = false;
			DiversitySoundManager.StopSoundBypass();
			if (DiversitySoundManager.Instance.currentGirlAudios.Count <= 0)
			{
				return;
			}
			foreach (GameObject item in DiversitySoundManager.Instance.currentGirlAudios.ToList())
			{
				item.GetComponent<AudioSource>().Stop();
				DiversitySoundManager.DeleteAudio(item);
				DiversitySoundManager.Instance.currentGirlAudios.Remove(item);
			}
		}
	}
	[HarmonyPatch(typeof(FlashlightItem))]
	public class FlashlightPatch : MonoBehaviour
	{
		private static bool wasHaunted;

		private static float timeElapsed;

		[HarmonyPatch(typeof(FlashlightItem), "Update")]
		[HarmonyPostfix]
		private static void Update(FlashlightItem __instance)
		{
			if (!Configuration.brakenRevamp.Value)
			{
				return;
			}
			FlashlightRevamp component = ((Component)__instance).gameObject.GetComponent<FlashlightRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return;
			}
			if (component.haunted)
			{
				if (!wasHaunted)
				{
					wasHaunted = true;
				}
				__instance.flashlightBulb.intensity = component.currentIntensity;
				timeElapsed = 0f;
			}
			else
			{
				timeElapsed += Time.deltaTime;
				if (timeElapsed >= 1f)
				{
					wasHaunted = false;
				}
			}
		}

		[HarmonyPatch(typeof(FlashlightItem), "Start")]
		[HarmonyPrefix]
		public static void Start(FlashlightItem __instance)
		{
			if (Configuration.brakenRevamp.Value)
			{
				FlashlightRevamp component = ((Component)__instance).gameObject.GetComponent<FlashlightRevamp>();
				Rigidbody component2 = ((Component)__instance).gameObject.GetComponent<Rigidbody>();
				if (!Object.op_Implicit((Object)(object)component))
				{
					((Component)__instance).gameObject.AddComponent<FlashlightRevamp>();
					Diversity.mls.LogInfo((object)("Added FlashlightRevamp to: " + ((Object)((Component)__instance).gameObject).name));
				}
				if (!Object.op_Implicit((Object)(object)component2))
				{
					Rigidbody val = ((Component)__instance).gameObject.AddComponent<Rigidbody>();
					val.isKinematic = true;
					Diversity.mls.LogInfo((object)("Added Rigidbody to: " + ((Object)((Component)__instance).gameObject).name));
				}
			}
		}
	}
	[HarmonyPatch(typeof(FlowermanAI))]
	internal class FlowermanAIPatch
	{
		[HarmonyPatch(typeof(FlowermanAI), "Start")]
		[HarmonyPrefix]
		public static void Start(FlowermanAI __instance)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			if (Configuration.brakenRevamp.Value)
			{
				BrakenRevamp component = ((Component)__instance).gameObject.GetComponent<BrakenRevamp>();
				if (!Object.op_Implicit((Object)(object)component))
				{
					((Component)__instance).gameObject.AddComponent<BrakenRevamp>();
					Diversity.mls.LogInfo((object)("Added BrakenRevamp to: " + ((Object)((Component)__instance).gameObject).name));
				}
				GameObject val = new GameObject("CreatureSpeech");
				AudioSource val2 = val.AddComponent<AudioSource>();
				val2.loop = false;
				((Behaviour)val2).enabled = true;
				val2.playOnAwake = false;
				val2.volume = 1f;
				val2.spatialBlend = 0f;
				val2.clip = Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/bracken/you're next.mp3");
				val.transform.SetParent(((Component)__instance).gameObject.transform);
				Diversity.mls.LogInfo((object)("Added CreatureSpeech to: " + ((Object)((Component)__instance).gameObject).name));
			}
		}

		[HarmonyPatch(typeof(FlowermanAI), "killAnimation")]
		[HarmonyPostfix]
		private static void killAnimation(FlowermanAI __instance)
		{
			if (!Configuration.brakenRevamp.Value || !((Object)(object)((EnemyAI)__instance).inSpecialAnimationWithPlayer != (Object)null))
			{
				return;
			}
			Transform val = ((Component)__instance).gameObject.transform.Find("CreatureSpeech");
			if (Object.op_Implicit((Object)(object)val))
			{
				AudioSource component = ((Component)val).GetComponent<AudioSource>();
				BrakenRevamp component2 = ((Component)__instance).gameObject.GetComponent<BrakenRevamp>();
				if (Object.op_Implicit((Object)(object)component2))
				{
					component2.TransmitWalkie(component.clip);
				}
			}
		}

		[HarmonyPatch(typeof(FlowermanAI), "OnCollideWithPlayer")]
		[HarmonyPrefix]
		private static void OnCollideWithPlayer(FlowermanAI __instance, Collider other)
		{
			if (!Configuration.brakenSpace.Value)
			{
				return;
			}
			BrakenRevamp component = ((Component)__instance).gameObject.GetComponent<BrakenRevamp>();
			StartOfRoundRevamp component2 = ((Component)StartOfRound.Instance).gameObject.GetComponent<StartOfRoundRevamp>();
			PlayerControllerB val = ((EnemyAI)__instance).MeetsStandardPlayerCollisionConditions(other, __instance.inKillAnimation || __instance.startingKillAnimationLocalClient || __instance.carryingPlayerBody, false);
			if ((Object)(object)val != (Object)null && Object.op_Implicit((Object)(object)component) && !component.kidnapped)
			{
				component.kidnapped = true;
				if (Object.op_Implicit((Object)(object)component2))
				{
					component2.Kidnap(val);
					StartOfRound.Instance.allowLocalPlayerDeath = false;
					((Component)((Component)val).gameObject.transform.Find("Misc").Find("MapDot")).gameObject.SetActive(false);
					component.ResetAnimation(__instance);
				}
			}
		}
	}
	[HarmonyPatch(typeof(HoarderBugAI))]
	internal class HoarderBugAIPatch
	{
		[HarmonyPatch(typeof(HoarderBugAI), "OnCollideWithPlayer")]
		[HarmonyPrefix]
		private static void OnCollideWithPlayer(HoarderBugAI __instance, Collider other)
		{
			if (!__instance.inChase || __instance.timeSinceHittingPlayer < 0.5f)
			{
				return;
			}
			PlayerControllerB val = ((EnemyAI)__instance).MeetsStandardPlayerCollisionConditions(other, false, false);
			if ((Object)(object)val != (Object)null)
			{
				PlayerRevamp component = ((Component)val).gameObject.GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ApplyConditions(DamageType.Mauled, 1f + (1f - (float)(val.health / 100)));
				}
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	public class HUDPatch
	{
		public static TextMeshProUGUI tipText;

		public static Image holderBar;

		public static Image clickBar;

		private static readonly string text = "Free from head : [E]";

		private static readonly Color color = Color32.op_Implicit(new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue));

		[HarmonyPatch(typeof(HUDManager), "Start")]
		[HarmonyPostfix]
		private static void Start(ref HUDManager __instance)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Expected O, but got Unknown
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("InteractText");
			val.AddComponent<RectTransform>();
			TextMeshProUGUI val2 = val.AddComponent<TextMeshProUGUI>();
			RectTransform rectTransform = ((TMP_Text)val2).rectTransform;
			((Transform)rectTransform).SetParent(((TMP_Text)__instance.signalTranslatorText).transform, false);
			Rect rect = rectTransform.rect;
			rectTransform.anchoredPosition = new Vector2((0f - ((Rect)(ref rect)).width) / 4f + 5f, -40f);
			GameObject val3 = new GameObject("InteractBarHolder");
			val3.AddComponent<RectTransform>();
			Image val4 = val3.AddComponent<Image>();
			val4.sprite = Content.MainAssets.LoadAsset<Sprite>("Assets/custom/diversity/hud/holder.png");
			RectTransform component = ((Component)val4).GetComponent<RectTransform>();
			((Transform)component).SetParent(((TMP_Text)__instance.signalTranslatorText).transform, false);
			component.sizeDelta = new Vector2(133.33333f, 20f);
			rect = rectTransform.rect;
			component.anchoredPosition = new Vector2((0f - ((Rect)(ref rect)).width) / 4f + 5f, -70f);
			((Behaviour)val4).enabled = false;
			holderBar = val4;
			GameObject val5 = new GameObject("InteractBarHolder");
			val5.AddComponent<RectTransform>();
			Image val6 = val5.AddComponent<Image>();
			val6.sprite = Content.MainAssets.LoadAsset<Sprite>("Assets/custom/diversity/hud/bar.png");
			RectTransform component2 = ((Component)val6).GetComponent<RectTransform>();
			((Transform)component2).SetParent(((TMP_Text)__instance.signalTranslatorText).transform, false);
			component2.sizeDelta = new Vector2(133.33333f, 20f);
			rect = rectTransform.rect;
			component2.anchoredPosition = new Vector2((0f - ((Rect)(ref rect)).width) / 4f + 5f, -70f);
			((Behaviour)val6).enabled = false;
			clickBar = val6;
			((TMP_Text)val2).alignment = (TextAlignmentOptions)514;
			((TMP_Text)val2).font = ((TMP_Text)__instance.controlTipLines[0]).font;
			((TMP_Text)val2).fontSize = 16f;
			((TMP_Text)val2).text = text;
			((Graphic)val2).color = color;
			((TMP_Text)val2).overflowMode = (TextOverflowModes)0;
			((Behaviour)val2).enabled = false;
			tipText = val2;
			HUDManagerRevamp component3 = ((Component)__instance).gameObject.GetComponent<HUDManagerRevamp>();
			if (!Object.op_Implicit((Object)(object)component3))
			{
				((Component)__instance).gameObject.AddComponent<HUDManagerRevamp>();
				Diversity.mls.LogInfo((object)("Added HUDManagerRevamp to: " + ((Object)((Component)__instance).gameObject).name));
			}
		}

		[HarmonyPatch(typeof(HUDManager), "UnderwaterScreenFilters")]
		[HarmonyPostfix]
		private static void UnderwaterScreenFilters(HUDManager __instance)
		{
			PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController;
			if (!Object.op_Implicit((Object)(object)localPlayerController))
			{
				return;
			}
			PlayerRevamp component = ((Component)localPlayerController).gameObject.GetComponent<PlayerRevamp>();
			if (Object.op_Implicit((Object)(object)component))
			{
				if (component.filter > 0f)
				{
					((Behaviour)__instance.audioListenerLowPass).enabled = true;
					__instance.audioListenerLowPass.cutoffFrequency = 20000f * (1f - component.filter);
				}
				else
				{
					((Behaviour)__instance.audioListenerLowPass).enabled = false;
					__instance.audioListenerLowPass.cutoffFrequency = 20000f * (1f - component.filter);
				}
			}
		}
	}
	[HarmonyPatch(typeof(LungProp))]
	internal class LungPropPatch
	{
		[HarmonyPatch(typeof(LungProp), "Start")]
		[HarmonyPrefix]
		private static void Start(LungProp __instance)
		{
			if (Configuration.brakenRevamp.Value)
			{
				LungPropRevamp component = ((Component)__instance).gameObject.GetComponent<LungPropRevamp>();
				if (!Object.op_Implicit((Object)(object)component))
				{
					((Component)__instance).gameObject.AddComponent<LungPropRevamp>();
					Diversity.mls.LogInfo((object)("Added LungPropRevamp to: " + ((Object)((Component)__instance).gameObject).name));
				}
			}
		}

		[HarmonyPatch(typeof(LungProp), "DisconnectFromMachinery")]
		[HarmonyPostfix]
		private static void DisconnectFromMachinery(LungProp __instance)
		{
			if (Configuration.brakenRevamp.Value && Configuration.apparatusAnger.Value)
			{
				LungPropRevamp component = ((Component)__instance).gameObject.GetComponent<LungPropRevamp>();
				if (Object.op_Implicit((Object)(object)component) && (Object)(object)((GrabbableObject)__instance).playerHeldBy != (Object)null)
				{
					component.AngerBracken(__instance.roundManager, ((GrabbableObject)__instance).playerHeldBy);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ManualCameraRenderer))]
	internal class ManualCameraRendererPatch
	{
		[HarmonyPatch(typeof(ManualCameraRenderer), "MapCameraFocusOnPosition")]
		[HarmonyPostfix]
		private static void MapCameraFocusOnPosition(ManualCameraRenderer __instance)
		{
			if (!Configuration.brakenSpace.Value || !Object.op_Implicit((Object)(object)__instance.targetedPlayer))
			{
				return;
			}
			PlayerRevamp component = ((Component)__instance.targetedPlayer).gameObject.GetComponent<PlayerRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return;
			}
			if (component.kidnapped)
			{
				if (__instance.isScreenOn)
				{
					((Behaviour)StartOfRound.Instance.mapScreenPlayerName).enabled = false;
					__instance.mapCamera.cullingMask = LayerMask.GetMask(new string[1] { "MapRadar" });
					Transform val = ((TMP_Text)StartOfRound.Instance.mapScreenPlayerName).transform.parent.Find("ErrorText");
					if (Object.op_Implicit((Object)(object)val))
					{
						((Component)val).gameObject.SetActive(true);
					}
				}
			}
			else if (__instance.isScreenOn)
			{
				((Behaviour)StartOfRound.Instance.mapScreenPlayerName).enabled = true;
				__instance.mapCamera.cullingMask = 16640;
				Transform val2 = ((TMP_Text)StartOfRound.Instance.mapScreenPlayerName).transform.parent.Find("ErrorText");
				if (Object.op_Implicit((Object)(object)val2))
				{
					((Component)val2).gameObject.SetActive(false);
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	public class PlayerControllerBPatch
	{
		public static Transform InteractorSource;

		private static float InteractRange = Configuration.interactRange.Value;

		public static PlayerControllerB player;

		private static CentipedeRevamp revamp;

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPrefix]
		public static void Start(PlayerControllerB __instance)
		{
			PlayerRevamp component = ((Component)__instance).gameObject.GetComponent<PlayerRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				((Component)__instance).gameObject.AddComponent<PlayerRevamp>();
				Diversity.mls.LogInfo((object)("Added PlayerRevamp to: " + ((Object)((Component)__instance).gameObject).name));
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "CheckConditionsForSinkingInQuicksand")]
		[HarmonyPrefix]
		private static bool CheckConditionsForSinkingInQuicksand(PlayerControllerB __instance, ref bool __result)
		{
			PlayerRevamp component = ((Component)__instance).gameObject.GetComponent<PlayerRevamp>();
			if (component.sinkingFromWalker)
			{
				__result = true;
				return false;
			}
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		private static void Update(PlayerControllerB __instance)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0475: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ac: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance.currentlyHeldObject != (Object)null && Object.op_Implicit((Object)(object)((Component)__instance.currentlyHeldObject).GetComponent<FlashlightItem>()) && Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponent<PlayerRevamp>()))
			{
				((Component)__instance).gameObject.GetComponent<PlayerRevamp>().lastID = ((Component)__instance.currentlyHeldObject).GetComponent<FlashlightItem>().flashlightTypeID;
			}
			if ((Object)(object)__instance == (Object)(object)StartOfRound.Instance.localPlayerController)
			{
				MovementActions movement = __instance.playerActions.Movement;
				if (((MovementActions)(ref movement)).Interact.WasPressedThisFrame())
				{
					InteractorSource = ((Component)__instance.gameplayCamera).transform;
					Ray val = default(Ray);
					((Ray)(ref val))..ctor(InteractorSource.position, InteractorSource.forward);
					RaycastHit val2 = default(RaycastHit);
					if (Physics.Raycast(val, ref val2, InteractRange, LayerMask.GetMask(new string[4] { "Enemies", "Room", "Terrain", "Railing" })))
					{
						Diversity.mls.LogInfo((object)("Interactor interacted with: " + ((Object)((Component)((RaycastHit)(ref val2)).transform).gameObject).name));
						if (((Object)((Component)((RaycastHit)(ref val2)).transform).gameObject).name == "brackendoor")
						{
							BrackenDoor component = ((Component)((RaycastHit)(ref val2)).transform).gameObject.GetComponent<BrackenDoor>();
							if (!Object.op_Implicit((Object)(object)component))
							{
								return;
							}
							component.CheckClicks(__instance);
						}
						else if (Configuration.centipedeRevamp.Value)
						{
							try
							{
								revamp = ((Component)((Component)((RaycastHit)(ref val2)).collider).transform.parent).gameObject.GetComponent<CentipedeRevamp>();
							}
							catch (Exception)
							{
							}
							if (!Object.op_Implicit((Object)(object)revamp))
							{
								return;
							}
							Diversity.mls.LogInfo((object)("Centipede clinging: " + revamp.clinging));
							Diversity.mls.LogInfo((object)("Amount of click done: " + revamp.clicks));
							if (revamp.clinging)
							{
								revamp.clicks++;
								float value = Random.value;
								if (value < (float)(Configuration.hurtChance.Value / 100))
								{
									__instance.DamagePlayer(5, true, true, (CauseOfDeath)6, 0, false, default(Vector3));
								}
							}
						}
					}
				}
			}
			if ((Object)(object)__instance == (Object)(object)StartOfRound.Instance.localPlayerController)
			{
				InteractorSource = ((Component)__instance.gameplayCamera).transform;
				Ray val3 = default(Ray);
				((Ray)(ref val3))..ctor(InteractorSource.position, InteractorSource.forward);
				RaycastHit val4 = default(RaycastHit);
				if (Physics.Raycast(val3, ref val4, InteractRange, LayerMask.GetMask(new string[4] { "Enemies", "Room", "Terrain", "Railing" })))
				{
					if (((Object)((Component)((RaycastHit)(ref val4)).transform).gameObject).name == "brackendoor")
					{
						BrackenDoor component2 = ((Component)((RaycastHit)(ref val4)).transform).gameObject.GetComponent<BrackenDoor>();
						if (!Object.op_Implicit((Object)(object)component2))
						{
							return;
						}
						((Behaviour)HUDPatch.tipText).enabled = true;
						((TMP_Text)HUDPatch.tipText).text = "Break out! : [E]";
						((Behaviour)HUDPatch.holderBar).enabled = true;
						((Behaviour)HUDPatch.clickBar).enabled = true;
						((Graphic)HUDPatch.clickBar).rectTransform.sizeDelta = new Vector2(8f * (float)component2.clicks / 1.5f, 20f);
					}
					else
					{
						try
						{
							revamp = ((Component)((Component)((RaycastHit)(ref val4)).collider).transform.parent).gameObject.GetComponent<CentipedeRevamp>();
						}
						catch (Exception)
						{
						}
						if (!Object.op_Implicit((Object)(object)revamp))
						{
							return;
						}
						if (revamp.clinging)
						{
							((Behaviour)HUDPatch.tipText).enabled = true;
							((TMP_Text)HUDPatch.tipText).text = "Free from head : [E]";
							((Behaviour)HUDPatch.holderBar).enabled = true;
							((Behaviour)HUDPatch.clickBar).enabled = true;
							((Graphic)HUDPatch.clickBar).rectTransform.sizeDelta = new Vector2((float)(200 / Configuration.clickAmount.Value * revamp.clicks) / 1.5f, 20f);
						}
					}
				}
				else
				{
					((Behaviour)HUDPatch.tipText).enabled = false;
					((Behaviour)HUDPatch.holderBar).enabled = false;
					((Behaviour)HUDPatch.clickBar).enabled = false;
				}
			}
			if (Configuration.playerConditions.Value)
			{
				PlayerRevamp component3 = ((Component)__instance).gameObject.GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component3))
				{
					component3.CheckConditions(__instance);
				}
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")]
		private static void LateUpdate(PlayerControllerB __instance)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			PlayerRevamp component = ((Component)__instance).gameObject.GetComponent<PlayerRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return;
			}
			if (((Component)__instance).gameObject.transform.position.y > -350f && !__instance.isPlayerDead)
			{
				component.kidnapped = false;
			}
			if (component.kidnapped)
			{
				__instance.sprintMeter = 1f;
				((Component)__instance.mapRadarDotAnimator).gameObject.SetActive(false);
				return;
			}
			((Component)__instance.mapRadarDotAnimator).gameObject.SetActive(true);
			bool flag = false;
			bool flag2 = false;
			using (List<Condition>.Enumerator enumerator = component.conditions.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					switch (enumerator.Current)
					{
					case Condition.FracturedLeg:
						flag = true;
						break;
					case Condition.BrokenLeg:
						flag2 = true;
						break;
					}
				}
			}
			float num = 1f;
			if (__instance.drunkness > 0.02f)
			{
				num *= Mathf.Abs(StartOfRound.Instance.drunknessSpeedEffect.Evaluate(__instance.drunkness) - 1.25f);
			}
			if (flag2)
			{
				if (__instance.isSprinting)
				{
					__instance.sprintMeter = Mathf.Clamp(__instance.sprintMeter - Time.deltaTime / (__instance.sprintTime / 1.5f) * __instance.carryWeight * num, 0f, 1f);
				}
				else if (__instance.isMovementHindered > 0)
				{
					if (__instance.isWalking)
					{
						__instance.sprintMeter = Mathf.Clamp(__instance.sprintMeter - Time.deltaTime / (__instance.sprintTime / 1.5f) * num * 0.5f, 0f, 1f);
					}
				}
				else if (!__instance.isWalking)
				{
					__instance.sprintMeter = Mathf.Clamp(__instance.sprintMeter + Time.deltaTime / (__instance.sprintTime / 1.5f + 4f) * num, 0f, 1f);
				}
				else
				{
					__instance.sprintMeter = Mathf.Clamp(__instance.sprintMeter + Time.deltaTime / (__instance.sprintTime / 1.5f + 9f) * num, 0f, 1f);
				}
			}
			else
			{
				if (!flag)
				{
					return;
				}
				if (__instance.isSprinting)
				{
					__instance.sprintMeter = Mathf.Clamp(__instance.sprintMeter - Time.deltaTime / (__instance.sprintTime / 1.2f) * __instance.carryWeight * num, 0f, 1f);
				}
				else if (__instance.isMovementHindered > 0)
				{
					if (__instance.isWalking)
					{
						__instance.sprintMeter = Mathf.Clamp(__instance.sprintMeter - Time.deltaTime / (__instance.sprintTime / 1.2f) * num * 0.5f, 0f, 1f);
					}
				}
				else if (!__instance.isWalking)
				{
					__instance.sprintMeter = Mathf.Clamp(__instance.sprintMeter + Time.deltaTime / (__instance.sprintTime / 1.2f + 4f) * num, 0f, 1f);
				}
				else
				{
					__instance.sprintMeter = Mathf.Clamp(__instance.sprintMeter + Time.deltaTime / (__instance.sprintTime / 1.2f + 9f) * num, 0f, 1f);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "DamagePlayer")]
		[HarmonyPrefix]
		private static void DamagePlayer(PlayerControllerB __instance, int damageNumber, bool hasDamageSFX = true, bool callRPC = true, CauseOfDeath causeOfDeath = 0, int deathAnimation = 0, bool fallDamage = false, Vector3 force = default(Vector3))
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Invalid comparison between Unknown and I4
			if (!Configuration.playerConditions.Value)
			{
				return;
			}
			PlayerRevamp component = ((Component)__instance).gameObject.GetComponent<PlayerRevamp>();
			if (Object.op_Implicit((Object)(object)component))
			{
				if ((int)causeOfDeath == 2)
				{
					component.ApplyConditions(DamageType.Falling, 1f + (1f - (float)(__instance.health / 100)));
				}
				else if ((int)causeOfDeath == 7)
				{
					component.ApplyConditions(DamageType.GunShotted, 1f + (1f - (float)(__instance.health / 100)));
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")]
		[HarmonyPrefix]
		private static void KillPlayer(PlayerControllerB __instance)
		{
			PlayerRevamp component = ((Component)__instance).gameObject.GetComponent<PlayerRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return;
			}
			if (component.kidnapped)
			{
				StartOfRoundRevamp component2 = ((Component)StartOfRound.Instance).gameObject.GetComponent<StartOfRoundRevamp>();
				if (!Object.op_Implicit((Object)(object)component2))
				{
					return;
				}
				foreach (GameObject currentEffect in component2.currentEffects)
				{
					currentEffect.SetActive(true);
				}
			}
			if (Configuration.playerConditions.Value)
			{
				component.conditions.Clear();
				HUDManagerRevamp component3 = ((Component)HUDManager.Instance).gameObject.GetComponent<HUDManagerRevamp>();
				if (Object.op_Implicit((Object)(object)component3) && ((Object)(object)__instance == (Object)(object)StartOfRound.Instance.localPlayerController || __instance.actualClientId == StartOfRound.Instance.localPlayerController.actualClientId))
				{
					component3.blindnessIntensity = 0f;
					component3.concussedIntensity = 0f;
				}
			}
		}
	}
	[HarmonyPatch(typeof(PufferAI))]
	internal class PufferAIPatch
	{
		[HarmonyPatch(typeof(PufferAI), "OnCollideWithPlayer")]
		[HarmonyPrefix]
		private static void OnCollideWithPlayer(PufferAI __instance, Collider other)
		{
			PlayerControllerB val = ((EnemyAI)__instance).MeetsStandardPlayerCollisionConditions(other, false, false);
			if ((Object)(object)val != (Object)null && __instance.timeSinceHittingPlayer > 1f)
			{
				PlayerRevamp component = ((Component)val).gameObject.GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ApplyConditions(DamageType.Bitten, 1f + (1f - (float)(val.health / 100)));
				}
			}
		}

		[HarmonyPatch(typeof(PufferAI), "Start")]
		[HarmonyPrefix]
		private static void Start(PufferAI __instance)
		{
			GameObject smokePrefab = __instance.smokePrefab;
			SphereCollider component = smokePrefab.GetComponent<SphereCollider>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				SphereCollider val = smokePrefab.AddComponent<SphereCollider>();
				((Collider)val).isTrigger = true;
				val.radius = 14f;
				Diversity.mls.LogInfo((object)("Added SphereCollider to: " + ((Object)smokePrefab).name));
			}
			Rigidbody component2 = smokePrefab.GetComponent<Rigidbody>();
			if (!Object.op_Implicit((Object)(object)component2))
			{
				Rigidbody val2 = smokePrefab.AddComponent<Rigidbody>();
				val2.isKinematic = true;
				Diversity.mls.LogInfo((object)("Added Rigidbody to: " + ((Object)smokePrefab).name));
			}
			PufferSmokeRevamp component3 = smokePrefab.GetComponent<PufferSmokeRevamp>();
			if (!Object.op_Implicit((Object)(object)component3))
			{
				PufferSmokeRevamp pufferSmokeRevamp = smokePrefab.AddComponent<PufferSmokeRevamp>();
				Diversity.mls.LogInfo((object)("Added PufferSmokeRevamp to: " + ((Object)smokePrefab).name));
			}
		}
	}
	[HarmonyPatch(typeof(RadarBoosterItem), "Start")]
	internal class RadarBoosterItemPatch
	{
		[HarmonyPatch(typeof(RadarBoosterItem), "Start")]
		[HarmonyPostfix]
		public static void Start(RadarBoosterItem __instance)
		{
			RadarBoosterItemRevamp component = ((Component)__instance).gameObject.GetComponent<RadarBoosterItemRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				((Component)__instance).gameObject.AddComponent<RadarBoosterItemRevamp>();
			}
			StartOfRoundRevamp.Instance.radarBoosters.Add(__instance);
		}
	}
	[HarmonyPatch(typeof(RedLocustBees))]
	internal class RedLocustBeesPatch
	{
		[HarmonyPatch(typeof(RedLocustBees), "OnCollideWithPlayer")]
		[HarmonyPrefix]
		private static void OnCollideWithPlayer(RedLocustBees __instance, Collider other)
		{
			if (__instance.timeSinceHittingPlayer < 0.4f)
			{
				return;
			}
			PlayerControllerB val = ((EnemyAI)__instance).MeetsStandardPlayerCollisionConditions(other, false, false);
			if ((Object)(object)val != (Object)null && (val.health > 10 || !val.criticallyInjured))
			{
				PlayerRevamp component = ((Component)val).gameObject.GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ApplyConditions(DamageType.Electrified, 1f + (1f - (float)(val.health / 100)));
				}
			}
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	internal class RoundManagerPatch : MonoBehaviour
	{
		[HarmonyPatch(typeof(RoundManager), "FinishGeneratingLevel")]
		[HarmonyPostfix]
		public static void FinishGeneratingLevel(RoundManager __instance)
		{
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0233: Expected O, but got Unknown
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Expected O, but got Unknown
			Vector3 startPos = default(Vector3);
			((Vector3)(ref startPos))..ctor(300f, -400f, 0f);
			GameObject test = Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/test.prefab");
			GameObject start = Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/start.prefab");
			GameObject end = Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/end.prefab");
			List<GameObject> list = new List<GameObject>();
			list.Add(Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/hall1.prefab"));
			list.Add(Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/hall2.prefab"));
			list.Add(Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/hall3.prefab"));
			list.Add(Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/hall4.prefab"));
			list.Add(Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/hall5.prefab"));
			list.Add(Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/hall6.prefab"));
			list.Add(Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/hall7.prefab"));
			list.Add(Content.MainAssets.LoadAsset<GameObject>("Assets/custom/diversity/bracken/rooms/prefabs/hall8.prefab"));
			StartOfRoundRevamp component = ((Component)StartOfRound.Instance).gameObject.GetComponent<StartOfRoundRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return;
			}
			component.GenerateRoom(StartOfRound.Instance.randomMapSeed, startPos, test, list, start, end, isTest: false);
			Light[] array = Object.FindObjectsOfType<Light>();
			Light[] array2 = array;
			foreach (Light val in array2)
			{
				if (Object.op_Implicit((Object)(object)((Component)val).transform.parent) && (((Object)((Component)val).transform.parent).name.StartsWith("HangingLight") || ((Object)((Component)val).transform.parent).name.StartsWith("WallFixtureLight") || ((Object)((Component)val).transform.parent).name.StartsWith("MansionWallLamp") || ((Object)((Component)val).transform.parent).name.StartsWith("Chandelier")))
				{
					GameObject gameObject = ((Component)val).gameObject;
					StartOfRoundRevamp.Instance.brackenLights.Add(gameObject);
				}
			}
			GameObject val2 = new GameObject("BrakenScreamAudio");
			AudioSource val3 = val2.AddComponent<AudioSource>();
			val3.loop = false;
			((Behaviour)val3).enabled = false;
			val3.playOnAwake = true;
			val3.volume = 1f;
			val3.spatialBlend = 0f;
			val3.clip = Content.MainAssets.LoadAsset<AudioClip>("Assets/custom/diversity/bracken/brakenScream.mp3");
			AnimationCurve val4 = new AnimationCurve();
			val4.AddKey(0f, 1f);
			val4.AddKey(1f, 1f);
			val3.SetCustomCurve((AudioSourceCurveType)0, val4);
			Object.Instantiate<GameObject>(val2);
			Diversity.mls.LogInfo((object)"Bracken scream audio created.");
		}
	}
	[HarmonyPatch(typeof(SandSpiderAI))]
	internal class SandSpiderAIPatch
	{
		private static SpiderRevamp spider;

		[HarmonyPatch(typeof(SandSpiderAI), "HitEnemy")]
		[HarmonyPrefix]
		public static void Slow(SandSpiderAI __instance)
		{
			spider = ((Component)__instance).GetComponent<SpiderRevamp>();
			if (Object.op_Implicit((Object)(object)spider) && !spider.onCooldown)
			{
				spider.hasBeenhit = true;
				spider.onCooldown = true;
				spider.previousAgentSpeed = ((EnemyAI)__instance).agent.speed;
				spider.previousSpiderSpeed = __instance.spiderSpeed;
				spider.currentAgentSpeed = ((EnemyAI)__instance).agent.speed;
				spider.currentSpiderSpeed = __instance.spiderSpeed;
				Diversity.mls.LogInfo((object)"Spider hit!");
			}
		}

		[HarmonyPatch(typeof(SandSpiderAI), "Start")]
		[HarmonyPrefix]
		public static void Start(SandSpiderAI __instance)
		{
			if (Configuration.spiderRevamp.Value)
			{
				spider = ((Component)__instance).gameObject.GetComponent<SpiderRevamp>();
				if (!Object.op_Implicit((Object)(object)spider))
				{
					((Component)__instance).gameObject.AddComponent<SpiderRevamp>();
					Diversity.mls.LogInfo((object)("Added SpiderRevamp to: " + ((Object)((Component)__instance).gameObject).name));
				}
			}
		}

		[HarmonyPatch(typeof(SandSpiderAI), "OnCollideWithPlayer")]
		[HarmonyPrefix]
		private static void OnCollideWithPlayer(SandSpiderAI __instance, Collider other)
		{
			if (((EnemyAI)__instance).isEnemyDead || __instance.onWall)
			{
				return;
			}
			PlayerControllerB val = ((EnemyAI)__instance).MeetsStandardPlayerCollisionConditions(other, __instance.spoolingPlayerBody, false);
			if ((Object)(object)val != (Object)null && __instance.timeSinceHittingPlayer > 1f)
			{
				PlayerRevamp component = ((Component)val).gameObject.GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ApplyConditions(DamageType.Mauled, 1f + (1f - (float)(val.health / 100)));
				}
			}
		}
	}
	[HarmonyPatch(typeof(ShipTeleporter))]
	internal class ShipTeleporterPatch
	{
		[HarmonyPatch(typeof(ShipTeleporter), "Awake")]
		[HarmonyPrefix]
		private static void Awake(ShipTeleporter __instance)
		{
			ShipTeleporterRevamp component = ((Component)__instance).gameObject.GetComponent<ShipTeleporterRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				((Component)__instance).gameObject.AddComponent<ShipTeleporterRevamp>();
			}
		}
	}
	[HarmonyPatch(typeof(SoundManager))]
	internal class SoundManagerPatch
	{
		[HarmonyPatch(typeof(SoundManager), "SetPlayerVoiceFilters")]
		[HarmonyPostfix]
		private static void SetPlayerVoiceFilters(SoundManager __instance)
		{
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				if (!StartOfRound.Instance.allPlayerScripts[i].isPlayerDead && (Object)(object)StartOfRound.Instance.allPlayerScripts[i] != (Object)(object)StartOfRound.Instance.localPlayerController)
				{
					PlayerRevamp component = ((Component)StartOfRound.Instance.localPlayerController).gameObject.GetComponent<PlayerRevamp>();
					if (!Object.op_Implicit((Object)(object)component))
					{
						break;
					}
					if (component.dressGirlHaunt)
					{
						__instance.diageticMixer.SetFloat($"PlayerVolume{i}", -80f);
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(SpringManAI))]
	internal class SpringManAIPatch
	{
		[HarmonyPatch(typeof(SpringManAI), "OnCollideWithPlayer")]
		[HarmonyPrefix]
		private static void OnCollideWithPlayer(SpringManAI __instance, Collider other)
		{
			if (__instance.stoppingMovement || ((EnemyAI)__instance).currentBehaviourStateIndex != 1 || __instance.timeSinceHittingPlayer >= 0f)
			{
				return;
			}
			PlayerControllerB val = ((EnemyAI)__instance).MeetsStandardPlayerCollisionConditions(other, false, false);
			if ((Object)(object)val != (Object)null)
			{
				PlayerRevamp component = ((Component)val).gameObject.GetComponent<PlayerRevamp>();
				if (Object.op_Implicit((Object)(object)component))
				{
					component.ApplyConditions(DamageType.Concussed, 1f + (1f - (float)(val.health / 100)));
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch(typeof(StartOfRound), "Start")]
		[HarmonyPrefix]
		private static void Start(StartOfRound __instance)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: 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_0150: Unknown result type (might be due to invalid IL or missing references)
			StartOfRoundRevamp component = ((Component)__instance).gameObject.GetComponent<StartOfRoundRevamp>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				((Component)__instance).gameObject.AddComponent<StartOfRoundRevamp>();
				Diversity.mls.LogInfo((object)("Added StartOfRoundRevamp to: " + ((Object)((Component)__instance).gameObject).name));
			}
			if (Configuration.brakenSpace.Value)
			{
				GameObject gameObject = ((Component)((Component)__instance.mapScreenPlayerName).gameObject.transform.parent).gameObject;
				GameObject val = new GameObject("ErrorText");
				val.layer = 14;
				val.AddComponent<RectTransform>();
				val.AddComponent<CanvasRenderer>();
				TextMeshProUGUI val2 = val.AddComponent<TextMeshProUGUI>();
				((TMP_Text)val2).font = ((TMP_Text)HUDManager.Instance.controlTipLines[0]).font;
				((TMP_Text)val2).fontSize = 17f;
				((TMP_Text)val2).alignment = (TextAlignmentOptions)514;
				((TMP_Text)val2).overflowMode = (TextOverflowModes)0;
				((TMP_Text)val2).text = "THEY ARE PAYING\nTHE PRICE";
				((Graphic)val2).color = Color.red;
				((Behaviour)val2).enabled = true;
				val.transform.SetParent(gameObject.transform);
				val.transform.localPosition = Vector3.zero;
				val.transform.localScale = new Vector3(2f, 2f, 2f);
				val.transform.localRotation = Quaternion.identity;
				val.SetActive(false);
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "EndOfGame")]
		[HarmonyPrefix]
		private static void EndOfGame(StartOfRound __instance)
		{
			PlayerControllerB[] allPlayerScripts = __instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if ((Object)(object)val != (Object)null)
				{
					PlayerRevamp component = ((Component)val).gameObject.GetComponent<PlayerRevamp>();
					if (!Object.op_Implicit((Object)(object)component))
					{
						return;
					}
					component.conditions.Clear();
					component.updated = false;
					val.playerBodyAnimator.SetBool("Limp", false);
					val.jumpForce = 13f;
					val.bleedingHeavily = false;
					val.isMovementHindered = 0;
					val.hinderedMultiplier = 1f;
					component.nearbySounds.Clear();
					DiversitySoundManager.Instance.current3Daudios.Clear();
					StartOfRoundRevamp.Instance.brackenLights.Clear();
					StartOfRoundRevamp.Instance.affectedLights.Clear();
					StartOfRoundRevamp.Instance.steamSounds.Clear();
					StartOfRoundRevamp.Instance.lightBuzz.Clear();
					HUDManagerRevamp component2 = ((Component)HUDManager.Instance).gameObject.GetComponent<HUDManagerRevamp>();
					if (!Object.op_Implicit((Object)(object)component2))
					{
						return;
					}
					component2.blindnessIntensity = 0f;
					component2.concussedIntensity = 0f;
					component.kidnapped = false;
				}
			}
			StartOfRoundRevamp component3 = ((Component)__instance).gameObject.GetComponent<StartOfRoundRevamp>();
			if (Object.op_Implicit((Object)(object)component3))
			{
				component3.Reset();
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "DisableShipSpeakerLocalClient")]
		[HarmonyPostfix]
		private static void DisableShipSpeakerLocalClient(StartOfRound __instance)
		{
		}
	}
	[HarmonyPatch(typeof(SteamValveHazard))]
	internal class SteamValveHazardPatch
	{
		[HarmonyPatch(typeof(SteamValveHazard), "Start")]
		[HarmonyPrefix]
		private static void Start(SteamValveHazard __instance)
		{
			SteamLeakRevamp component = ((Component)__instance).gameObject.GetComponent<SteamLeakRevamp>();
			if (!

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/EladsHUD.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using CustomHUD;
using GameNetcodeStuff;
using HarmonyLib;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("EladsHUD")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Custom HUD for lethal company :]")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("EladsHUD")]
[assembly: AssemblyTitle("EladsHUD")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public enum PocketFlashlightOptions
{
	Disabled,
	Vanilla,
	Separate
}
public enum StaminaTextOptions
{
	Disabled,
	PercentageOnly,
	Full
}
internal class CustomHUD_Mono : MonoBehaviour
{
	public static CustomHUD_Mono instance;

	[Header("Health")]
	public CanvasGroup healthGroup;

	public Image healthBar;

	public TextMeshProUGUI healthText;

	[Header("Stamina")]
	public CanvasGroup staminaGroup;

	public Image staminaBar;

	public Image staminaBarChangeFG;

	public TextMeshProUGUI staminaText;

	public TextMeshProUGUI carryText;

	[Header("Battery")]
	public CanvasGroup batteryGroup;

	public Image batteryBar;

	public TextMeshProUGUI batteryText;

	[Header("Flashlight")]
	public CanvasGroup flashlightGroup;

	public Image flashlightBar;

	public TextMeshProUGUI flashlightText;

	private Color staminaColor;

	private Color staminaWarnColor = new Color(255f, 0f, 0f);

	private float colorLerp;

	private int lastHealth = 100;

	private float lastHealthChange = 0f;

	private void Awake()
	{
		if ((Object)(object)instance != (Object)null)
		{
			throw new Exception("2 instances of CustomHUD_Mono!");
		}
		instance = this;
	}

	private void Start()
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		staminaColor = ((Graphic)staminaBar).color;
	}

	public void UpdateFromPlayer(PlayerControllerB player)
	{
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_017c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_018d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01da: Unknown result type (might be due to invalid IL or missing references)
		lastHealthChange += Time.deltaTime;
		if (lastHealth != player.health)
		{
			lastHealth = player.health;
			lastHealthChange = 0f;
		}
		int health = player.health;
		float sprintMeter = player.sprintMeter;
		float sprintTime = player.sprintTime;
		if ((double)sprintMeter < 0.3)
		{
			colorLerp = Mathf.Clamp01(colorLerp + Time.deltaTime * 8f);
		}
		else
		{
			colorLerp = Mathf.Clamp01(colorLerp - Time.deltaTime * 8f);
		}
		((Graphic)staminaBar).color = Color.Lerp(staminaColor, staminaWarnColor, colorLerp);
		int num = Mathf.FloorToInt(sprintMeter * 100f);
		float num2 = CalculateStaminaOverTime(player);
		float num3 = num2 * 100f;
		if (Plugin.detailedStamina.Value != 0)
		{
			((TMP_Text)staminaText).text = $"{num}<size=75%><voffset=1>%</voffset></size>";
		}
		else
		{
			((TMP_Text)staminaText).text = "";
		}
		float num4 = Mathf.Sign(num2);
		float num5 = num4;
		if (num5 != -1f)
		{
			if (num5 != 0f)
			{
				if (num5 != 1f)
				{
				}
				staminaBar.fillAmount = sprintMeter;
				staminaBarChangeFG.fillAmount = 0f;
				if (Plugin.detailedStamina.Value == StaminaTextOptions.Full)
				{
					TextMeshProUGUI obj = staminaText;
					((TMP_Text)obj).text = ((TMP_Text)obj).text + " | +" + num3.ToString("0.0") + "<size=75%>/sec</size>";
				}
			}
			else
			{
				staminaBar.fillAmount = sprintMeter;
				staminaBarChangeFG.fillAmount = 0f;
				if (Plugin.detailedStamina.Value == StaminaTextOptions.Full)
				{
					TextMeshProUGUI obj2 = staminaText;
					((TMP_Text)obj2).text = ((TMP_Text)obj2).text + " | +0.0<size=75%>/sec</size>";
				}
			}
		}
		else
		{
			staminaBar.fillAmount = sprintMeter - Mathf.Abs(num2);
			((Graphic)staminaBarChangeFG).color = Color.Lerp(Color.white, staminaWarnColor, colorLerp);
			staminaBarChangeFG.fillAmount = Mathf.Min(sprintMeter, Mathf.Abs(num2));
			((Transform)((Graphic)staminaBarChangeFG).rectTransform).localPosition = new Vector3(270f * Mathf.Max(0f, sprintMeter - Mathf.Abs(num2)), 0f);
			if (Plugin.detailedStamina.Value == StaminaTextOptions.Full)
			{
				TextMeshProUGUI obj3 = staminaText;
				((TMP_Text)obj3).text = ((TMP_Text)obj3).text + " | " + num3.ToString("0.0") + "<size=75%>/sec</size>";
			}
		}
		float num6 = Mathf.RoundToInt(Mathf.Clamp(player.carryWeight - 1f, 0f, 100f) * 105f);
		if (Plugin.shouldDoKGConversion)
		{
			num6 *= 0.453592f;
			((TMP_Text)carryText).text = $"{num6}<size=60%>kg</size>";
		}
		else
		{
			((TMP_Text)carryText).text = $"{num6}<size=60%>lb</size>";
		}
		healthBar.fillAmount = (float)health / 100f;
		((TMP_Text)healthText).text = health.ToString();
		float value = Plugin.healthbarHideDelay.Value;
		healthGroup.alpha = (Plugin.autoHideHealthbar.Value ? Mathf.InverseLerp(value + 1f, value, lastHealthChange) : 1f);
		((Component)flashlightGroup).gameObject.SetActive(UpdateFlashlight(player));
		((Component)batteryGroup).gameObject.SetActive(UpdateBattery(player));
	}

	private bool UpdateFlashlight(PlayerControllerB player)
	{
		if (Plugin.pocketedFlashlightDisplayMode.Value != PocketFlashlightOptions.Separate)
		{
			return false;
		}
		if (!((Behaviour)player.helmetLight).enabled)
		{
			return false;
		}
		GrabbableObject pocketedFlashlight = player.pocketedFlashlight;
		if ((Object)(object)pocketedFlashlight == (Object)null)
		{
			return false;
		}
		if (!pocketedFlashlight.itemProperties.requiresBattery)
		{
			return false;
		}
		flashlightBar.fillAmount = pocketedFlashlight.insertedBattery.charge;
		int num = Mathf.CeilToInt(pocketedFlashlight.insertedBattery.charge * pocketedFlashlight.itemProperties.batteryUsage);
		((TMP_Text)flashlightText).text = $"{Mathf.CeilToInt(pocketedFlashlight.insertedBattery.charge * 100f)}%";
		if (Plugin.displayTimeLeft.Value)
		{
			return true;
		}
		TextMeshProUGUI obj = flashlightText;
		((TMP_Text)obj).text = ((TMP_Text)obj).text + string.Format(" <size=60%>{0}:{1}", num / 60, (num % 60).ToString("D2"));
		return true;
	}

	private bool UpdateBattery(PlayerControllerB player)
	{
		GrabbableObject val = player.currentlyHeldObjectServer;
		if ((Object)(object)val == (Object)null && Plugin.pocketedFlashlightDisplayMode.Value == PocketFlashlightOptions.Vanilla)
		{
			val = player.pocketedFlashlight;
		}
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		if (!val.itemProperties.requiresBattery)
		{
			return false;
		}
		batteryBar.fillAmount = val.insertedBattery.charge;
		int num = (int)(val.insertedBattery.charge / val.itemProperties.batteryUsage);
		int num2 = Mathf.CeilToInt(val.insertedBattery.charge * val.itemProperties.batteryUsage);
		((TMP_Text)batteryText).text = $"{Mathf.CeilToInt(val.insertedBattery.charge * 100f)}%";
		if (!Plugin.displayTimeLeft.Value)
		{
			return true;
		}
		if (val.itemProperties.itemIsTrigger)
		{
			TextMeshProUGUI obj = batteryText;
			((TMP_Text)obj).text = ((TMP_Text)obj).text + $" ({num} uses remaining)";
		}
		else
		{
			TextMeshProUGUI obj2 = batteryText;
			((TMP_Text)obj2).text = ((TMP_Text)obj2).text + string.Format(" ({0}:{1} remaining)", num2 / 60, (num2 % 60).ToString("D2"));
		}
		return true;
	}

	private float CalculateStaminaOverTime(PlayerControllerB player)
	{
		if (player.sprintMeter == 1f)
		{
			return 0f;
		}
		bool privateField = player.GetPrivateField<bool>("isWalking");
		float sprintTime = player.sprintTime;
		float num = 1f;
		if ((double)player.drunkness > 0.019999999552965164)
		{
			num *= Mathf.Abs(StartOfRound.Instance.drunknessSpeedEffect.Evaluate(player.drunkness) - 1.25f);
		}
		return player.isSprinting ? (-1f / sprintTime * player.carryWeight * num) : ((player.isMovementHindered > 0 && privateField) ? (-1f / sprintTime * num * 0.5f) : ((!privateField) ? (1f / (sprintTime + 4f) * num) : (1f / (sprintTime + 9f) * num)));
	}
}
namespace EladsHUD
{
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "EladsHUD";

		public const string PLUGIN_NAME = "EladsHUD";

		public const string PLUGIN_VERSION = "1.1.0";
	}
}
namespace CustomHUD
{
	[BepInPlugin("me.eladnlg.customhud", "Elads HUD", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin instance;

		public AssetBundle assets;

		public GameObject HUD;

		public static bool shouldDoKGConversion;

		internal static ConfigEntry<PocketFlashlightOptions> pocketedFlashlightDisplayMode;

		internal static ConfigEntry<StaminaTextOptions> detailedStamina;

		internal static ConfigEntry<bool> displayTimeLeft;

		internal static ConfigEntry<float> hudScale;

		internal static ConfigEntry<bool> autoHideHealthbar;

		internal static ConfigEntry<float> healthbarHideDelay;

		private void Awake()
		{
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			if ((Object)(object)instance != (Object)null)
			{
				throw new Exception("what the cuck??? more than 1 plugin instance.");
			}
			instance = this;
			hudScale = ((BaseUnityPlugin)this).Config.Bind<float>("General", "HUDScale", 1f, "The size of the HUD.");
			autoHideHealthbar = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "HideHealthbarAutomatically", true, "Should the healthbar be hidden after not taking damage for a while.");
			healthbarHideDelay = ((BaseUnityPlugin)this).Config.Bind<float>("General", "HealthbarHideDelay", 4f, "The amount of time before the healthbar starts fading away.");
			pocketedFlashlightDisplayMode = ((BaseUnityPlugin)this).Config.Bind<PocketFlashlightOptions>("General", "FlashlightBattery", PocketFlashlightOptions.Separate, "How the flashlight battery is displayed whilst unequipped.\r\nDisabled - Flashlight battery will not be displayed.\r\nVanilla - Flashlight battery will be displayed when you don't have a battery-using item equipped.\r\nSeparate - Flashlight battery will be displayed using a dedicated panel. (recommended)");
			detailedStamina = ((BaseUnityPlugin)this).Config.Bind<StaminaTextOptions>("General", "DetailedStamina", StaminaTextOptions.PercentageOnly, "What the stamina text should display.\r\nDisabled - The stamina text will be hidden.\r\nPercentageOnly - Only the percentage will be displayed. (recommended)\r\nFull - Both percentage and rate of gain/loss will be displayed.");
			displayTimeLeft = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DisplayTimeLeft", true, "Should the uses/time left for a battery-using item be displayed.");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Elad's HUD is loaded!");
			assets = AssetUtils.LoadAssetBundleFromResources("customhud", typeof(PlayerPatches).Assembly);
			HUD = assets.LoadAsset<GameObject>("PlayerInfo");
			Harmony val = new Harmony("me.eladnlg.customhud");
			val.PatchAll(Assembly.GetExecutingAssembly());
		}

		private void Start()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)(Chainloader.PluginInfos.Count + " plugins loaded"));
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Plugin GUID: " + pluginInfo.Value.Metadata.GUID));
			}
			shouldDoKGConversion = Chainloader.PluginInfos.Any((KeyValuePair<string, PluginInfo> pair) => pair.Value.Metadata.GUID == "com.zduniusz.lethalcompany.lbtokg");
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	public class HUDPatches
	{
		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		private static void Awake_Postfix(HUDManager __instance)
		{
			//IL_0057: 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)
			HUDElement[] privateField = __instance.GetPrivateField<HUDElement[]>("HUDElements");
			privateField[2].canvasGroup.alpha = 0f;
			GameObject val = Object.Instantiate<GameObject>(Plugin.instance.HUD, ((Component)privateField[2].canvasGroup).transform.parent);
			val.transform.localScale = new Vector3(0.75f, 0.75f, 0.75f) * Plugin.hudScale.Value;
			privateField[2].canvasGroup = val.GetComponent<CanvasGroup>();
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB))]
	public static class PlayerPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch("LateUpdate")]
		private static void LateUpdate_Prefix(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject) && !((Object)(object)CustomHUD_Mono.instance == (Object)null))
			{
				CustomHUD_Mono.instance.UpdateFromPlayer(__instance);
			}
		}
	}
	internal static class ReflectionUtils
	{
		public static T GetPrivateField<T>(this object obj, string field)
		{
			return (T)obj.GetType().GetField(field, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
		}
	}
}
namespace Jotunn.Utils
{
	public static class AssetUtils
	{
		public const char AssetBundlePathSeparator = '$';

		public static Texture2D LoadTexture(string texturePath, bool relativePath = true)
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			string text = texturePath;
			if (relativePath)
			{
				text = Path.Combine(Paths.PluginPath, texturePath);
			}
			if (!File.Exists(text))
			{
				return null;
			}
			if (!text.EndsWith(".png") && !text.EndsWith(".jpg"))
			{
				throw new Exception("LoadTexture can only load png or jpg textures");
			}
			byte[] array = File.ReadAllBytes(text);
			Texture2D val = new Texture2D(2, 2);
			val.LoadRawTextureData(array);
			return val;
		}

		public static Sprite LoadSpriteFromFile(string spritePath)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = LoadTexture(spritePath);
			if ((Object)(object)val != (Object)null)
			{
				return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), default(Vector2), 100f);
			}
			return null;
		}

		public static AssetBundle LoadAssetBundle(string bundlePath)
		{
			string text = Path.Combine(Paths.PluginPath, bundlePath);
			if (!File.Exists(text))
			{
				return null;
			}
			return AssetBundle.LoadFromFile(text);
		}

		public static AssetBundle LoadAssetBundleFromResources(string bundleName, Assembly resourceAssembly)
		{
			if (resourceAssembly == null)
			{
				throw new ArgumentNullException("Parameter resourceAssembly can not be null.");
			}
			string text = null;
			try
			{
				text = resourceAssembly.GetManifestResourceNames().Single((string str) => str.EndsWith(bundleName));
			}
			catch (Exception)
			{
			}
			if (text == null)
			{
				Debug.LogError((object)("AssetBundle " + bundleName + " not found in assembly manifest"));
				return null;
			}
			AssetBundle result;
			using (Stream stream = resourceAssembly.GetManifestResourceStream(text))
			{
				result = AssetBundle.LoadFromStream(stream);
			}
			return result;
		}

		public static string LoadText(string path)
		{
			string text = Path.Combine(Paths.PluginPath, path);
			if (!File.Exists(text))
			{
				Debug.LogError((object)("Error, failed to load contents from non-existant path: $" + text));
				return null;
			}
			return File.ReadAllText(text);
		}

		public static Sprite LoadSprite(string assetPath)
		{
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			string text = Path.Combine(Paths.PluginPath, assetPath);
			if (!File.Exists(text))
			{
				return null;
			}
			if (text.Contains('$'.ToString()))
			{
				string[] array = text.Split('$');
				string text2 = array[0];
				string text3 = array[1];
				AssetBundle val = AssetBundle.LoadFromFile(text2);
				Sprite result = val.LoadAsset<Sprite>(text3);
				val.Unload(false);
				return result;
			}
			Texture2D val2 = LoadTexture(text, relativePath: false);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return null;
			}
			return Sprite.Create(val2, new Rect(0f, 0f, (float)((Texture)val2).width, (float)((Texture)val2).height), Vector2.zero);
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/FairAI.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using FairAI.Component;
using FairAI.Patches;
using GameNetcodeStuff;
using HarmonyLib;
using LethalThings;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FairAI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FairAI")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("42deea12-f73e-4d63-81e9-5359e98c8d53")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace FairAI
{
	internal class FAIR_AI : NetworkBehaviour
	{
		public EnemyAI targetWithRotation;

		[ClientRpc]
		public void SwitchedTargetedEnemyClientRpc(Turret turret, EnemyAI enemy, bool setModeToCharging = false)
		{
			targetWithRotation = enemy;
			if (setModeToCharging)
			{
				Type typeFromHandle = typeof(Turret);
				MethodInfo method = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
				method.Invoke(turret, new object[1] { 1 });
			}
		}

		[ClientRpc]
		public void RemoveTargetedEnemyClientRpc()
		{
			targetWithRotation = null;
		}
	}
	[BepInPlugin("GoldenKitten.FairAI", "Fair AI", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private const string modGUID = "GoldenKitten.FairAI";

		private const string modName = "Fair AI";

		private const string modVersion = "1.0.0";

		private Harmony harmony = new Harmony("GoldenKitten.FairAI");

		public static Plugin Instance;

		public static ManualLogSource logger;

		public static List<EnemyType> enemies;

		public static List<Item> items;

		public static bool playersEnteredInside = false;

		public static int wallsAndEnemyLayerMask = 524288;

		public static int enemyMask = 524288;

		public static int allHittablesMask;

		private static float onMeshThreshold = 3f;

		private void Awake()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			harmony = new Harmony("GoldenKitten.FairAI");
			logger = Logger.CreateLogSource("GoldenKitten.FairAI");
			harmony.PatchAll(typeof(Plugin));
			logger.LogInfo((object)"Fair AI initiated!");
			CreateHarmonyPatch(harmony, typeof(RoundManager), "Start", null, typeof(RoundManagerPatch), "PatchStart", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(StartOfRound), "Start", null, typeof(StartOfRoundPatch), "PatchStart", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(StartOfRound), "Update", null, typeof(StartOfRoundPatch), "PatchUpdate", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Turret), "Start", null, typeof(TurretAIPatch), "PatchStart", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Turret), "Update", null, typeof(TurretAIPatch), "PatchUpdate", isPrefix: true);
			CreateHarmonyPatch(harmony, typeof(Turret), "SetTargetToPlayerBody", null, typeof(TurretAIPatch), "PatchSetTargetToPlayerBody", isPrefix: true);
			CreateHarmonyPatch(harmony, typeof(Turret), "TurnTowardsTargetIfHasLOS", null, typeof(TurretAIPatch), "PatchTurnTowardsTargetIfHasLOS", isPrefix: true);
			CreateHarmonyPatch(harmony, typeof(Landmine), "SpawnExplosion", new Type[4]
			{
				typeof(Vector3),
				typeof(bool),
				typeof(float),
				typeof(float)
			}, typeof(MineAIPatch), "PatchSpawnExplosion", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Landmine), "OnTriggerEnter", null, typeof(MineAIPatch), "PatchOnTriggerEnter", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Landmine), "OnTriggerExit", null, typeof(MineAIPatch), "PatchOnTriggerExit", isPrefix: false);
			CreateHarmonyPatch(harmony, typeof(Landmine), "Detonate", null, typeof(MineAIPatch), "DetonatePatch", isPrefix: false);
			if (FindType("LethalThings.RoombaAI") != null)
			{
				CreateHarmonyPatch(harmony, FindType("LethalThings.RoombaAI"), "Start", null, typeof(BoombaPatch), "PatchStart", isPrefix: false);
				CreateHarmonyPatch(harmony, FindType("LethalThings.RoombaAI"), "DoAIInterval", null, typeof(BoombaPatch), "PatchDoAIInterval", isPrefix: false);
			}
		}

		public static List<PlayerControllerB> GetActivePlayers()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			List<PlayerControllerB> list = new List<PlayerControllerB>();
			PlayerControllerB[] array = allPlayerScripts;
			foreach (PlayerControllerB val in array)
			{
				if ((Object)val != (Object)null && !val.isPlayerDead && ((Behaviour)val).isActiveAndEnabled && val.isPlayerControlled)
				{
					list.Add(val);
				}
			}
			return list;
		}

		public static bool AllowFairness(Vector3 position)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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)
			if ((Object)(object)StartOfRound.Instance != (Object)null && Can("CheckForPlayersInside"))
			{
				if (IsAPlayersOutside())
				{
					if (!(position.y > -80f))
					{
						Bounds bounds = StartOfRound.Instance.shipInnerRoomBounds.bounds;
						if (!((Bounds)(ref bounds)).Contains(position))
						{
							goto IL_005c;
						}
					}
					return true;
				}
				goto IL_005c;
			}
			return true;
			IL_005c:
			return playersEnteredInside;
		}

		public static bool IsAPlayersOutside()
		{
			List<PlayerControllerB> activePlayers = GetActivePlayers();
			for (int i = 0; i < activePlayers.Count; i++)
			{
				PlayerControllerB val = activePlayers[i];
				if (!val.isInsideFactory)
				{
					return true;
				}
			}
			return false;
		}

		public static bool IsAPlayerInsideShip()
		{
			List<PlayerControllerB> activePlayers = GetActivePlayers();
			for (int i = 0; i < activePlayers.Count; i++)
			{
				PlayerControllerB val = activePlayers[i];
				if (val.isInHangarShipRoom)
				{
					return true;
				}
			}
			return false;
		}

		public static bool IsAPlayerInsideDungeon()
		{
			List<PlayerControllerB> activePlayers = GetActivePlayers();
			for (int i = 0; i < activePlayers.Count; i++)
			{
				PlayerControllerB val = activePlayers[i];
				if (val.isInsideFactory)
				{
					return true;
				}
			}
			return false;
		}

		public static bool CanMob(string parentIdentifier, string identifier, string mobName)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			string text = RemoveInvalidCharacters(mobName).ToUpper();
			if (((BaseUnityPlugin)Instance).Config[new ConfigDefinition("Mobs", parentIdentifier)].BoxedValue.ToString().ToUpper().Equals("TRUE"))
			{
				foreach (ConfigDefinition key in ((BaseUnityPlugin)Instance).Config.Keys)
				{
					if (RemoveInvalidCharacters(key.Key.ToUpper()).Equals(RemoveInvalidCharacters(text + identifier.ToUpper())))
					{
						return ((BaseUnityPlugin)Instance).Config[key].BoxedValue.ToString().ToUpper().Equals("TRUE");
					}
				}
				return false;
			}
			return false;
		}

		public static bool Can(string identifier)
		{
			foreach (ConfigDefinition key in ((BaseUnityPlugin)Instance).Config.Keys)
			{
				if (RemoveInvalidCharacters(key.Key.ToUpper()).Equals(RemoveInvalidCharacters(identifier.ToUpper())))
				{
					return ((BaseUnityPlugin)Instance).Config[key].BoxedValue.ToString().ToUpper().Equals("TRUE");
				}
			}
			return false;
		}

		public static string RemoveWhitespaces(string source)
		{
			return string.Join("", source.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries));
		}

		public static string RemoveSpecialCharacters(string source)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (char c in source)
			{
				if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString();
		}

		public static string RemoveInvalidCharacters(string source)
		{
			return RemoveWhitespaces(RemoveSpecialCharacters(source));
		}

		public static Type FindType(string fullName)
		{
			try
			{
				if ((from a in AppDomain.CurrentDomain.GetAssemblies()
					where !a.IsDynamic
					select a).SelectMany((Assembly a) => a.GetTypes()).FirstOrDefault((Type t) => t.FullName.Equals(fullName)) != null)
				{
					return (from a in AppDomain.CurrentDomain.GetAssemblies()
						where !a.IsDynamic
						select a).SelectMany((Assembly a) => a.GetTypes()).FirstOrDefault((Type t) => t.FullName.Equals(fullName));
				}
			}
			catch
			{
				return null;
			}
			return null;
		}

		public static void CreateHarmonyPatch(Harmony harmony, Type typeToPatch, string methodToPatch, Type[] parameters, Type patchType, string patchMethod, bool isPrefix)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			if (typeToPatch == null || patchType == null)
			{
				logger.LogInfo((object)"Type is either incorrect or does not exist!");
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeToPatch, methodToPatch, parameters, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(patchType, patchMethod, (Type[])null, (Type[])null);
			if (isPrefix)
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			else
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		public static bool IsAgentOnNavMesh(GameObject agentObject)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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_0058: 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)
			Vector3 position = agentObject.transform.position;
			NavMeshHit val = default(NavMeshHit);
			if (NavMesh.SamplePosition(position, ref val, onMeshThreshold, -1) && Mathf.Approximately(position.x, ((NavMeshHit)(ref val)).position.x) && Mathf.Approximately(position.z, ((NavMeshHit)(ref val)).position.z))
			{
				return position.y >= ((NavMeshHit)(ref val)).position.y;
			}
			return false;
		}

		public static bool AttackTargets(Vector3 aimPoint, Vector3 forward, float range)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			return HitTargets(GetTargets(aimPoint, forward, range), forward);
		}

		public static List<GameObject> GetTargets(Vector3 aimPoint, Vector3 forward, float range)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: 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)
			List<GameObject> list = new List<GameObject>();
			Ray val = default(Ray);
			((Ray)(ref val))..ctor(aimPoint, forward);
			RaycastHit[] array = Physics.RaycastAll(val, range, allHittablesMask, (QueryTriggerInteraction)2);
			Array.Sort(array, (RaycastHit x, RaycastHit y) => ((RaycastHit)(ref x)).distance.CompareTo(((RaycastHit)(ref y)).distance));
			Vector3 val2 = aimPoint + forward * range;
			IHittable val3 = default(IHittable);
			EnemyAI val6 = default(EnemyAI);
			for (int i = 0; i < array.Length; i++)
			{
				GameObject gameObject = ((Component)((RaycastHit)(ref array[i])).transform).gameObject;
				if (gameObject.TryGetComponent<IHittable>(ref val3))
				{
					EnemyAI val4 = null;
					EnemyAICollisionDetect val5 = (EnemyAICollisionDetect)(object)((val3 is EnemyAICollisionDetect) ? val3 : null);
					if (val5 != null)
					{
						val4 = val5.mainScript;
					}
					if ((Object)(object)val4 != (Object)null && (val4.isEnemyDead || val4.enemyHP <= 0 || !val4.enemyType.canDie))
					{
						continue;
					}
					if (val3 is PlayerControllerB)
					{
						list.Add(gameObject);
					}
					else
					{
						if (!((Object)(object)val4 != (Object)null))
						{
							continue;
						}
						list.Add(gameObject);
					}
					val2 = ((RaycastHit)(ref array[i])).point;
					break;
				}
				if (((Component)((RaycastHit)(ref array[i])).collider).TryGetComponent<EnemyAI>(ref val6))
				{
					if (val6.isEnemyDead || val6.enemyHP <= 0 || !val6.enemyType.canDie)
					{
						continue;
					}
					list.Add(((Component)val6).gameObject);
					val2 = ((RaycastHit)(ref array[i])).point;
					break;
				}
				val2 = ((RaycastHit)(ref array[i])).point;
				break;
			}
			return list;
		}

		public static bool HitTargets(List<GameObject> targets, Vector3 forward)
		{
			//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)
			bool hits = false;
			if (!targets.Any())
			{
				return hits;
			}
			targets.ForEach(delegate(GameObject t)
			{
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0239: Unknown result type (might be due to invalid IL or missing references)
				//IL_0240: Expected O, but got Unknown
				//IL_0346: Unknown result type (might be due to invalid IL or missing references)
				//IL_0317: Unknown result type (might be due to invalid IL or missing references)
				//IL_031e: Expected O, but got Unknown
				//IL_0333: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e4: 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_01a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_011d: 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_00d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
				//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
				//IL_029d: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
				//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)t != (Object)null)
				{
					if ((Object)(object)t.GetComponent<PlayerControllerB>() != (Object)null)
					{
						PlayerControllerB component = t.GetComponent<PlayerControllerB>();
						int num = 20;
						hits = true;
						component.DamagePlayer(num, true, true, (CauseOfDeath)7, 0, false, forward);
					}
					else if ((Object)(object)t.GetComponent<EnemyAICollisionDetect>() != (Object)null)
					{
						EnemyAICollisionDetect component2 = t.GetComponent<EnemyAICollisionDetect>();
						int num2 = 1;
						if (!component2.mainScript.isEnemyDead && ((NetworkBehaviour)component2.mainScript).IsOwner && CanMob("TurretDamageAllMobs", ".Turret Damage", component2.mainScript.enemyType.enemyName))
						{
							if (component2.mainScript is NutcrackerEnemyAI)
							{
								if (((EnemyAI)(NutcrackerEnemyAI)component2.mainScript).currentBehaviourStateIndex > 0)
								{
									component2.mainScript.HitEnemyOnLocalClient(num2, default(Vector3), (PlayerControllerB)null, false);
									hits = true;
								}
							}
							else
							{
								component2.mainScript.HitEnemyOnLocalClient(num2, default(Vector3), (PlayerControllerB)null, false);
								hits = true;
							}
						}
					}
					else if ((Object)(object)t.GetComponent<EnemyAI>() != (Object)null)
					{
						EnemyAI component3 = t.GetComponent<EnemyAI>();
						if (((NetworkBehaviour)component3).IsOwner)
						{
							int num3 = 1;
							if (CanMob("TurretDamageAllMobs", ".Turret Damage", component3.enemyType.enemyName))
							{
								if (component3 is NutcrackerEnemyAI)
								{
									if (((EnemyAI)(NutcrackerEnemyAI)component3).currentBehaviourStateIndex > 0)
									{
										component3.HitEnemyOnLocalClient(num3, default(Vector3), (PlayerControllerB)null, false);
										hits = true;
									}
								}
								else
								{
									component3.HitEnemyOnLocalClient(num3, default(Vector3), (PlayerControllerB)null, false);
									hits = true;
								}
							}
						}
					}
					else if (t.GetComponent<IHittable>() != null)
					{
						IHittable component4 = t.GetComponent<IHittable>();
						if (component4 is EnemyAICollisionDetect)
						{
							EnemyAICollisionDetect val = (EnemyAICollisionDetect)component4;
							int num4 = 1;
							if (((NetworkBehaviour)val.mainScript).IsOwner && CanMob("TurretDamageAllMobs", ".Turret Damage", val.mainScript.enemyType.enemyName))
							{
								if (val.mainScript is NutcrackerEnemyAI)
								{
									if (((EnemyAI)(NutcrackerEnemyAI)val.mainScript).currentBehaviourStateIndex > 0)
									{
										val.mainScript.HitEnemyOnLocalClient(num4, default(Vector3), (PlayerControllerB)null, false);
										hits = true;
									}
								}
								else
								{
									val.mainScript.HitEnemyOnLocalClient(num4, default(Vector3), (PlayerControllerB)null, false);
									hits = true;
								}
							}
						}
						else if (component4 is PlayerControllerB)
						{
							PlayerControllerB val2 = (PlayerControllerB)component4;
							int num5 = 33;
							hits = true;
							val2.DamagePlayer(num5, true, true, (CauseOfDeath)7, 0, false, forward);
						}
						else
						{
							component4.Hit(1, forward, (PlayerControllerB)null, true);
							hits = true;
						}
					}
				}
			});
			return hits;
		}
	}
}
namespace FairAI.Patches
{
	internal class BoombaPatch
	{
		public static void PatchStart(ref RoombaAI __instance)
		{
			((Component)__instance).gameObject.AddComponent<BoombaTimer>();
		}

		public static void PatchDoAIInterval(ref RoombaAI __instance)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: 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)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.AllowFairness(((Component)__instance).transform.position) || !Plugin.IsAgentOnNavMesh(((Component)__instance).gameObject) || (((EnemyAI)__instance).currentSearch == null && !((EnemyAI)__instance).movingTowardsTargetPlayer) || (!__instance.mineAudio.isPlaying && !__instance.mineFarAudio.isPlaying) || !((Component)__instance).GetComponent<BoombaTimer>().IsActiveBomb())
			{
				return;
			}
			Vector3 val = ((Component)__instance).transform.position + Vector3.up;
			Collider[] array = Physics.OverlapSphere(val, 6f, 2621448, (QueryTriggerInteraction)2);
			for (int i = 0; i < array.Length; i++)
			{
				float num = Vector3.Distance(val, ((Component)array[i]).transform.position);
				if ((num > 4f && Physics.Linecast(val, ((Component)array[i]).transform.position + Vector3.up * 0.3f, 256, (QueryTriggerInteraction)1)) || !((Object)(object)((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>() != (Object)null))
				{
					continue;
				}
				EnemyAICollisionDetect component = ((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>();
				if (!((Object)(object)((Component)component.mainScript).gameObject != (Object)(object)((Component)__instance).gameObject) || !Plugin.CanMob("BoombaAllMobs", ".Boomba", component.mainScript.enemyType.enemyName))
				{
					continue;
				}
				if ((Object)(object)component != (Object)null && ((NetworkBehaviour)component.mainScript).IsOwner && !component.mainScript.isEnemyDead)
				{
					Object.Instantiate<GameObject>(StartOfRound.Instance.explosionPrefab, val, Quaternion.Euler(-90f, 0f, 0f), RoundManager.Instance.mapPropsContainer.transform).SetActive(true);
					if (num < 3f)
					{
						component.mainScript.KillEnemyOnOwnerClient(true);
					}
					else if (num < 6f)
					{
						component.mainScript.HitEnemyOnLocalClient(2, default(Vector3), (PlayerControllerB)null, false);
					}
				}
				if (((NetworkBehaviour)__instance).IsServer)
				{
					((EnemyAI)__instance).KillEnemy(true);
				}
				else
				{
					((EnemyAI)__instance).KillEnemyServerRpc(true);
				}
			}
		}
	}
	internal class EnemyAIPatch
	{
		public static void DoAIIntervalPatch(ref EnemyAI __instance)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			if (!(__instance is ForestGiantAI))
			{
				return;
			}
			ForestGiantAI val = (ForestGiantAI)__instance;
			if (StartOfRound.Instance.livingPlayers != 0 && !((EnemyAI)val).isEnemyDead)
			{
				int currentBehaviourStateIndex = ((EnemyAI)val).currentBehaviourStateIndex;
				int num = currentBehaviourStateIndex;
				if (num == 1)
				{
					val.investigating = false;
				}
			}
		}

		public static bool OnCollideWithEnemyPatch(ref EnemyAI __instance, Collider other)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: 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_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: 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_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			if (__instance is ForestGiantAI)
			{
				Type typeFromHandle = typeof(ForestGiantAI);
				ForestGiantAI val = (ForestGiantAI)__instance;
				FieldInfo field = typeFromHandle.GetField("inEatingPlayerAnimation", BindingFlags.Instance | BindingFlags.NonPublic);
				bool flag = (bool)field.GetValue(val);
				if ((Object)(object)((EnemyAI)val).inSpecialAnimationWithPlayer != (Object)null || flag || ((EnemyAI)val).stunNormalizedTimer >= 0f)
				{
					return false;
				}
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if (!((Object)(object)component != (Object)null) || !((Object)(object)component == (Object)(object)GameNetworkManager.Instance.localPlayerController))
				{
					return false;
				}
				Vector3 val2 = Vector3.Normalize((val.centerPosition.position - (((Component)GameNetworkManager.Instance.localPlayerController).transform.position + Vector3.up * 1.5f)) * 1000f);
				if (!Physics.Linecast(val.centerPosition.position + val2 * 1.7f, ((Component)GameNetworkManager.Instance.localPlayerController).transform.position + Vector3.up * 1.5f, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1) && ((!StartOfRound.Instance.shipIsLeaving && StartOfRound.Instance.shipHasLanded) || !GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom) && !((Object)(object)component.inAnimationWithEnemy != (Object)null))
				{
					if (component.inSpecialInteractAnimation && (Object)(object)component.currentTriggerInAnimationWith != (Object)null)
					{
						component.currentTriggerInAnimationWith.CancelAnimationExternally();
					}
					FieldInfo field2 = typeFromHandle.GetField("triggerChaseByTouchingDebounce", BindingFlags.Instance | BindingFlags.NonPublic);
					bool flag2 = (bool)field2.GetValue(val);
					if (((EnemyAI)val).currentBehaviourStateIndex == 0 && !flag2)
					{
						field2.SetValue(val, true);
						MethodInfo method = typeFromHandle.GetMethod("BeginChasingNewPlayerServerRpc", BindingFlags.Instance | BindingFlags.NonPublic);
						method.Invoke(__instance, new object[1] { (int)component.playerClientId });
					}
					else
					{
						val.GrabPlayerServerRpc((int)component.playerClientId);
					}
				}
				return false;
			}
			return true;
		}
	}
	internal class MineAIPatch
	{
		public static void PatchOnTriggerEnter(ref Landmine __instance, Collider other, ref float ___pressMineDebounceTimer)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.AllowFairness(((Component)__instance).transform.position))
			{
				EnemyAICollisionDetect component = ((Component)other).gameObject.GetComponent<EnemyAICollisionDetect>();
				if ((Object)(object)component != (Object)null && !component.mainScript.isEnemyDead && Plugin.CanMob("ExplodeAllMobs", ".Mine", component.mainScript.enemyType.enemyName.ToUpper()))
				{
					___pressMineDebounceTimer = 0.5f;
					__instance.PressMineServerRpc();
				}
			}
		}

		public static void PatchOnTriggerExit(ref Landmine __instance, Collider other, ref bool ___sendingExplosionRPC)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.AllowFairness(((Component)__instance).transform.position))
			{
				EnemyAICollisionDetect component = ((Component)other).gameObject.GetComponent<EnemyAICollisionDetect>();
				if ((Object)(object)component != (Object)null && !component.mainScript.isEnemyDead && Plugin.CanMob("ExplodeAllMobs", ".Mine", component.mainScript.enemyType.enemyName.ToUpper()) && !__instance.hasExploded)
				{
					__instance.SetOffMineAnimation();
					___sendingExplosionRPC = true;
					__instance.ExplodeMineServerRpc();
				}
			}
		}

		public static void DetonatePatch(ref Landmine __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				((MonoBehaviour)__instance).StartCoroutine(WaitForUpdate(1.5f, __instance));
			}
		}

		public static IEnumerator WaitForUpdate(float waitTime, Landmine mine)
		{
			yield return (object)new WaitForSeconds(waitTime);
			if (!((Object)(object)mine == (Object)null))
			{
				if ((Object)(object)((Component)mine).GetComponent<NetworkObject>() != (Object)null)
				{
					((Component)mine).GetComponent<NetworkObject>().Despawn(true);
				}
				else
				{
					Object.Destroy((Object)(object)((Component)mine).gameObject);
				}
			}
		}

		public static void PatchSpawnExplosion(Vector3 explosionPosition, bool spawnExplosionEffect = false, float killRange = 1f, float damageRange = 1f)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(explosionPosition, 6f, 2621448, (QueryTriggerInteraction)2);
			for (int i = 0; i < array.Length; i++)
			{
				float num = Vector3.Distance(explosionPosition, ((Component)array[i]).transform.position);
				if ((num > 4f && Physics.Linecast(explosionPosition, ((Component)array[i]).transform.position + Vector3.up * 0.3f, 256, (QueryTriggerInteraction)1)) || !((Object)(object)((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>() != (Object)null))
				{
					continue;
				}
				EnemyAICollisionDetect component = ((Component)array[i]).gameObject.GetComponent<EnemyAICollisionDetect>();
				if ((Object)(object)component != (Object)null && ((NetworkBehaviour)component.mainScript).IsOwner && !component.mainScript.isEnemyDead)
				{
					if (num < killRange)
					{
						component.mainScript.HitEnemyOnLocalClient(component.mainScript.enemyHP, default(Vector3), (PlayerControllerB)null, false);
					}
					else if (num < damageRange)
					{
						component.mainScript.HitEnemyOnLocalClient(Mathf.RoundToInt((float)(component.mainScript.enemyHP / 2)), default(Vector3), (PlayerControllerB)null, false);
					}
				}
			}
		}
	}
	internal class RoundManagerPatch
	{
		public static void PatchStart(ref RoundManager __instance)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Expected O, but got Unknown
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Expected O, but got Unknown
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Expected O, but got Unknown
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Expected O, but got Unknown
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Expected O, but got Unknown
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0363: Expected O, but got Unknown
			Plugin.enemies = (from EnemyType e in Resources.FindObjectsOfTypeAll(typeof(EnemyType))
				where (Object)(object)e != (Object)null
				select e).ToList();
			Plugin.items = (from Item i in Resources.FindObjectsOfTypeAll(typeof(Item))
				where (Object)(object)i != (Object)null
				select i).ToList();
			Plugin.allHittablesMask = StartOfRound.Instance.collidersRoomMaskDefaultAndPlayers | 0x280008 | Plugin.enemyMask;
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "ExplodeAllMobs")))
			{
				ConfigEntry<bool> val = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "ExplodeAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Mines.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "BoombaAllMobs")))
			{
				ConfigEntry<bool> val2 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "BoombaAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Boombas.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretTargetAllMobs")))
			{
				ConfigEntry<bool> val3 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretTargetAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Targeted By Turrets.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretDamageAllMobs")))
			{
				ConfigEntry<bool> val4 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretDamageAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Killed By Turrets.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "CheckForPlayersInside")))
			{
				ConfigEntry<bool> val5 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "CheckForPlayersInside", false, "Whether to check for players inside the dungeon before anything else occurs.");
			}
			foreach (EnemyType enemy in Plugin.enemies)
			{
				string text = Plugin.RemoveInvalidCharacters(enemy.enemyName);
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Mine")))
				{
					ConfigEntry<bool> val6 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Mine", true, "Does it set off the landmine or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Boomba")))
				{
					ConfigEntry<bool> val7 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Boomba", true, "Does it set off the boomba or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Target")))
				{
					ConfigEntry<bool> val8 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Target", true, "Is it targetable by turrets?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Damage")))
				{
					ConfigEntry<bool> val9 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Damage", true, "Is it damageable by turrets?");
				}
			}
		}
	}
	internal class StartOfRoundPatch
	{
		public static void PatchStart(ref StartOfRound __instance)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Expected O, but got Unknown
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Expected O, but got Unknown
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Expected O, but got Unknown
			//IL_02a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Expected O, but got Unknown
			//IL_0301: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Expected O, but got Unknown
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0363: Expected O, but got Unknown
			Plugin.enemies = (from EnemyType e in Resources.FindObjectsOfTypeAll(typeof(EnemyType))
				where (Object)(object)e != (Object)null
				select e).ToList();
			Plugin.items = (from Item i in Resources.FindObjectsOfTypeAll(typeof(Item))
				where (Object)(object)i != (Object)null
				select i).ToList();
			Plugin.allHittablesMask = StartOfRound.Instance.collidersRoomMaskDefaultAndPlayers | 0x280008 | Plugin.enemyMask;
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "ExplodeAllMobs")))
			{
				ConfigEntry<bool> val = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "ExplodeAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Mines.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "BoombaAllMobs")))
			{
				ConfigEntry<bool> val2 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "BoombaAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Set Off Boombas.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretTargetAllMobs")))
			{
				ConfigEntry<bool> val3 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretTargetAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Targeted By Turrets.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "TurretDamageAllMobs")))
			{
				ConfigEntry<bool> val4 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "TurretDamageAllMobs", true, "Leave On To Customise Mobs Below Or Turn Off To Make All Mobs Unable To Be Killed By Turrets.");
			}
			if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", "CheckForPlayersInside")))
			{
				ConfigEntry<bool> val5 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", "CheckForPlayersInside", false, "Whether to check for players inside the dungeon before anything else occurs.");
			}
			foreach (EnemyType enemy in Plugin.enemies)
			{
				string text = Plugin.RemoveInvalidCharacters(enemy.enemyName);
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Mine")))
				{
					ConfigEntry<bool> val6 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Mine", true, "Does it set off the landmine or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Boomba")))
				{
					ConfigEntry<bool> val7 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Boomba", true, "Does it set off the boomba or not?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Target")))
				{
					ConfigEntry<bool> val8 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Target", true, "Is it targetable by turrets?");
				}
				if (!((BaseUnityPlugin)Plugin.Instance).Config.ContainsKey(new ConfigDefinition("Mobs", text + ".Turret Damage")))
				{
					ConfigEntry<bool> val9 = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Mobs", text + ".Turret Damage", true, "Is it damageable by turrets?");
				}
			}
		}

		public static void PatchUpdate(ref StartOfRound __instance)
		{
			if (Plugin.Can("CheckForPlayersInside"))
			{
				if (__instance.shipIsLeaving)
				{
					Plugin.playersEnteredInside = false;
				}
				else
				{
					Plugin.playersEnteredInside = Plugin.IsAPlayerInsideDungeon();
				}
			}
		}
	}
	internal class TurretAIPatch
	{
		public static float viewRadius = 10f;

		public static float viewAngle = 90f;

		public static void PatchStart(ref Turret __instance)
		{
			FAIR_AI component = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
			if ((Object)(object)component == (Object)null)
			{
				component = ((Component)__instance).gameObject.AddComponent<FAIR_AI>();
			}
		}

		public static bool PatchUpdate(ref Turret __instance)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Expected I4, but got Unknown
			//IL_0150: 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_00e6: Invalid comparison between Unknown and I4
			//IL_02c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Invalid comparison between Unknown and I4
			//IL_05d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d9: Invalid comparison between Unknown and I4
			//IL_078f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0795: Invalid comparison between Unknown and I4
			//IL_09d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_09db: Invalid comparison between Unknown and I4
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_032e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Invalid comparison between Unknown and O
			//IL_082b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0831: Invalid comparison between Unknown and O
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Expected O, but got Unknown
			//IL_08d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_08e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_08fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0908: Unknown result type (might be due to invalid IL or missing references)
			//IL_090d: Unknown result type (might be due to invalid IL or missing references)
			//IL_091f: Unknown result type (might be due to invalid IL or missing references)
			//IL_083e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0848: Expected O, but got Unknown
			//IL_0ddc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0df7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e10: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e1c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e2e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0946: Unknown result type (might be due to invalid IL or missing references)
			//IL_0955: Unknown result type (might be due to invalid IL or missing references)
			//IL_095a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0977: Unknown result type (might be due to invalid IL or missing references)
			//IL_097c: Unknown result type (might be due to invalid IL or missing references)
			//IL_098b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c1f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c2b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c46: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c52: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c57: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c74: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ba7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bad: Invalid comparison between Unknown and O
			//IL_0ea5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0eb1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ec3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e8b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ca6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ccc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cd1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cd7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cdc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ceb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bc4: Expected O, but got Unknown
			if (Plugin.AllowFairness(((Component)__instance).transform.position))
			{
				FAIR_AI component = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
				Type typeFromHandle = typeof(Turret);
				if (!__instance.turretActive)
				{
					FieldInfo field = typeFromHandle.GetField("wasTargetingPlayerLastFrame", BindingFlags.Instance | BindingFlags.NonPublic);
					field.SetValue(__instance, false);
					__instance.turretMode = (TurretMode)0;
					__instance.targetPlayerWithRotation = null;
					component.targetWithRotation = null;
					return false;
				}
				FieldInfo field2 = typeFromHandle.GetField("wasTargetingPlayerLastFrame", BindingFlags.Instance | BindingFlags.NonPublic);
				object value = field2.GetValue(__instance);
				if ((Object)(object)__instance.targetPlayerWithRotation != (Object)null || (Object)(object)component.targetWithRotation != (Object)null)
				{
					if (!(bool)value)
					{
						field2.SetValue(__instance, true);
						if ((int)__instance.turretMode == 0)
						{
							__instance.turretMode = (TurretMode)1;
						}
					}
					MethodInfo method = typeFromHandle.GetMethod("SetTargetToPlayerBody", BindingFlags.Instance | BindingFlags.NonPublic);
					method.Invoke(__instance, null);
					MethodInfo method2 = typeFromHandle.GetMethod("TurnTowardsTargetIfHasLOS", BindingFlags.Instance | BindingFlags.NonPublic);
					method2.Invoke(__instance, null);
				}
				else if ((bool)value)
				{
					field2.SetValue(__instance, false);
					__instance.turretMode = (TurretMode)0;
				}
				FieldInfo field3 = typeFromHandle.GetField("turretModeLastFrame", BindingFlags.Instance | BindingFlags.NonPublic);
				object value2 = field3.GetValue(__instance);
				FieldInfo field4 = typeFromHandle.GetField("rotatingClockwise", BindingFlags.Instance | BindingFlags.NonPublic);
				object value3 = field4.GetValue(__instance);
				FieldInfo field5 = typeFromHandle.GetField("fadeBulletAudioCoroutine", BindingFlags.Instance | BindingFlags.NonPublic);
				object value4 = field5.GetValue(__instance);
				FieldInfo field6 = typeFromHandle.GetField("turretInterval", BindingFlags.Instance | BindingFlags.NonPublic);
				object value5 = field6.GetValue(__instance);
				FieldInfo field7 = typeFromHandle.GetField("rotatingSmoothly", BindingFlags.Instance | BindingFlags.NonPublic);
				object value6 = field7.GetValue(__instance);
				FieldInfo field8 = typeFromHandle.GetField("switchRotationTimer", BindingFlags.Instance | BindingFlags.NonPublic);
				object value7 = field8.GetValue(__instance);
				FieldInfo field9 = typeFromHandle.GetField("rotatingRight", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field10 = typeFromHandle.GetField("hasLineOfSight", BindingFlags.Instance | BindingFlags.NonPublic);
				object value8 = field10.GetValue(__instance);
				FieldInfo field11 = typeFromHandle.GetField("lostLOSTimer", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field12 = typeFromHandle.GetField("shootRay", BindingFlags.Instance | BindingFlags.NonPublic);
				object value9 = field12.GetValue(__instance);
				FieldInfo field13 = typeFromHandle.GetField("hit", BindingFlags.Instance | BindingFlags.NonPublic);
				object value10 = field13.GetValue(__instance);
				FieldInfo field14 = typeFromHandle.GetField("berserkTimer", BindingFlags.Instance | BindingFlags.NonPublic);
				object value11 = field14.GetValue(__instance);
				FieldInfo field15 = typeFromHandle.GetField("enteringBerserkMode", BindingFlags.Instance | BindingFlags.NonPublic);
				object value12 = field15.GetValue(__instance);
				TurretMode turretMode = __instance.turretMode;
				TurretMode val = turretMode;
				RaycastHit val4;
				switch ((int)val)
				{
				case 0:
					value2 = field3.GetValue(__instance);
					if ((int)(TurretMode)value2 > 0)
					{
						field3.SetValue(__instance, (object)(TurretMode)0);
						field4.SetValue(__instance, false);
						__instance.mainAudio.Stop();
						__instance.farAudio.Stop();
						__instance.berserkAudio.Stop();
						value4 = field5.GetValue(__instance);
						if ((object)(Coroutine)value4 != null)
						{
							((MonoBehaviour)__instance).StopCoroutine((Coroutine)value4);
						}
						MethodInfo method4 = typeFromHandle.GetMethod("FadeBulletAudio", BindingFlags.Instance | BindingFlags.NonPublic);
						IEnumerator enumerator = (IEnumerator)method4.Invoke(__instance, null);
						field5.SetValue(__instance, ((MonoBehaviour)__instance).StartCoroutine(enumerator));
						__instance.bulletParticles.Stop(true, (ParticleSystemStopBehavior)1);
						__instance.rotationSpeed = 28f;
						field7.SetValue(__instance, true);
						__instance.turretAnimator.SetInteger("TurretMode", 0);
						field6.SetValue(__instance, Random.Range(0f, 0.15f));
					}
					if (!((NetworkBehaviour)__instance).IsServer)
					{
						break;
					}
					if ((float)value7 >= 7f)
					{
						field8.SetValue(__instance, 0f);
						value7 = field8.GetValue(__instance);
						bool flag = !(bool)field9.GetValue(__instance);
						__instance.SwitchRotationClientRpc(flag);
						__instance.SwitchRotationOnInterval(flag);
					}
					else
					{
						field8.SetValue(__instance, (float)value7 + Time.deltaTime);
					}
					value5 = field6.GetValue(__instance);
					if ((float)value5 >= 0.25f)
					{
						field6.SetValue(__instance, 0f);
						PlayerControllerB val5 = __instance.CheckForPlayersInLineOfSight(1.35f, true);
						List<EnemyAI> actualTargets = GetActualTargets(__instance, GetTargets(__instance));
						if ((Object)(object)val5 != (Object)null && !val5.isPlayerDead)
						{
							__instance.targetPlayerWithRotation = val5;
							MethodInfo method5 = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
							method5.Invoke(__instance, new object[1] { 1 });
							__instance.SwitchTargetedPlayerClientRpc((int)val5.playerClientId, true);
						}
						else if (actualTargets.Any())
						{
							__instance.targetPlayerWithRotation = null;
							component.targetWithRotation = actualTargets[0];
							MethodInfo method6 = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
							method6.Invoke(__instance, new object[1] { 1 });
							component.SwitchedTargetedEnemyClientRpc(__instance, actualTargets[0], setModeToCharging: true);
						}
					}
					else
					{
						value5 = field6.GetValue(__instance);
						field6.SetValue(__instance, (float)value5 + Time.deltaTime);
					}
					break;
				case 1:
					value2 = field3.GetValue(__instance);
					if ((int)(TurretMode)value2 != 1)
					{
						field3.SetValue(__instance, (object)(TurretMode)1);
						field4.SetValue(__instance, false);
						__instance.mainAudio.PlayOneShot(__instance.detectPlayerSFX);
						__instance.berserkAudio.Stop();
						WalkieTalkie.TransmitOneShotAudio(__instance.mainAudio, __instance.detectPlayerSFX, 1f);
						__instance.rotationSpeed = 95f;
						field7.SetValue(__instance, false);
						field11.SetValue(__instance, 0f);
						__instance.turretAnimator.SetInteger("TurretMode", 1);
					}
					if (!((NetworkBehaviour)__instance).IsServer)
					{
						break;
					}
					value5 = field6.GetValue(__instance);
					if ((float)value5 >= 1.5f)
					{
						field6.SetValue(__instance, 0f);
						Debug.Log((object)"Charging timer is up, setting to firing mode");
						if (!(bool)value8)
						{
							Debug.Log((object)"hasLineOfSight is false");
							__instance.targetPlayerWithRotation = null;
							component.targetWithRotation = null;
							__instance.RemoveTargetedPlayerClientRpc();
							component.RemoveTargetedEnemyClientRpc();
						}
						else
						{
							MethodInfo method7 = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
							method7.Invoke(__instance, new object[1] { 2 });
							__instance.SetToModeClientRpc(2);
						}
					}
					else
					{
						value5 = field6.GetValue(__instance);
						field6.SetValue(__instance, (float)value5 + Time.deltaTime);
					}
					break;
				case 2:
					value2 = field3.GetValue(__instance);
					if ((int)(TurretMode)value2 != 2)
					{
						field3.SetValue(__instance, (object)(TurretMode)2);
						__instance.berserkAudio.Stop();
						__instance.mainAudio.clip = __instance.firingSFX;
						__instance.mainAudio.Play();
						__instance.farAudio.clip = __instance.firingFarSFX;
						__instance.farAudio.Play();
						__instance.bulletParticles.Play(true);
						__instance.bulletCollisionAudio.Play();
						value4 = field5.GetValue(__instance);
						if ((object)(Coroutine)value4 != null)
						{
							((MonoBehaviour)__instance).StopCoroutine((Coroutine)value4);
						}
						__instance.bulletCollisionAudio.volume = 1f;
						field7.SetValue(__instance, false);
						field11.SetValue(__instance, 0f);
						__instance.turretAnimator.SetInteger("TurretMode", 2);
					}
					value5 = field6.GetValue(__instance);
					if ((float)value5 >= 0.21f)
					{
						field6.SetValue(__instance, 0f);
						Plugin.AttackTargets(__instance.aimPoint.position, __instance.aimPoint.forward, 30f);
						field12.SetValue(__instance, (object)new Ray(__instance.aimPoint.position, __instance.aimPoint.forward));
						RaycastHit val6 = default(RaycastHit);
						if (Physics.Raycast((Ray)value9, ref val6, 30f, StartOfRound.Instance.collidersAndRoomMask, (QueryTriggerInteraction)1))
						{
							field13.SetValue(__instance, val6);
							Ray val7 = (Ray)value9;
							value10 = field13.GetValue(__instance);
							Transform transform2 = ((Component)__instance.bulletCollisionAudio).transform;
							val4 = (RaycastHit)value10;
							transform2.position = ((Ray)(ref val7)).GetPoint(((RaycastHit)(ref val4)).distance - 0.5f);
						}
					}
					else
					{
						value5 = field6.GetValue(__instance);
						field6.SetValue(__instance, (float)value5 + Time.deltaTime);
					}
					break;
				case 3:
					value2 = field3.GetValue(__instance);
					if ((int)(TurretMode)value2 != 3)
					{
						field3.SetValue(__instance, (object)(TurretMode)3);
						__instance.turretAnimator.SetInteger("TurretMode", 1);
						field14.SetValue(__instance, 1.3f);
						__instance.berserkAudio.Play();
						__instance.rotationSpeed = 77f;
						field15.SetValue(__instance, true);
						field7.SetValue(__instance, true);
						field11.SetValue(__instance, 0f);
						field2.SetValue(__instance, false);
						__instance.targetPlayerWithRotation = null;
						component.targetWithRotation = null;
					}
					value12 = field15.GetValue(__instance);
					if ((bool)value12)
					{
						value11 = field14.GetValue(__instance);
						field14.SetValue(__instance, (float)value11 - Time.deltaTime);
						value11 = field14.GetValue(__instance);
						if ((float)value11 <= 0f)
						{
							field15.SetValue(__instance, false);
							field4.SetValue(__instance, true);
							field14.SetValue(__instance, 9f);
							__instance.turretAnimator.SetInteger("TurretMode", 2);
							__instance.mainAudio.clip = __instance.firingSFX;
							__instance.mainAudio.Play();
							__instance.farAudio.clip = __instance.firingFarSFX;
							__instance.farAudio.Play();
							__instance.bulletParticles.Play(true);
							__instance.bulletCollisionAudio.Play();
							value4 = field5.GetValue(__instance);
							if ((object)(Coroutine)value4 != null)
							{
								((MonoBehaviour)__instance).StopCoroutine((Coroutine)value4);
							}
							__instance.bulletCollisionAudio.volume = 1f;
						}
						break;
					}
					value5 = field6.GetValue(__instance);
					if ((float)value5 >= 0.21f)
					{
						field6.SetValue(__instance, 0f);
						Plugin.AttackTargets(__instance.aimPoint.position, __instance.aimPoint.forward, 30f);
						field12.SetValue(__instance, (object)new Ray(__instance.aimPoint.position, __instance.aimPoint.forward));
						value9 = field12.GetValue(__instance);
						RaycastHit val2 = default(RaycastHit);
						if (Physics.Raycast((Ray)value9, ref val2, 30f, StartOfRound.Instance.collidersAndRoomMask, (QueryTriggerInteraction)1))
						{
							value9 = field12.GetValue(__instance);
							field13.SetValue(__instance, val2);
							value10 = field12.GetValue(__instance);
							Transform transform = ((Component)__instance.bulletCollisionAudio).transform;
							Ray val3 = (Ray)value9;
							val4 = (RaycastHit)value10;
							transform.position = ((Ray)(ref val3)).GetPoint(((RaycastHit)(ref val4)).distance - 0.5f);
						}
					}
					else
					{
						value5 = field6.GetValue(__instance);
						field6.SetValue(__instance, (float)value5 - Time.deltaTime);
					}
					if (((NetworkBehaviour)__instance).IsServer)
					{
						value11 = field14.GetValue(__instance);
						field14.SetValue(__instance, (float)value11 - Time.deltaTime);
						value11 = field14.GetValue(__instance);
						if ((float)value11 <= 0f)
						{
							MethodInfo method3 = typeFromHandle.GetMethod("SwitchTurretMode", BindingFlags.Instance | BindingFlags.NonPublic);
							method3.Invoke(__instance, new object[1] { 0 });
							__instance.SetToModeClientRpc(0);
						}
					}
					break;
				}
				value3 = field4.GetValue(__instance);
				if ((bool)value3)
				{
					__instance.turnTowardsObjectCompass.localEulerAngles = new Vector3(-180f, __instance.turretRod.localEulerAngles.y - Time.deltaTime * 20f, 180f);
					__instance.turretRod.rotation = Quaternion.RotateTowards(__instance.turretRod.rotation, __instance.turnTowardsObjectCompass.rotation, __instance.rotationSpeed * Time.deltaTime);
					return false;
				}
				value6 = field7.GetValue(__instance);
				if ((bool)value6)
				{
					__instance.turnTowardsObjectCompass.localEulerAngles = new Vector3(-180f, Mathf.Clamp(__instance.targetRotation, 0f - __instance.rotationRange, __instance.rotationRange), 180f);
				}
				__instance.turretRod.rotation = Quaternion.RotateTowards(__instance.turretRod.rotation, __instance.turnTowardsObjectCompass.rotation, __instance.rotationSpeed * Time.deltaTime);
			}
			return false;
		}

		public static bool PatchSetTargetToPlayerBody(ref Turret __instance)
		{
			Type typeFromHandle = typeof(Turret);
			FieldInfo field = typeFromHandle.GetField("targetingDeadPlayer", BindingFlags.Instance | BindingFlags.NonPublic);
			object value = field.GetValue(__instance);
			if ((Object)(object)__instance.targetPlayerWithRotation != (Object)null)
			{
				if (__instance.targetPlayerWithRotation.isPlayerDead)
				{
					value = field.GetValue(__instance);
					if (!(bool)value)
					{
						field.SetValue(__instance, true);
					}
					if ((Object)(object)__instance.targetPlayerWithRotation.deadBody != (Object)null)
					{
						__instance.targetTransform = ((Component)__instance.targetPlayerWithRotation.deadBody.bodyParts[5]).transform;
					}
					FAIR_AI component = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
					if ((Object)(object)component.targetWithRotation != (Object)null)
					{
						value = field.GetValue(__instance);
						if (!(bool)value)
						{
							field.SetValue(__instance, true);
						}
						value = field.GetValue(__instance);
						if (!((Component)component.targetWithRotation).GetComponent<EnemyAI>().isEnemyDead)
						{
							field.SetValue(__instance, false);
							__instance.targetTransform = ((Component)component.targetWithRotation).transform;
						}
					}
				}
				else
				{
					field.SetValue(__instance, false);
					__instance.targetTransform = ((Component)__instance.targetPlayerWithRotation.gameplayCamera).transform;
				}
			}
			else
			{
				FAIR_AI component2 = ((Component)__instance).gameObject.GetComponent<FAIR_AI>();
				if ((Object)(object)component2.targetWithRotation != (Object)null)
				{
					value = field.GetValue(__instance);
					if (!(bool)value)
					{
						field.SetValue(__instance, true);
					}
					value = field.GetValue(__instance);
					if (!((Component)component2.targetWithRotation).GetComponent<EnemyAI>().isEnemyDead)
					{
						field.SetValue(__instance, false);
						__instance.targetTransform = ((Component)component2.targetWithRotation).transform;
					}
				}
			}
			return false;
		}

		public static bool PatchTurnTowardsTargetIfHasLOS(ref Turret __instance)
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: 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_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			if (TurnTowardsTargetEnemyIfHasLOS(__instance))
			{
				return false;
			}
			bool flag = true;
			Type typeFromHandle = typeof(Turret);
			FieldInfo field = typeFromHandle.GetField("targetingDeadPlayer", BindingFlags.Instance | BindingFlags.NonPublic);
			object value = field.GetValue(__instance);
			FieldInfo field2 = typeFromHandle.GetField("hasLineOfSight", BindingFlags.Instance | BindingFlags.NonPublic);
			object value2 = field.GetValue(__instance);
			FieldInfo field3 = typeFromHandle.GetField("lostLOSTimer", BindingFlags.Instance | BindingFlags.NonPublic);
			object value3 = field.GetValue(__instance);
			if ((bool)value || Vector3.Angle(__instance.targetTransform.position - __instance.centerPoint.position, __instance.forwardFacingPos.forward) > __instance.rotationRange)
			{
				flag = false;
			}
			if (Physics.Linecast(__instance.aimPoint.position, __instance.targetTransform.position, StartOfRound.Instance.collidersAndRoomMask, (QueryTriggerInteraction)1))
			{
				flag = false;
			}
			if (flag)
			{
				field2.SetValue(__instance, true);
				field3.SetValue(__instance, 0f);
				__instance.tempTransform.position = __instance.targetTransform.position;
				Transform tempTransform = __instance.tempTransform;
				tempTransform.position -= Vector3.up * 0.15f;
				__instance.turnTowardsObjectCompass.LookAt(__instance.tempTransform);
				return false;
			}
			value2 = field2.GetValue(__instance);
			if ((bool)value2)
			{
				field2.SetValue(__instance, false);
				field3.SetValue(__instance, 0f);
			}
			if (!((NetworkBehaviour)__instance).IsServer)
			{
				return false;
			}
			value3 = field3.GetValue(__instance);
			field3.SetValue(__instance, (float)value3 + Time.deltaTime);
			value3 = field3.GetValue(__instance);
			if ((float)value3 >= 2f)
			{
				field3.SetValue(__instance, 0f);
				Debug.Log((object)"Turret: LOS timer ended on server. checking for new player target");
				PlayerControllerB val = __instance.CheckForPlayersInLineOfSight(2f, false);
				List<EnemyAI> actualTargets = GetActualTargets(__instance, GetTargets(__instance));
				if ((Object)(object)val != (Object)null)
				{
					__instance.targetPlayerWithRotation = val;
					__instance.SwitchTargetedPlayerClientRpc((int)val.playerClientId, false);
					Debug.Log((object)"Turret: Got new player target");
				}
				else
				{
					Debug.Log((object)"Turret: No new player to target; returning to detection mode.");
					__instance.targetPlayerWithRotation = null;
					__instance.RemoveTargetedPlayerClientRpc();
				}
			}
			return false;
		}

		public static bool TurnTowardsTargetEnemyIfHasLOS(Turret turret)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: 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_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			bool flag = true;
			Type typeFromHandle = typeof(Turret);
			FieldInfo field = typeFromHandle.GetField("targetingDeadPlayer", BindingFlags.Instance | BindingFlags.NonPublic);
			object value = field.GetValue(turret);
			FieldInfo field2 = typeFromHandle.GetField("hasLineOfSight", BindingFlags.Instance | BindingFlags.NonPublic);
			FieldInfo field3 = typeFromHandle.GetField("lostLOSTimer", BindingFlags.Instance | BindingFlags.NonPublic);
			if ((bool)value || Vector3.Angle(turret.targetTransform.position - turret.centerPoint.position, turret.forwardFacingPos.forward) > turret.rotationRange)
			{
				flag = false;
			}
			if (Physics.Linecast(turret.aimPoint.position, turret.targetTransform.position, StartOfRound.Instance.collidersAndRoomMask, (QueryTriggerInteraction)1))
			{
				flag = false;
			}
			List<EnemyAI> actualTargets = GetActualTargets(turret, GetTargets(turret));
			if (flag && actualTargets != null && actualTargets.Any())
			{
				field2.SetValue(turret, true);
				field3.SetValue(turret, 0f);
				if ((Object)(object)((Component)turret).GetComponent<FAIR_AI>() != (Object)null)
				{
					FAIR_AI component = ((Component)turret).GetComponent<FAIR_AI>();
					if ((Object)(object)component.targetWithRotation == (Object)null)
					{
						component.targetWithRotation = actualTargets[0];
					}
					turret.tempTransform.position = ((Component)component.targetWithRotation).transform.position;
					Transform tempTransform = turret.tempTransform;
					tempTransform.position -= Vector3.up * 0.15f;
					turret.turnTowardsObjectCompass.LookAt(turret.tempTransform);
				}
				return flag;
			}
			object value2 = field2.GetValue(turret);
			if ((bool)value2)
			{
				field2.SetValue(turret, false);
				field3.SetValue(turret, 0f);
			}
			if (!((NetworkBehaviour)turret).IsServer)
			{
				return false;
			}
			FAIR_AI component2 = ((Component)turret).gameObject.GetComponent<FAIR_AI>();
			List<EnemyAI> actualTargets2 = GetActualTargets(turret, GetTargets(turret));
			if (actualTargets2.Any())
			{
				component2.targetWithRotation = actualTargets2[0];
				component2.SwitchedTargetedEnemyClientRpc(turret, actualTargets2[0]);
				return true;
			}
			component2.targetWithRotation = null;
			component2.RemoveTargetedEnemyClientRpc();
			return false;
		}

		public static List<EnemyAI> GetActualTargets(Turret turret, List<EnemyAI> targets)
		{
			List<EnemyAI> list = new List<EnemyAI>();
			if (targets != null)
			{
				targets.RemoveAll((EnemyAI t) => (Object)(object)t == (Object)null);
				if (targets.Any())
				{
					foreach (EnemyAI target in targets)
					{
						if ((Object)(object)target != (Object)null && !target.isEnemyDead && Plugin.CanMob("TurretTargetAllMobs", ".Turret Target", target.enemyType.enemyName))
						{
							list.Add(target);
						}
					}
				}
			}
			return list;
		}

		private static List<EnemyAI> GetTargets(Turret turret, float radius = 2f, bool angleRangeCheck = false)
		{
			List<Transform> list = FindVisibleTargets(turret);
			List<EnemyAI> en = new List<EnemyAI>();
			if (list.Any())
			{
				list.ForEach(delegate(Transform e)
				{
					EnemyAICollisionDetect component = ((Component)e).GetComponent<EnemyAICollisionDetect>();
					EnemyAI val = ((Component)component).GetComponent<EnemyAI>();
					if ((Object)(object)component != (Object)null)
					{
						val = component.mainScript;
					}
					if ((Object)(object)val != (Object)null && Plugin.CanMob("TurretTargetAllMobs", ".Turret Target", val.enemyType.enemyName))
					{
						en.Add(val);
					}
				});
			}
			return en;
		}

		public static Vector3 DirectionFromAngle(Turret turret, float angleInDegrees, bool angleIsGlobal)
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (!angleIsGlobal)
			{
				angleInDegrees += ((Component)turret).transform.eulerAngles.y;
			}
			return new Vector3(Mathf.Sin(angleInDegrees * ((float)Math.PI / 180f)), 0f, Mathf.Cos(angleInDegrees * ((float)Math.PI / 180f)));
		}

		public static List<Transform> FindVisibleTargets(Turret turret)
		{
			//IL_0007: 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)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: 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_0089: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
			Collider[] array = Physics.OverlapSphere(turret.aimPoint.position, viewRadius, Plugin.enemyMask);
			List<Transform> list = new List<Transform>();
			for (int i = 0; i < array.Length; i++)
			{
				Transform transform = ((Component)array[i]).transform;
				Vector3 val = transform.position - turret.aimPoint.position;
				Vector3 normalized = ((Vector3)(ref val)).normalized;
				if (!(Vector3.Angle(turret.aimPoint.forward, normalized) < viewAngle / 2f))
				{
					continue;
				}
				float num = Vector3.Distance(turret.aimPoint.position, transform.position);
				if (!Physics.Raycast(turret.aimPoint.position, normalized, num, ~Plugin.enemyMask))
				{
					if ((Object)(object)((Component)transform).GetComponent<EnemyAICollisionDetect>() != (Object)null && Plugin.CanMob("TurretTargetAllMobs", ".Turret Target", ((Component)transform).GetComponent<EnemyAICollisionDetect>().mainScript.enemyType.enemyName))
					{
						list.Add(transform);
					}
					if ((Object)(object)((Component)transform).GetComponent<EnemyAI>() != (Object)null && Plugin.CanMob("TurretTargetAllMobs", ".Turret Target", ((Component)transform).GetComponent<EnemyAI>().enemyType.enemyName))
					{
						list.Add(transform);
					}
				}
			}
			return list;
		}
	}
}
namespace FairAI.Component
{
	internal class BoombaTimer : MonoBehaviour
	{
		private bool isActiveBomb = false;

		private void Start()
		{
			((MonoBehaviour)this).StartCoroutine(StartBombTimer());
			Plugin.logger.LogInfo((object)"Boomba has been set active.");
		}

		public IEnumerator StartBombTimer()
		{
			SetActiveBomb(isActive: false);
			yield return (object)new WaitForSeconds(3f);
			SetActiveBomb(isActive: true);
		}

		public void SetActiveBomb(bool isActive)
		{
			isActiveBomb = isActive;
		}

		public bool IsActiveBomb()
		{
			return isActiveBomb;
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/FreddyBracken.dll

Decompiled 7 months ago
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FreddyBracken")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FreddyBracken")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("2ed810b2-476e-4150-b015-645ee4681b3d")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace FreddyBracken
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "FreddyBracken";

		public const string PLUGIN_NAME = "FreddyBracken";

		public const string PLUGIN_VERSION = "1.0.4";
	}
	[BepInPlugin("FreddyBracken", "FreddyBracken", "1.0.4")]
	public class Plugin : BaseUnityPlugin
	{
		public static GameObject Visuals;

		public static AudioClip NeckCrackAudio;

		public static AudioClip AngeredAudio;

		public static Texture2D FreddyMaterial;

		public static Texture2D FreddyNormal;

		public static Texture2D FreddyEyes;

		public static ConfigEntry<bool> useFreddyTextures;

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin FreddyBracken is loaded!");
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
			string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "freddy.bundle");
			AssetBundle val = AssetBundle.LoadFromFile(text);
			Visuals = val.LoadAsset<GameObject>("assets/prefabs/freddy.prefab");
			NeckCrackAudio = val.LoadAsset<AudioClip>("assets/prefabs/freddycrackneck.wav");
			AngeredAudio = val.LoadAsset<AudioClip>("assets/prefabs/freddyangered.wav");
			FreddyMaterial = val.LoadAsset<Texture2D>("assets/prefabs/freddy_albedo.png");
			FreddyNormal = val.LoadAsset<Texture2D>("assets/prefabs/freddy_normal.png");
			FreddyEyes = val.LoadAsset<Texture2D>("assets/prefabs/freddy_eyes_albedo.png");
			useFreddyTextures = ((BaseUnityPlugin)this).Config.Bind<bool>("FreddyBracken", "UseFreddyTextures", false, "Swap out the default dark Bracken body material for Freddy's actual brown fur, bowtie, etc materials.");
			SkinnedMeshRenderer[] componentsInChildren = Visuals.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			foreach (SkinnedMeshRenderer val2 in componentsInChildren)
			{
				((Component)val2).gameObject.layer = LayerMask.NameToLayer("Enemies");
			}
		}
	}
}
namespace FreddyBracken.Patches
{
	[HarmonyPatch(typeof(FlowermanAI), "Start")]
	internal class FlowermanPatch
	{
		private static void Postfix(FlowermanAI __instance)
		{
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Expected O, but got Unknown
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Expected O, but got Unknown
			if ((Object)(object)Plugin.Visuals == (Object)null)
			{
				return;
			}
			Transform val = ((Component)__instance).transform.Find("FlowermanModel");
			object obj;
			if (val == null)
			{
				obj = null;
			}
			else
			{
				Transform obj2 = val.Find("LOD1");
				obj = ((obj2 != null) ? ((Component)obj2).GetComponent<SkinnedMeshRenderer>() : null);
			}
			SkinnedMeshRenderer val2 = (SkinnedMeshRenderer)obj;
			object obj3;
			if (val == null)
			{
				obj3 = null;
			}
			else
			{
				Transform obj4 = val.Find("AnimContainer");
				obj3 = ((obj4 != null) ? obj4.Find("metarig") : null);
			}
			Transform val3 = (Transform)obj3;
			if (!((Object)(object)val2 == (Object)null) && ((Renderer)val2).enabled)
			{
				((Renderer)val2).enabled = false;
				Renderer[] componentsInChildren = ((Component)val3).gameObject.GetComponentsInChildren<Renderer>();
				foreach (Renderer val4 in componentsInChildren)
				{
					val4.enabled = false;
				}
				GameObject val5 = Object.Instantiate<GameObject>(Plugin.Visuals);
				val5.transform.SetParent(val);
				val5.transform.localPosition = Vector3.zero;
				val5.transform.localRotation = Quaternion.identity;
				val5.transform.localScale = Vector3.one;
				Transform val6 = val5.transform.Find("Container/Body_Geo");
				Transform val7 = val5.transform.Find("Container/metarig");
				val7.SetParent(val3.parent, true);
				((Component)val7).transform.localScale = ((Component)val3).transform.localScale;
				((Component)val7).transform.localRotation = ((Component)val3).transform.localRotation;
				((Component)val7).transform.localPosition = ((Component)val3).transform.localPosition;
				SkinnedMeshRenderer component = ((Component)val6).GetComponent<SkinnedMeshRenderer>();
				component.rootBone = val7;
				if (Plugin.useFreddyTextures.Value)
				{
					MaterialPropertyBlock val8 = new MaterialPropertyBlock();
					((Renderer)component).GetPropertyBlock(val8, 0);
					val8.SetColor("_BaseColor", Color.white);
					val8.SetColor("_Color", Color.white);
					val8.SetTexture("_BaseColorMap", (Texture)(object)Plugin.FreddyMaterial);
					val8.SetVector("_BaseColorMap_ST", new Vector4(1f, 1f, 0f, 0f));
					val8.SetFloat("_NormalMapSpace", 0f);
					val8.SetTexture("_NormalMap", (Texture)(object)Plugin.FreddyNormal);
					val8.SetVector("_NormalMap_ST", new Vector4(1f, 1f, 0f, 0f));
					val8.SetFloat("_Metallic", 0f);
					((Renderer)component).SetPropertyBlock(val8, 0);
					MaterialPropertyBlock val9 = new MaterialPropertyBlock();
					((Renderer)component).GetPropertyBlock(val9, 1);
					val8.SetTexture("_BaseColorMap", (Texture)(object)Plugin.FreddyEyes);
					((Renderer)component).SetPropertyBlock(val9, 1);
				}
				((Object)val3).name = "old-metarig";
				__instance.crackNeckSFX = Plugin.NeckCrackAudio;
				__instance.creatureAngerVoice.clip = Plugin.AngeredAudio;
				__instance.rightHandGrip = val7.Find("Torso1").Find("Torso2").Find("Torso3")
					.Find("Arm1.R")
					.Find("Arm2.R")
					.Find("Arm3.R")
					.Find("Hand1.R")
					.Find("HandGripPosition");
			}
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/GokuSpiders.dll

Decompiled 7 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using LethalCompanyGokuSpiders;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("GokuSpiders")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP")]
[assembly: AssemblyProduct("GokuSpiders")]
[assembly: AssemblyCopyright("Copyright © HP 2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("97e220e6-98a7-4a53-9470-2546a962ab77")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Goku.Patches
{
	[HarmonyPatch]
	internal class EnemyTypes
	{
		[HarmonyPatch(typeof(SandSpiderAI), "Start")]
		[HarmonyPostfix]
		public static void SummonGoku(SandSpiderAI __instance)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Expected O, but got Unknown
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			ManualLogSource val = new ManualLogSource("GokuSpiders");
			Logger.Sources.Add((ILogSource)val);
			string text = "null";
			text = "Assets/gok.prefab";
			try
			{
				Object.Destroy((Object)(object)((Component)((Component)__instance).gameObject.transform.Find("MeshContainer").Find("MeshRenderer")).gameObject.GetComponent<SkinnedMeshRenderer>());
				Object.Destroy((Object)(object)((Component)((Component)__instance).gameObject.transform.Find("MeshContainer").Find("AnimContainer").Find("Armature")
					.Find("Head")
					.Find("RightFang")).gameObject.GetComponent<MeshRenderer>());
				Object.Destroy((Object)(object)((Component)((Component)__instance).gameObject.transform.Find("MeshContainer").Find("AnimContainer").Find("Armature")
					.Find("Head")
					.Find("RightFang")).gameObject.GetComponent<MeshFilter>());
				Object.Destroy((Object)(object)((Component)((Component)__instance).gameObject.transform.Find("MeshContainer").Find("AnimContainer").Find("Armature")
					.Find("Head")
					.Find("LeftFang")).gameObject.GetComponent<MeshRenderer>());
				Object.Destroy((Object)(object)((Component)((Component)__instance).gameObject.transform.Find("MeshContainer").Find("AnimContainer").Find("Armature")
					.Find("Head")
					.Find("LeftFang")).gameObject.GetComponent<MeshFilter>());
				GameObject val2 = Plugin.LoadedBundle.LoadAsset<GameObject>(text);
				if ((Object)val2 == (Object)null)
				{
					Debug.LogError((object)"Goku prefab not loaded!");
					return;
				}
				GameObject val3 = Object.Instantiate<GameObject>(Plugin.LoadedBundle.LoadAsset<GameObject>(text), ((Component)__instance).gameObject.transform);
				Debug.Log((object)"SPAWNED GOKU AEAEAEE");
				val3.transform.SetParent(((Component)__instance).transform, false);
				val3.transform.localPosition = new Vector3(0f, 2.2f, 0f);
			}
			catch (Exception arg)
			{
				Debug.LogError((object)$"Exception: {arg}");
			}
		}
	}
}
namespace LethalCompanyGokuSpiders
{
	[BepInPlugin("GokuSpiders", "GokuSpiders", "1.0.1")]
	public class Plugin : BaseUnityPlugin
	{
		public Harmony harmonymain;

		public static AssetBundle LoadedBundle;

		private void Awake()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			harmonymain = new Harmony("GokuSpiders");
			harmonymain.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin GokuSpiders is loaded!");
			string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "Gok");
			AssetBundle val = AssetBundle.LoadFromFile(text);
			if ((Object)val == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Failed to load GokuSpiders AssetBundle! (Bundle should be located in the same folder as mod!)");
				return;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Successfully loaded GokuSpiders AssetBundle!");
			LoadedBundle = val;
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "GokuSpiders";

		public const string PLUGIN_NAME = "GokuSpiders";

		public const string PLUGIN_VERSION = "1.0.1";
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/LC_API.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.BundleAPI;
using LC_API.ClientAPI;
using LC_API.Comp;
using LC_API.Data;
using LC_API.Exceptions;
using LC_API.Extensions;
using LC_API.GameInterfaceAPI;
using LC_API.GameInterfaceAPI.Events;
using LC_API.GameInterfaceAPI.Events.Cache;
using LC_API.GameInterfaceAPI.Events.EventArgs.Player;
using LC_API.GameInterfaceAPI.Events.Handlers;
using LC_API.GameInterfaceAPI.Features;
using LC_API.ManualPatches;
using LC_API.Networking;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("2018")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Utilities for plugin devs")]
[assembly: AssemblyFileVersion("3.4.5.0")]
[assembly: AssemblyInformationalVersion("3.4.5+ae2de74676f4f0d6440c82067f4c1a22389fe27b")]
[assembly: AssemblyProduct("Lethal Company API")]
[assembly: AssemblyTitle("LC_API")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("3.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LC_API
{
	internal static class CheatDatabase
	{
		private const string SIG_REQ_GUID = "LC_API_ReqGUID";

		private const string SIG_SEND_MODS = "LC_APISendMods";

		private static Dictionary<string, PluginInfo> PluginsLoaded = new Dictionary<string, PluginInfo>();

		public static void RunLocalCheatDetector()
		{
			PluginsLoaded = Chainloader.PluginInfos;
			using Dictionary<string, PluginInfo>.ValueCollection.Enumerator enumerator = PluginsLoaded.Values.GetEnumerator();
			while (enumerator.MoveNext())
			{
				switch (enumerator.Current.Metadata.GUID)
				{
				case "mikes.lethalcompany.mikestweaks":
				case "mom.llama.enhancer":
				case "Posiedon.GameMaster":
				case "LethalCompanyScalingMaster":
				case "verity.amberalert":
					ModdedServer.SetServerModdedOnly();
					break;
				}
			}
		}

		public static void OtherPlayerCheatDetector()
		{
			Plugin.Log.LogWarning((object)"Asking all other players for their mod list..");
			LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.QueueTip("Mod List:", "Asking all other players for installed mods..");
			LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.QueueTip("Mod List:", "Check the logs for more detailed results.\n<size=13>(Note that if someone doesnt show up on the list, they may not have LC_API installed)</size>");
			Network.Broadcast("LC_API_ReqGUID");
		}

		[NetworkMessage("LC_APISendMods", false)]
		internal static void ReceivedModListHandler(ulong senderId, List<string> mods)
		{
			string text = LC_API.GameInterfaceAPI.Features.Player.Get(senderId).Username + " responded with these mods:\n" + string.Join("\n", mods);
			LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.QueueTip("Mod List:", text);
			Plugin.Log.LogWarning((object)text);
		}

		[NetworkMessage("LC_API_ReqGUID", false)]
		internal static void ReceivedModListHandler(ulong senderId)
		{
			List<string> list = new List<string>();
			foreach (PluginInfo value in PluginsLoaded.Values)
			{
				list.Add(value.Metadata.GUID);
			}
			Network.Broadcast("LC_APISendMods", list);
		}
	}
	[BepInPlugin("LC_API", "Lethal Company API", "3.4.5")]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		private ConfigEntry<bool> configOverrideModServer;

		private ConfigEntry<bool> configLegacyAssetLoading;

		private ConfigEntry<bool> configDisableBundleLoader;

		internal static ConfigEntry<bool> configVanillaSupport;

		internal static Harmony Harmony;

		internal static Plugin Instance { get; private set; }

		public static bool Initialized { get; private set; }

		private void Awake()
		{
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Expected O, but got Unknown
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Expected O, but got Unknown
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Expected O, but got Unknown
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Expected O, but got Unknown
			//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d2: Expected O, but got Unknown
			//IL_02dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ea: Expected O, but got Unknown
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Expected O, but got Unknown
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_031a: Expected O, but got Unknown
			Instance = this;
			configOverrideModServer = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Force modded server browser", false, "Should the API force you into the modded server browser?");
			configLegacyAssetLoading = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Legacy asset bundle loading", false, "Should the BundleLoader use legacy asset loading? Turning this on may help with loading assets from older plugins.");
			configDisableBundleLoader = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Disable BundleLoader", false, "Should the BundleLoader be turned off? Enable this if you are having problems with mods that load assets using a different method from LC_API's BundleLoader.");
			configVanillaSupport = ((BaseUnityPlugin)this).Config.Bind<bool>("Compatibility", "Vanilla Compatibility", false, "Allows you to join vanilla servers, but disables many networking-related things and could cause mods to not work properly.");
			CommandHandler.commandPrefix = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Prefix", "/", "Command prefix");
			Log = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogWarning((object)"\n.____    _________           _____  __________ .___  \r\n|    |   \\_   ___ \\         /  _  \\ \\______   \\|   | \r\n|    |   /    \\  \\/        /  /_\\  \\ |     ___/|   | \r\n|    |___\\     \\____      /    |    \\|    |    |   | \r\n|_______ \\\\______  /______\\____|__  /|____|    |___| \r\n        \\/       \\//_____/        \\/                 \r\n                                                     ");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Starting up..");
			if (configOverrideModServer.Value)
			{
				ModdedServer.SetServerModdedOnly();
			}
			if (configVanillaSupport.Value)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API is starting with VANILLA SUPPORT ENABLED.");
			}
			Harmony = new Harmony("ModAPI");
			MethodInfo methodInfo = AccessTools.Method(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyCreated", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(GameNetworkManager), "LobbyDataIsJoinable", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(ServerPatch), "OnLobbyCreate", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(MenuManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(ServerPatch), "CacheMenuManager", (Type[])null, (Type[])null);
			AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(typeof(HUDManager), "SubmitChat_performed", (Type[])null, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(typeof(CommandHandler.SubmitChatPatch), "Transpiler", (Type[])null, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.Method(typeof(GameNetworkManager), "Awake", (Type[])null, (Type[])null);
			MethodInfo methodInfo8 = AccessTools.Method(typeof(ServerPatch), "GameNetworkManagerAwake", (Type[])null, (Type[])null);
			MethodInfo methodInfo9 = AccessTools.Method(typeof(NetworkManager), "StartClient", (Type[])null, (Type[])null);
			MethodInfo methodInfo10 = AccessTools.Method(typeof(NetworkManager), "StartHost", (Type[])null, (Type[])null);
			MethodInfo methodInfo11 = AccessTools.Method(typeof(NetworkManager), "Shutdown", (Type[])null, (Type[])null);
			MethodInfo methodInfo12 = AccessTools.Method(typeof(RegisterPatch), "Postfix", (Type[])null, (Type[])null);
			MethodInfo methodInfo13 = AccessTools.Method(typeof(UnregisterPatch), "Postfix", (Type[])null, (Type[])null);
			Harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo7, new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo9, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo10, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Harmony.Patch((MethodBase)methodInfo11, (HarmonyMethod)null, new HarmonyMethod(methodInfo13), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Network.Init();
			Events.Patch(Harmony);
		}

		internal void Start()
		{
			Initialize();
		}

		internal void OnDestroy()
		{
			Initialize();
		}

		internal void Initialize()
		{
			//IL_002f: 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)
			//IL_003a: Expected O, but got Unknown
			if (!Initialized)
			{
				Initialized = true;
				if (!configDisableBundleLoader.Value)
				{
					BundleLoader.Load(configLegacyAssetLoading.Value);
				}
				GameObject val = new GameObject("API");
				Object.DontDestroyOnLoad((Object)val);
				val.AddComponent<LC_APIManager>();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Started!");
				CheatDatabase.RunLocalCheatDetector();
			}
		}

		internal static void PatchMethodManual(MethodInfo method, MethodInfo patch, Harmony harmony)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			harmony.Patch((MethodBase)method, new HarmonyMethod(patch), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
	}
	public static class Utils
	{
		public static string ReplaceWithCase(this string input, string toReplace, string replacement)
		{
			Dictionary<string, string> map = new Dictionary<string, string> { { toReplace, replacement } };
			return input.ReplaceWithCase(map);
		}

		public static string ReplaceWithCase(this string input, Dictionary<string, string> map)
		{
			string text = input;
			foreach (KeyValuePair<string, string> item in map)
			{
				string key = item.Key;
				string value = item.Value;
				text = Regex.Replace(text, key, delegate(Match match)
				{
					string value2 = match.Value;
					char[] array = value2.ToCharArray();
					string[] source = value2.Split(' ');
					bool flag = char.IsUpper(array[0]);
					bool flag2 = source.All((string w) => char.IsUpper(w[0]) || !char.IsLetter(w[0]));
					if (array.All((char c) => char.IsUpper(c) || !char.IsLetter(c)))
					{
						return value.ToUpper();
					}
					if (flag2)
					{
						return Regex.Replace(value, "\\b\\w", (Match charMatch) => charMatch.Value.ToUpper());
					}
					char[] array2 = value.ToCharArray();
					array2[0] = (flag ? char.ToUpper(array2[0]) : char.ToLower(array2[0]));
					return new string(array2);
				}, RegexOptions.IgnoreCase);
			}
			return text;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LC_API";

		public const string PLUGIN_NAME = "Lethal Company API";

		public const string PLUGIN_VERSION = "3.4.5";
	}
}
namespace LC_API.ServerAPI
{
	public static class ModdedServer
	{
		private static bool moddedOnly;

		[Obsolete("Use SetServerModdedOnly() instead. This will be removed/private in a future update.")]
		public static bool setModdedOnly;

		public static int GameVersion { get; internal set; }

		public static bool ModdedOnly => moddedOnly;

		public static void SetServerModdedOnly()
		{
			moddedOnly = true;
			Plugin.Log.LogMessage((object)"A plugin has set your game to only allow you to play with other people who have mods!");
		}

		public static void OnSceneLoaded()
		{
			if (Object.op_Implicit((Object)(object)GameNetworkManager.Instance) && ModdedOnly)
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				instance.gameVersionNum += 16440;
				setModdedOnly = true;
			}
		}
	}
	[Obsolete("ServerAPI.Networking is obsolete and will be removed in future versions. Use LC_API.Networking.Network.")]
	public static class Networking
	{
		private sealed class Data<T>
		{
			public readonly string Signature;

			public readonly T Value;

			public Data(string signature, T value)
			{
				Signature = signature;
				Value = value;
			}
		}

		private const string StringMessageRegistrationName = "LCAPI_NET_LEGACY_STRING";

		private const string ListStringMessageRegistrationName = "LCAPI_NET_LEGACY_LISTSTRING";

		private const string IntMessageRegistrationName = "LCAPI_NET_LEGACY_INT";

		private const string FloatMessageRegistrationName = "LCAPI_NET_LEGACY_FLOAT";

		private const string Vector3MessageRegistrationName = "LCAPI_NET_LEGACY_VECTOR3";

		private const string SyncVarMessageRegistrationName = "LCAPI_NET_LEGACY_SYNCVAR_SET";

		public static Action<string, string> GetString = delegate
		{
		};

		public static Action<List<string>, string> GetListString = delegate
		{
		};

		public static Action<int, string> GetInt = delegate
		{
		};

		public static Action<float, string> GetFloat = delegate
		{
		};

		public static Action<Vector3, string> GetVector3 = delegate
		{
		};

		private static Dictionary<string, string> syncStringVars = new Dictionary<string, string>();

		public static void Broadcast(string data, string signature)
		{
			if (data.Contains("/"))
			{
				Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )");
			}
			else
			{
				Network.Broadcast("LCAPI_NET_LEGACY_STRING", new Data<string>(signature, data));
			}
		}

		public static void Broadcast(List<string> data, string signature)
		{
			string text = "";
			foreach (string datum in data)
			{
				if (datum.Contains("/"))
				{
					Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )");
					return;
				}
				if (datum.Contains("\n"))
				{
					Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( NewLine )");
					return;
				}
				text = text + datum + "\n";
			}
			Network.Broadcast("LCAPI_NET_LEGACY_LISTSTRING", new Data<string>(signature, text));
		}

		public static void Broadcast(int data, string signature)
		{
			Network.Broadcast("LCAPI_NET_LEGACY_INT", new Data<int>(signature, data));
		}

		public static void Broadcast(float data, string signature)
		{
			Network.Broadcast("LCAPI_NET_LEGACY_FLOAT", new Data<float>(signature, data));
		}

		public static void Broadcast(Vector3 data, string signature)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Network.Broadcast("LCAPI_NET_LEGACY_VECTOR3", new Data<Vector3>(signature, data));
		}

		public static void RegisterSyncVariable(string name)
		{
			if (!syncStringVars.ContainsKey(name))
			{
				syncStringVars.Add(name, "");
			}
			else
			{
				Plugin.Log.LogError((object)("Cannot register Sync Variable! A Sync Variable has already been registered with name " + name));
			}
		}

		public static void SetSyncVariable(string name, string value)
		{
			if (syncStringVars.ContainsKey(name))
			{
				syncStringVars[name] = value;
				Broadcast(new List<string> { name, value }, "LCAPI_NET_LEGACY_SYNCVAR_SET");
			}
			else
			{
				Plugin.Log.LogError((object)("Cannot set the value of Sync Variable " + name + " as it is not registered!"));
			}
		}

		private static void SetSyncVariableB(string name, string value)
		{
			if (syncStringVars.ContainsKey(name))
			{
				syncStringVars[name] = value;
			}
			else
			{
				Plugin.Log.LogError((object)("Cannot set the value of Sync Variable " + name + " as it is not registered!"));
			}
		}

		internal static void LCAPI_NET_SYNCVAR_SET(List<string> list, string arg2)
		{
			if (arg2 == "LCAPI_NET_LEGACY_SYNCVAR_SET")
			{
				SetSyncVariableB(list[0], list[1]);
			}
		}

		public static string GetSyncVariable(string name)
		{
			if (syncStringVars.ContainsKey(name))
			{
				return syncStringVars[name];
			}
			Plugin.Log.LogError((object)("Cannot get the value of Sync Variable " + name + " as it is not registered!"));
			return "";
		}

		internal static void InitializeLegacyNetworking()
		{
			GetListString = (Action<List<string>, string>)Delegate.Combine(GetListString, new Action<List<string>, string>(LCAPI_NET_SYNCVAR_SET));
			Network.RegisterMessage("LCAPI_NET_LEGACY_STRING", relayToSelf: false, delegate(ulong senderId, Data<string> data)
			{
				GetString(data.Value, data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_LISTSTRING", relayToSelf: false, delegate(ulong senderId, Data<string> data)
			{
				GetListString(data.Value.Split('\n').ToList(), data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_INT", relayToSelf: false, delegate(ulong senderId, Data<int> data)
			{
				GetInt(data.Value, data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_FLOAT", relayToSelf: false, delegate(ulong senderId, Data<float> data)
			{
				GetFloat(data.Value, data.Signature);
			});
			Network.RegisterMessage("LCAPI_NET_LEGACY_VECTOR3", relayToSelf: false, delegate(ulong senderId, Data<Vector3> data)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				GetVector3(data.Value, data.Signature);
			});
		}
	}
}
namespace LC_API.Networking
{
	public static class Network
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static HandleNamedMessageDelegate <>9__35_2;

			public static Events.CustomEventHandler <>9__35_0;

			public static Events.CustomEventHandler <>9__35_1;

			internal void <Init>b__35_0()
			{
				//IL_0041: 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)
				//IL_004c: Expected O, but got Unknown
				StartedNetworking = true;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
					object obj = <>9__35_2;
					if (obj == null)
					{
						HandleNamedMessageDelegate val = delegate(ulong senderClientId, FastBufferReader reader)
						{
							//IL_0006: Unknown result type (might be due to invalid IL or missing references)
							//IL_000c: Unknown result type (might be due to invalid IL or missing references)
							//IL_003d: Unknown result type (might be due to invalid IL or missing references)
							//IL_0043: Unknown result type (might be due to invalid IL or missing references)
							//IL_0059: Unknown result type (might be due to invalid IL or missing references)
							byte[] bytes = default(byte[]);
							((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
							NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
							networkMessageWrapper.Sender = senderClientId;
							byte[] array = networkMessageWrapper.ToBytes();
							FastBufferWriter val2 = default(FastBufferWriter);
							((FastBufferWriter)(ref val2))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
							try
							{
								((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(array, default(ForPrimitives));
								NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val2, (NetworkDelivery)4);
							}
							finally
							{
								((IDisposable)(FastBufferWriter)(ref val2)).Dispose();
							}
						};
						<>9__35_2 = val;
						obj = (object)val;
					}
					customMessagingManager.RegisterNamedMessageHandler("LC_API_RELAY_MESSAGE", (HandleNamedMessageDelegate)obj);
				}
				RegisterAllMessages();
			}

			internal void <Init>b__35_2(ulong senderClientId, FastBufferReader reader)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				byte[] bytes = default(byte[]);
				((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
				NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
				networkMessageWrapper.Sender = senderClientId;
				byte[] array = networkMessageWrapper.ToBytes();
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val, (NetworkDelivery)4);
				}
				finally
				{
					((IDisposable)(FastBufferWriter)(ref val)).Dispose();
				}
			}

			internal void <Init>b__35_1()
			{
				StartedNetworking = false;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("LC_API_RELAY_MESSAGE");
				}
				UnregisterAllMessages();
			}
		}

		internal const string MESSAGE_RELAY_UNIQUE_NAME = "LC_API_RELAY_MESSAGE";

		private static MethodInfo _registerInfo = null;

		private static MethodInfo _registerInfoGeneric = null;

		internal static Dictionary<string, NetworkMessageFinalizerBase> NetworkMessageFinalizers { get; } = new Dictionary<string, NetworkMessageFinalizerBase>();


		internal static bool StartedNetworking { get; set; } = false;


		internal static MethodInfo RegisterInfo
		{
			get
			{
				if (_registerInfo == null)
				{
					MethodInfo[] methods = typeof(Network).GetMethods();
					foreach (MethodInfo methodInfo in methods)
					{
						if (methodInfo.Name == "RegisterMessage" && !methodInfo.IsGenericMethod)
						{
							_registerInfo = methodInfo;
							break;
						}
					}
				}
				return _registerInfo;
			}
		}

		internal static MethodInfo RegisterInfoGeneric
		{
			get
			{
				if (_registerInfoGeneric == null)
				{
					MethodInfo[] methods = typeof(Network).GetMethods();
					foreach (MethodInfo methodInfo in methods)
					{
						if (methodInfo.Name == "RegisterMessage" && methodInfo.IsGenericMethod)
						{
							_registerInfoGeneric = methodInfo;
							break;
						}
					}
				}
				return _registerInfoGeneric;
			}
		}

		public static event Events.CustomEventHandler RegisterNetworkMessages;

		internal static event Events.CustomEventHandler UnregisterNetworkMessages;

		internal static byte[] ToBytes(this object @object)
		{
			if (@object == null)
			{
				return null;
			}
			return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@object));
		}

		internal static T ToObject<T>(this byte[] bytes) where T : class
		{
			return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes));
		}

		internal static void OnRegisterNetworkMessages()
		{
			Network.RegisterNetworkMessages.InvokeSafely();
		}

		internal static void OnUnregisterNetworkMessages()
		{
			Network.UnregisterNetworkMessages.InvokeSafely();
		}

		internal static void RegisterAllMessages()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			foreach (NetworkMessageFinalizerBase value in NetworkMessageFinalizers.Values)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(value.UniqueName, new HandleNamedMessageDelegate(value.Read));
			}
		}

		internal static void UnregisterAllMessages()
		{
			foreach (string key in NetworkMessageFinalizers.Keys)
			{
				UnregisterMessage(key, andRemoveHandler: false);
			}
		}

		public static void RegisterAll()
		{
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly);
			for (int i = 0; i < typesFromAssembly.Length; i++)
			{
				RegisterAll(typesFromAssembly[i]);
			}
		}

		public static void RegisterAll(Type type)
		{
			if (!type.IsClass)
			{
				return;
			}
			NetworkMessage customAttribute = type.GetCustomAttribute<NetworkMessage>();
			if (customAttribute != null)
			{
				if (type.BaseType.Name == "NetworkMessageHandler`1")
				{
					Type type2 = type.BaseType.GetGenericArguments()[0];
					RegisterInfoGeneric.MakeGenericMethod(type2).Invoke(null, new object[3]
					{
						customAttribute.UniqueName,
						customAttribute.RelayToSelf,
						type.GetMethod("Handler").CreateDelegate(typeof(Action<, >).MakeGenericType(typeof(ulong), type2), Activator.CreateInstance(type))
					});
				}
				else if (type.BaseType.Name == "NetworkMessageHandler")
				{
					RegisterInfo.Invoke(null, new object[3]
					{
						customAttribute.UniqueName,
						customAttribute.RelayToSelf,
						type.GetMethod("Handler").CreateDelegate(typeof(Action<>).MakeGenericType(typeof(ulong)), Activator.CreateInstance(type))
					});
				}
				return;
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				customAttribute = methodInfo.GetCustomAttribute<NetworkMessage>();
				if (customAttribute != null)
				{
					if (!methodInfo.IsStatic)
					{
						throw new Exception("Detected NetworkMessage attribute on non-static method. All NetworkMessages on methods must be static.");
					}
					if (methodInfo.GetParameters().Length == 1)
					{
						RegisterInfo.Invoke(null, new object[3]
						{
							customAttribute.UniqueName,
							customAttribute.RelayToSelf,
							methodInfo.CreateDelegate(typeof(Action<>).MakeGenericType(typeof(ulong)))
						});
					}
					else
					{
						Type parameterType = methodInfo.GetParameters()[1].ParameterType;
						RegisterInfoGeneric.MakeGenericMethod(parameterType).Invoke(null, new object[3]
						{
							customAttribute.UniqueName,
							customAttribute.RelayToSelf,
							methodInfo.CreateDelegate(typeof(Action<, >).MakeGenericType(typeof(ulong), parameterType))
						});
					}
				}
			}
		}

		public static void UnregisterAll(bool andRemoveHandler = true)
		{
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly);
			for (int i = 0; i < typesFromAssembly.Length; i++)
			{
				UnregisterAll(typesFromAssembly[i], andRemoveHandler);
			}
		}

		public static void UnregisterAll(Type type, bool andRemoveHandler = true)
		{
			if (!type.IsClass)
			{
				return;
			}
			NetworkMessage customAttribute = type.GetCustomAttribute<NetworkMessage>();
			if (customAttribute != null)
			{
				UnregisterMessage(customAttribute.UniqueName, andRemoveHandler);
				return;
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			for (int i = 0; i < methods.Length; i++)
			{
				customAttribute = methods[i].GetCustomAttribute<NetworkMessage>();
				if (customAttribute != null)
				{
					UnregisterMessage(customAttribute.UniqueName, andRemoveHandler);
				}
			}
		}

		public static void RegisterMessage<T>(string uniqueName, bool relayToSelf, Action<ulong, T> onReceived) where T : class
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			if (NetworkMessageFinalizers.ContainsKey(uniqueName))
			{
				throw new Exception(uniqueName + " already registered");
			}
			NetworkMessageFinalizer<T> networkMessageFinalizer = new NetworkMessageFinalizer<T>(uniqueName, relayToSelf, onReceived);
			NetworkMessageFinalizers.Add(uniqueName, networkMessageFinalizer);
			if (StartedNetworking)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(uniqueName, new HandleNamedMessageDelegate(networkMessageFinalizer.Read));
			}
		}

		public static void RegisterMessage(string uniqueName, bool relayToSelf, Action<ulong> onReceived)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			if (NetworkMessageFinalizers.ContainsKey(uniqueName))
			{
				throw new Exception(uniqueName + " already registered");
			}
			NetworkMessageFinalizer networkMessageFinalizer = new NetworkMessageFinalizer(uniqueName, relayToSelf, onReceived);
			NetworkMessageFinalizers.Add(uniqueName, networkMessageFinalizer);
			if (StartedNetworking)
			{
				NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(uniqueName, new HandleNamedMessageDelegate(networkMessageFinalizer.Read));
			}
		}

		public static void UnregisterMessage(string uniqueName, bool andRemoveHandler = true)
		{
			if ((!andRemoveHandler && NetworkMessageFinalizers.ContainsKey(uniqueName)) || (andRemoveHandler && NetworkMessageFinalizers.Remove(uniqueName)))
			{
				NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler(uniqueName);
			}
		}

		public static void Broadcast<T>(string uniqueName, T @object) where T : class
		{
			if (NetworkMessageFinalizers.TryGetValue(uniqueName, out var value))
			{
				if (!(value is NetworkMessageFinalizer<T> networkMessageFinalizer))
				{
					throw new Exception("Network handler for " + uniqueName + " was not broadcast with the right type!");
				}
				networkMessageFinalizer.Send(@object);
			}
		}

		public static void Broadcast(string uniqueName)
		{
			if (NetworkMessageFinalizers.TryGetValue(uniqueName, out var value))
			{
				if (!(value is NetworkMessageFinalizer networkMessageFinalizer))
				{
					throw new Exception("Network handler for " + uniqueName + " was not broadcast with the right type!");
				}
				networkMessageFinalizer.Send();
			}
		}

		internal static void Init()
		{
			RegisterNetworkMessages += delegate
			{
				//IL_0041: 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)
				//IL_004c: Expected O, but got Unknown
				StartedNetworking = true;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
					object obj = <>c.<>9__35_2;
					if (obj == null)
					{
						HandleNamedMessageDelegate val = delegate(ulong senderClientId, FastBufferReader reader)
						{
							//IL_0006: Unknown result type (might be due to invalid IL or missing references)
							//IL_000c: Unknown result type (might be due to invalid IL or missing references)
							//IL_003d: Unknown result type (might be due to invalid IL or missing references)
							//IL_0043: Unknown result type (might be due to invalid IL or missing references)
							//IL_0059: Unknown result type (might be due to invalid IL or missing references)
							byte[] bytes = default(byte[]);
							((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
							NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
							networkMessageWrapper.Sender = senderClientId;
							byte[] array = networkMessageWrapper.ToBytes();
							FastBufferWriter val2 = default(FastBufferWriter);
							((FastBufferWriter)(ref val2))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
							try
							{
								((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(array, default(ForPrimitives));
								NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val2, (NetworkDelivery)4);
							}
							finally
							{
								((IDisposable)(FastBufferWriter)(ref val2)).Dispose();
							}
						};
						<>c.<>9__35_2 = val;
						obj = (object)val;
					}
					customMessagingManager.RegisterNamedMessageHandler("LC_API_RELAY_MESSAGE", (HandleNamedMessageDelegate)obj);
				}
				RegisterAllMessages();
			};
			UnregisterNetworkMessages += delegate
			{
				StartedNetworking = false;
				if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
				{
					NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("LC_API_RELAY_MESSAGE");
				}
				UnregisterAllMessages();
			};
			SetupNetworking();
			RegisterAll();
			LC_API.ServerAPI.Networking.InitializeLegacyNetworking();
		}

		internal static void SetupNetworking()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			for (int i = 0; i < types.Length; i++)
			{
				MethodInfo[] methods = types[i].GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	public class NetworkMessage : Attribute
	{
		public string UniqueName { get; }

		public bool RelayToSelf { get; }

		public NetworkMessage(string uniqueName, bool relayToSelf = false)
		{
			UniqueName = uniqueName;
			RelayToSelf = relayToSelf;
		}
	}
	public abstract class NetworkMessageHandler<T> where T : class
	{
		public abstract void Handler(ulong sender, T message);
	}
	public abstract class NetworkMessageHandler
	{
		public abstract void Handler(ulong sender);
	}
	internal abstract class NetworkMessageFinalizerBase
	{
		internal abstract string UniqueName { get; }

		internal abstract bool RelayToSelf { get; }

		public abstract void Read(ulong sender, FastBufferReader reader);
	}
	internal class NetworkMessageFinalizer : NetworkMessageFinalizerBase
	{
		internal override string UniqueName { get; }

		internal override bool RelayToSelf { get; }

		internal Action<ulong> OnReceived { get; }

		public NetworkMessageFinalizer(string uniqueName, bool relayToSelf, Action<ulong> onReceived)
		{
			UniqueName = uniqueName;
			RelayToSelf = relayToSelf;
			OnReceived = onReceived;
		}

		public void Send()
		{
			//IL_005d: 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)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater());
				return;
			}
			byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId).ToBytes();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)4);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)4);
				}
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public override void Read(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0021: 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)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(ReadLater(fakeSender, reader));
				return;
			}
			byte[] bytes = default(byte[]);
			((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
			NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
			if (RelayToSelf || LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId != networkMessageWrapper.Sender)
			{
				OnReceived(networkMessageWrapper.Sender);
			}
		}

		private IEnumerator SendLater()
		{
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to send network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Send();
		}

		private IEnumerator ReadLater(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to read network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Read(fakeSender, reader);
		}
	}
	internal class NetworkMessageFinalizer<T> : NetworkMessageFinalizerBase where T : class
	{
		internal override string UniqueName { get; }

		internal override bool RelayToSelf { get; }

		internal Action<ulong, T> OnReceived { get; }

		public NetworkMessageFinalizer(string uniqueName, bool relayToSelf, Action<ulong, T> onReceived)
		{
			UniqueName = uniqueName;
			RelayToSelf = relayToSelf;
			OnReceived = onReceived;
		}

		public void Send(T obj)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: 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_00bf: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater(obj));
				return;
			}
			byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId, obj.ToBytes()).ToBytes();
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives));
				if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)4);
				}
				else
				{
					NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)4);
				}
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public override void Read(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0021: 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)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(ReadLater(fakeSender, reader));
				return;
			}
			byte[] bytes = default(byte[]);
			((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives));
			NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>();
			if (RelayToSelf || LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId != networkMessageWrapper.Sender)
			{
				OnReceived(networkMessageWrapper.Sender, networkMessageWrapper.Message.ToObject<T>());
			}
		}

		private IEnumerator SendLater(T obj)
		{
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to send network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Send(obj);
		}

		private IEnumerator ReadLater(ulong fakeSender, FastBufferReader reader)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			int timesWaited = 0;
			while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null)
			{
				yield return (object)new WaitForSeconds(0.1f);
				timesWaited++;
				if (timesWaited % 20 == 0)
				{
					Plugin.Log.LogWarning((object)$"Waiting to read network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}");
				}
				if (timesWaited >= 100)
				{
					Plugin.Log.LogError((object)"Dropping network message");
					yield return null;
				}
			}
			Read(fakeSender, reader);
		}
	}
	internal class NetworkMessageWrapper
	{
		public string UniqueName { get; set; }

		public ulong Sender { get; set; }

		public byte[] Message { get; set; }

		internal NetworkMessageWrapper(string uniqueName, ulong sender)
		{
			UniqueName = uniqueName;
			Sender = sender;
		}

		internal NetworkMessageWrapper(string uniqueName, ulong sender, byte[] message)
		{
			UniqueName = uniqueName;
			Sender = sender;
			Message = message;
		}

		internal NetworkMessageWrapper()
		{
		}
	}
	internal static class RegisterPatch
	{
		internal static void Postfix()
		{
			Network.OnRegisterNetworkMessages();
		}
	}
	internal static class UnregisterPatch
	{
		internal static void Postfix()
		{
			Network.OnUnregisterNetworkMessages();
		}
	}
}
namespace LC_API.Networking.Serializers
{
	public struct Vector2S
	{
		private Vector2? v2;

		public float x { get; set; }

		public float y { get; set; }

		[JsonIgnore]
		public Vector2 vector2
		{
			get
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				if (!v2.HasValue)
				{
					v2 = new Vector2(x, y);
				}
				return v2.Value;
			}
		}

		public Vector2S(float x, float y)
		{
			v2 = null;
			this.x = x;
			this.y = y;
		}

		public static implicit operator Vector2(Vector2S vector2S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector2S.vector2;
		}

		public static implicit operator Vector2S(Vector2 vector2)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return new Vector2S(vector2.x, vector2.y);
		}
	}
	public struct Vector2IntS
	{
		private Vector2Int? v2;

		public int x { get; set; }

		public int y { get; set; }

		[JsonIgnore]
		public Vector2Int vector2
		{
			get
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				if (!v2.HasValue)
				{
					v2 = new Vector2Int(x, y);
				}
				return v2.Value;
			}
		}

		public Vector2IntS(int x, int y)
		{
			v2 = null;
			this.x = x;
			this.y = y;
		}

		public static implicit operator Vector2Int(Vector2IntS vector2S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector2S.vector2;
		}

		public static implicit operator Vector2IntS(Vector2Int vector2)
		{
			return new Vector2IntS(((Vector2Int)(ref vector2)).x, ((Vector2Int)(ref vector2)).y);
		}
	}
	public struct Vector3S
	{
		private Vector3? v3;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		[JsonIgnore]
		public Vector3 vector3
		{
			get
			{
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				if (!v3.HasValue)
				{
					v3 = new Vector3(x, y, z);
				}
				return v3.Value;
			}
		}

		public Vector3S(float x, float y, float z)
		{
			v3 = null;
			this.x = x;
			this.y = y;
			this.z = z;
		}

		public static implicit operator Vector3(Vector3S vector3S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector3S.vector3;
		}

		public static implicit operator Vector3S(Vector3 vector3)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3S(vector3.x, vector3.y, vector3.z);
		}
	}
	public struct Vector3IntS
	{
		private Vector3Int? v3;

		public int x { get; set; }

		public int y { get; set; }

		public int z { get; set; }

		[JsonIgnore]
		public Vector3Int vector3
		{
			get
			{
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				if (!v3.HasValue)
				{
					v3 = new Vector3Int(x, y, z);
				}
				return v3.Value;
			}
		}

		public Vector3IntS(int x, int y, int z)
		{
			v3 = null;
			this.x = x;
			this.y = y;
			this.z = z;
		}

		public static implicit operator Vector3Int(Vector3IntS vector3S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector3S.vector3;
		}

		public static implicit operator Vector3IntS(Vector3Int vector3)
		{
			return new Vector3IntS(((Vector3Int)(ref vector3)).x, ((Vector3Int)(ref vector3)).y, ((Vector3Int)(ref vector3)).z);
		}
	}
	public struct Vector4S
	{
		private Vector4? v4;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public float w { get; set; }

		[JsonIgnore]
		public Vector4 Vector4
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!v4.HasValue)
				{
					v4 = new Vector4(x, y, z, w);
				}
				return v4.Value;
			}
		}

		public Vector4S(float x, float y, float z, float w)
		{
			v4 = null;
			this.x = x;
			this.y = y;
			this.z = z;
			this.w = w;
		}

		public static implicit operator Vector4(Vector4S vector4S)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return vector4S.Vector4;
		}

		public static implicit operator Vector4S(Vector4 vector4)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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)
			return new Vector4S(vector4.x, vector4.y, vector4.z, vector4.w);
		}
	}
	public struct QuaternionS
	{
		private Quaternion? q;

		public float x { get; set; }

		public float y { get; set; }

		public float z { get; set; }

		public float w { get; set; }

		[JsonIgnore]
		public Quaternion Quaternion
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!q.HasValue)
				{
					q = new Quaternion(x, y, z, w);
				}
				return q.Value;
			}
		}

		public QuaternionS(float x, float y, float z, float w)
		{
			q = null;
			this.x = x;
			this.y = y;
			this.z = z;
			this.w = w;
		}

		public static implicit operator Quaternion(QuaternionS quaternionS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return quaternionS.Quaternion;
		}

		public static implicit operator QuaternionS(Quaternion quaternion)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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)
			return new QuaternionS(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
		}
	}
	public struct ColorS
	{
		private Color? c;

		public float r { get; set; }

		public float g { get; set; }

		public float b { get; set; }

		public float a { get; set; }

		[JsonIgnore]
		public Color Color
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!c.HasValue)
				{
					c = new Color(r, g, b, a);
				}
				return c.Value;
			}
		}

		public ColorS(float r, float g, float b, float a)
		{
			c = null;
			this.r = r;
			this.g = g;
			this.b = b;
			this.a = a;
		}

		public static implicit operator Color(ColorS colorS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return colorS.Color;
		}

		public static implicit operator ColorS(Color color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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)
			return new ColorS(color.r, color.g, color.b, color.a);
		}
	}
	public struct Color32S
	{
		private Color32? c;

		public byte r { get; set; }

		public byte g { get; set; }

		public byte b { get; set; }

		public byte a { get; set; }

		[JsonIgnore]
		public Color32 Color
		{
			get
			{
				//IL_003b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				if (!c.HasValue)
				{
					c = new Color32(r, g, b, a);
				}
				return c.Value;
			}
		}

		public Color32S(byte r, byte g, byte b, byte a)
		{
			c = null;
			this.r = r;
			this.g = g;
			this.b = b;
			this.a = a;
		}

		public static implicit operator Color32(Color32S colorS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return colorS.Color;
		}

		public static implicit operator Color32S(Color32 color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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)
			return new Color32S(color.r, color.g, color.b, color.a);
		}
	}
	public struct RayS
	{
		private Ray? r;

		public Vector3S origin { get; set; }

		public Vector3S direction { get; set; }

		[JsonIgnore]
		public Ray Ray
		{
			get
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: 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)
				if (!r.HasValue)
				{
					r = new Ray((Vector3)origin, (Vector3)direction);
				}
				return r.Value;
			}
		}

		public RayS(Vector3 origin, Vector3 direction)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			r = null;
			this.origin = origin;
			this.direction = direction;
		}

		public static implicit operator Ray(RayS rayS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return rayS.Ray;
		}

		public static implicit operator RayS(Ray ray)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			return new RayS(((Ray)(ref ray)).origin, ((Ray)(ref ray)).direction);
		}
	}
	public struct Ray2DS
	{
		private Ray2D? r;

		public Vector2S origin { get; set; }

		public Vector2S direction { get; set; }

		[JsonIgnore]
		public Ray2D Ray
		{
			get
			{
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: 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)
				if (!r.HasValue)
				{
					r = new Ray2D((Vector2)origin, (Vector2)direction);
				}
				return r.Value;
			}
		}

		public Ray2DS(Vector2 origin, Vector2 direction)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			r = null;
			this.origin = origin;
			this.direction = direction;
		}

		public static implicit operator Ray2D(Ray2DS ray2DS)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return ray2DS.Ray;
		}

		public static implicit operator Ray2DS(Ray2D ray2D)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			return new Ray2DS(((Ray2D)(ref ray2D)).origin, ((Ray2D)(ref ray2D)).direction);
		}
	}
}
namespace LC_API.ManualPatches
{
	internal static class ServerPatch
	{
		internal static bool OnLobbyCreate(GameNetworkManager __instance, Result result, Lobby lobby)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if ((int)result != 1)
			{
				Debug.LogError((object)$"Lobby could not be created! {result}", (Object)(object)__instance);
			}
			__instance.lobbyHostSettings.lobbyName = "[MODDED]" + __instance.lobbyHostSettings.lobbyName.ToString();
			Plugin.Log.LogMessage((object)"server pre-setup success");
			return true;
		}

		internal static bool CacheMenuManager(MenuManager __instance)
		{
			LC_APIManager.MenuManager = __instance;
			return true;
		}

		internal static bool ChatCommands(HUDManager __instance, CallbackContext context)
		{
			if (__instance.chatTextField.text.ToLower().Contains("/modcheck"))
			{
				CheatDatabase.OtherPlayerCheatDetector();
				return false;
			}
			return true;
		}

		internal static void GameNetworkManagerAwake(GameNetworkManager __instance)
		{
			if ((Object)(object)GameNetworkManager.Instance == (Object)null)
			{
				ModdedServer.GameVersion = __instance.gameVersionNum;
			}
		}
	}
}
namespace LC_API.GameInterfaceAPI
{
	public static class GameState
	{
		private static readonly Action NothingAction = delegate
		{
		};

		public static int AlivePlayerCount { get; private set; }

		public static ShipState ShipState { get; private set; }

		public static event Action PlayerDied;

		public static event Action LandOnMoon;

		public static event Action WentIntoOrbit;

		public static event Action ShipStartedLeaving;

		internal static void GSUpdate()
		{
			if (!((Object)(object)StartOfRound.Instance == (Object)null))
			{
				if (StartOfRound.Instance.shipHasLanded && ShipState != ShipState.OnMoon)
				{
					ShipState = ShipState.OnMoon;
					GameState.LandOnMoon.InvokeActionSafe();
				}
				if (StartOfRound.Instance.inShipPhase && ShipState != 0)
				{
					ShipState = ShipState.InOrbit;
					GameState.WentIntoOrbit.InvokeActionSafe();
				}
				if (StartOfRound.Instance.shipIsLeaving && ShipState != ShipState.LeavingMoon)
				{
					ShipState = ShipState.LeavingMoon;
					GameState.ShipStartedLeaving.InvokeActionSafe();
				}
				if (AlivePlayerCount < StartOfRound.Instance.livingPlayers)
				{
					GameState.PlayerDied.InvokeActionSafe();
				}
				AlivePlayerCount = StartOfRound.Instance.livingPlayers;
			}
		}

		static GameState()
		{
			GameState.PlayerDied = NothingAction;
			GameState.LandOnMoon = NothingAction;
			GameState.WentIntoOrbit = NothingAction;
			GameState.ShipStartedLeaving = NothingAction;
		}
	}
	[Obsolete("Use Player::QueueTip instead.")]
	public class GameTips
	{
		private static List<string> tipHeaders = new List<string>();

		private static List<string> tipBodys = new List<string>();

		private static float lastMessageTime;

		public static void ShowTip(string header, string body)
		{
			tipHeaders.Add(header);
			tipBodys.Add(body);
		}

		public static void UpdateInternal()
		{
			lastMessageTime -= Time.deltaTime;
			if ((tipHeaders.Count > 0) & (lastMessageTime < 0f))
			{
				lastMessageTime = 5f;
				if ((Object)(object)HUDManager.Instance != (Object)null)
				{
					HUDManager.Instance.DisplayTip(tipHeaders[0], tipBodys[0], false, false, "LC_Tip1");
				}
				tipHeaders.RemoveAt(0);
				tipBodys.RemoveAt(0);
			}
		}
	}
}
namespace LC_API.GameInterfaceAPI.Features
{
	public class Item : NetworkBehaviour
	{
		private bool hasNewProps;

		internal static GameObject ItemNetworkPrefab { get; set; }

		public static Dictionary<GrabbableObject, Item> Dictionary { get; } = new Dictionary<GrabbableObject, Item>();


		public static IReadOnlyCollection<Item> List => Dictionary.Values;

		public GrabbableObject GrabbableObject { get; private set; }

		public Item ItemProperties => GrabbableObject.itemProperties;

		public ScanNodeProperties ScanNodeProperties { get; set; }

		public bool IsHeld => GrabbableObject.isHeld;

		public bool IsTwoHanded => ItemProperties.twoHanded;

		public Player Holder
		{
			get
			{
				if (!IsHeld)
				{
					return null;
				}
				if (!Player.Dictionary.TryGetValue(GrabbableObject.playerHeldBy, out var value))
				{
					return null;
				}
				return value;
			}
		}

		public string Name
		{
			get
			{
				return ItemProperties.itemName;
			}
			set
			{
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item name on client.");
				}
				string oldName = ItemProperties.itemName.ToLower();
				CloneProperties();
				ItemProperties.itemName = value;
				OverrideTooltips(oldName, value.ToLower());
				ScanNodeProperties.headerText = value;
				SetGrabbableNameClientRpc(value);
			}
		}

		public Vector3 Position
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.position;
			}
			set
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: 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)
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item position on client.");
				}
				GrabbableObject.startFallingPosition = value;
				GrabbableObject.targetFloorPosition = value;
				((Component)GrabbableObject).transform.position = value;
				SetItemPositionClientRpc(value);
			}
		}

		public Quaternion Rotation
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.rotation;
			}
			set
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				((Component)GrabbableObject).transform.rotation = value;
			}
		}

		public Vector3 Scale
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				return ((Component)GrabbableObject).transform.localScale;
			}
			set
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				((Component)GrabbableObject).transform.localScale = value;
			}
		}

		public bool IsScrap
		{
			get
			{
				return ItemProperties.isScrap;
			}
			set
			{
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set item name on client.");
				}
				CloneProperties();
				ItemProperties.isScrap = value;
				SetIsScrapClientRpc(value);
			}
		}

		public int ScrapValue
		{
			get
			{
				return GrabbableObject.scrapValue;
			}
			set
			{
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to set scrap value on client.");
				}
				GrabbableObject.SetScrapValue(value);
				SetScrapValueClientRpc(value);
			}
		}

		[ClientRpc]
		private void SetGrabbableNameClientRpc(string name)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(66243798u, val, (RpcDelivery)0);
				bool flag = name != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(name, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 66243798u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				string oldName = ItemProperties.itemName.ToLower();
				CloneProperties();
				ItemProperties.itemName = name;
				OverrideTooltips(oldName, name.ToLower());
				ScanNodeProperties.headerText = name;
			}
		}

		private void OverrideTooltips(string oldName, string newName)
		{
			for (int i = 0; i < ItemProperties.toolTips.Length; i++)
			{
				ItemProperties.toolTips[i] = ItemProperties.toolTips[i].ReplaceWithCase(oldName, newName);
			}
			if (IsHeld && (Object)(object)Holder == (Object)(object)Player.LocalPlayer)
			{
				GrabbableObject.SetControlTipsForItem();
			}
		}

		[ClientRpc]
		private void SetItemPositionClientRpc(Vector3 pos)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(949135576u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref pos);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 949135576u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					GrabbableObject.startFallingPosition = pos;
					GrabbableObject.targetFloorPosition = pos;
					((Component)GrabbableObject).transform.position = pos;
				}
			}
		}

		public void SetAndSyncRotation(Quaternion rotation)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to sync item rotation from client.");
			}
			SetItemRotationClientRpc(rotation);
		}

		[ClientRpc]
		private void SetItemRotationClientRpc(Quaternion rotation)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1528367091u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref rotation);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1528367091u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Rotation = rotation;
				}
			}
		}

		public void SetAndSyncScale(Vector3 scale)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to sync item scale from client.");
			}
			SetItemScaleClientRpc(scale);
		}

		[ClientRpc]
		private void SetItemScaleClientRpc(Vector3 scale)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2688253945u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe(ref scale);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2688253945u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					Scale = scale;
				}
			}
		}

		[ClientRpc]
		private void SetIsScrapClientRpc(bool isScrap)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4227417717u, val, (RpcDelivery)0);
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref isScrap, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4227417717u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					CloneProperties();
					ItemProperties.isScrap = isScrap;
				}
			}
		}

		[ClientRpc]
		private void SetScrapValueClientRpc(int scrapValue)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3866863385u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, scrapValue);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3866863385u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					GrabbableObject.SetScrapValue(scrapValue);
				}
			}
		}

		public void RemoveFromHolder(Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion))
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to remove item from player on client.");
			}
			if (IsHeld)
			{
				((NetworkBehaviour)this).NetworkObject.RemoveOwnership();
				Holder.Inventory.RemoveItem(this);
				RemoveFromHolderClientRpc();
				Position = position;
				Rotation = rotation;
			}
		}

		[ClientRpc]
		private void RemoveFromHolderClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1050513218u, val, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1050513218u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && IsHeld)
				{
					Holder.Inventory.RemoveItem(this);
				}
			}
		}

		public void EnablePhysics(bool enable)
		{
			GrabbableObject.EnablePhysics(enable);
		}

		public void EnableMeshes(bool enable)
		{
			GrabbableObject.EnableItemMeshes(enable);
		}

		public void FallToGround(bool randomizePosition = false)
		{
			GrabbableObject.FallToGround(randomizePosition);
		}

		public bool PocketItem()
		{
			if (!IsHeld || (Object)(object)Holder.HeldItem != (Object)(object)this || IsTwoHanded)
			{
				return false;
			}
			GrabbableObject.PocketItem();
			return true;
		}

		public bool GiveTo(Player player, bool switchTo = true)
		{
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to give item to player on client.");
			}
			return player.Inventory.TryAddItem(this, switchTo);
		}

		public void InitializeScrap()
		{
			if (RoundManager.Instance.AnomalyRandom != null)
			{
				InitializeScrap((int)((float)RoundManager.Instance.AnomalyRandom.Next(ItemProperties.minValue, ItemProperties.maxValue) * RoundManager.Instance.scrapValueMultiplier));
			}
			else
			{
				InitializeScrap((int)((float)Random.Range(ItemProperties.minValue, ItemProperties.maxValue) * RoundManager.Instance.scrapValueMultiplier));
			}
		}

		public void InitializeScrap(int scrapValue)
		{
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to initialize scrap on client.");
			}
			ScrapValue = scrapValue;
			InitializeScrapClientRpc();
		}

		[ClientRpc]
		private void InitializeScrapClientRpc()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1334565671u, val, (RpcDelivery)0);
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1334565671u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			MeshFilter val3 = default(MeshFilter);
			if (((Component)GrabbableObject).gameObject.TryGetComponent<MeshFilter>(ref val3) && ItemProperties.meshVariants != null && ItemProperties.meshVariants.Length != 0)
			{
				if (RoundManager.Instance.ScrapValuesRandom != null)
				{
					val3.mesh = ItemProperties.meshVariants[RoundManager.Instance.ScrapValuesRandom.Next(ItemProperties.meshVariants.Length)];
				}
				else
				{
					val3.mesh = ItemProperties.meshVariants[0];
				}
			}
			MeshRenderer val4 = default(MeshRenderer);
			if (((Component)GrabbableObject).gameObject.TryGetComponent<MeshRenderer>(ref val4) && ItemProperties.materialVariants != null && ItemProperties.materialVariants.Length != 0)
			{
				if (RoundManager.Instance.ScrapValuesRandom != null)
				{
					((Renderer)val4).sharedMaterial = ItemProperties.materialVariants[RoundManager.Instance.ScrapValuesRandom.Next(ItemProperties.materialVariants.Length)];
				}
				else
				{
					((Renderer)val4).sharedMaterial = ItemProperties.materialVariants[0];
				}
			}
		}

		public static Item CreateAndSpawnItem(string itemName, bool andInitialize = true, Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion))
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to create and spawn item on client.");
			}
			string name = itemName.ToLower();
			GameObject val = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => i.itemName.ToLower().Contains(name)))?.spawnPrefab;
			if ((Object)(object)val != (Object)null)
			{
				GameObject obj = Object.Instantiate<GameObject>(val, position, rotation);
				obj.GetComponent<NetworkObject>().Spawn(false);
				Item component = obj.GetComponent<Item>();
				if (component.IsScrap && andInitialize)
				{
					component.InitializeScrap();
				}
				return component;
			}
			return null;
		}

		public static Item CreateAndGiveItem(string itemName, Player player, bool andInitialize = true, bool switchTo = true)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
			{
				throw new NoAuthorityException("Tried to create and give item on client.");
			}
			string name = itemName.ToLower();
			GameObject val = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => i.itemName.ToLower().Contains(name)))?.spawnPrefab;
			if ((Object)(object)val != (Object)null)
			{
				GameObject obj = Object.Instantiate<GameObject>(val, Vector3.zero, default(Quaternion));
				obj.GetComponent<NetworkObject>().Spawn(false);
				Item component = obj.GetComponent<Item>();
				if (component.IsScrap && andInitialize)
				{
					component.InitializeScrap();
				}
				component.GiveTo(player, switchTo);
				return component;
			}
			return null;
		}

		private void Awake()
		{
			GrabbableObject = ((Component)this).GetComponent<GrabbableObject>();
			ScanNodeProperties = ((Component)GrabbableObject).gameObject.GetComponentInChildren<ScanNodeProperties>();
			Dictionary.Add(GrabbableObject, this);
		}

		private void CloneProperties()
		{
			Item itemProperties = Object.Instantiate<Item>(ItemProperties);
			if (hasNewProps)
			{
				Object.Destroy((Object)(object)ItemProperties);
			}
			GrabbableObject.itemProperties = itemProperties;
			hasNewProps = true;
		}

		public override void OnDestroy()
		{
			Dictionary.Remove(GrabbableObject);
			((NetworkBehaviour)this).OnDestroy();
		}

		public static Item GetOrAdd(GrabbableObject grabbableObject)
		{
			if (Dictionary.TryGetValue(grabbableObject, out var value))
			{
				return value;
			}
			return ((Component)grabbableObject).gameObject.AddComponent<Item>();
		}

		public static Item Get(GrabbableObject grabbableObject)
		{
			if (Dictionary.TryGetValue(grabbableObject, out var value))
			{
				return value;
			}
			return null;
		}

		public static bool TryGet(GrabbableObject grabbableObject, out Item item)
		{
			return Dictionary.TryGetValue(grabbableObject, out item);
		}

		public static Item Get(ulong netId)
		{
			return List.FirstOrDefault((Item i) => ((NetworkBehaviour)i).NetworkObjectId == netId);
		}

		public static bool TryGet(ulong netId, out Item item)
		{
			item = Get(netId);
			return (Object)(object)item != (Object)null;
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_Item()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(66243798u, new RpcReceiveHandler(__rpc_handler_66243798));
			NetworkManager.__rpc_func_table.Add(949135576u, new RpcReceiveHandler(__rpc_handler_949135576));
			NetworkManager.__rpc_func_table.Add(1528367091u, new RpcReceiveHandler(__rpc_handler_1528367091));
			NetworkManager.__rpc_func_table.Add(2688253945u, new RpcReceiveHandler(__rpc_handler_2688253945));
			NetworkManager.__rpc_func_table.Add(4227417717u, new RpcReceiveHandler(__rpc_handler_4227417717));
			NetworkManager.__rpc_func_table.Add(3866863385u, new RpcReceiveHandler(__rpc_handler_3866863385));
			NetworkManager.__rpc_func_table.Add(1050513218u, new RpcReceiveHandler(__rpc_handler_1050513218));
			NetworkManager.__rpc_func_table.Add(1334565671u, new RpcReceiveHandler(__rpc_handler_1334565671));
		}

		private static void __rpc_handler_66243798(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string grabbableNameClientRpc = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref grabbableNameClientRpc, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetGrabbableNameClientRpc(grabbableNameClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_949135576(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0036: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Vector3 itemPositionClientRpc = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref itemPositionClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetItemPositionClientRpc(itemPositionClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1528367091(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0036: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Quaternion itemRotationClientRpc = default(Quaternion);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref itemRotationClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetItemRotationClientRpc(itemRotationClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_2688253945(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0036: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				Vector3 itemScaleClientRpc = default(Vector3);
				((FastBufferReader)(ref reader)).ReadValueSafe(ref itemScaleClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetItemScaleClientRpc(itemScaleClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_4227417717(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool isScrapClientRpc = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref isScrapClientRpc, default(ForPrimitives));
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetIsScrapClientRpc(isScrapClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_3866863385(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				int scrapValueClientRpc = default(int);
				ByteUnpacker.ReadValueBitPacked(reader, ref scrapValueClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).SetScrapValueClientRpc(scrapValueClientRpc);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1050513218(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).RemoveFromHolderClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		private static void __rpc_handler_1334565671(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((Item)(object)target).InitializeScrapClientRpc();
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		protected internal override string __getTypeName()
		{
			return "Item";
		}
	}
	public class Player : NetworkBehaviour
	{
		public class PlayerInventory : NetworkBehaviour
		{
			public Player Player { get; private set; }

			public Item[] Items => Player.PlayerController.ItemSlots.Select((GrabbableObject i) => (!((Object)(object)i != (Object)null)) ? null : Item.Dictionary[i]).ToArray();

			public int CurrentSlot
			{
				get
				{
					return Player.PlayerController.currentItemSlot;
				}
				set
				{
					//IL_0011: Unknown result type (might be due to invalid IL or missing references)
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					if (Player.IsLocalPlayer)
					{
						SetSlotServerRpc(value);
					}
					else if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
					{
						SetSlotClientRpc(value);
					}
				}
			}

			[ServerRpc(RequireOwnership = false)]
			private void SetSlotServerRpc(int slot, ServerRpcParams serverRpcParams = default(ServerRpcParams))
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c8: 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)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
					{
						FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1475903090u, serverRpcParams, (RpcDelivery)0);
						BytePacker.WriteValueBitPacked(val, slot);
						((NetworkBehaviour)this).__endSendServerRpc(ref val, 1475903090u, serverRpcParams, (RpcDelivery)0);
					}
					if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && serverRpcParams.Receive.SenderClientId == Player.ClientId)
					{
						SetSlotClientRpc(slot);
					}
				}
			}

			[ClientRpc]
			private void SetSlotClientRpc(int slot)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
					{
						ClientRpcParams val = default(ClientRpcParams);
						FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2977994897u, val, (RpcDelivery)0);
						BytePacker.WriteValueBitPacked(val2, slot);
						((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2977994897u, val, (RpcDelivery)0);
					}
					if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
					{
						Player.PlayerController.SwitchToItemSlot(slot, (GrabbableObject)null);
					}
				}
			}

			public int GetFirstEmptySlot()
			{
				return Player.PlayerController.FirstEmptyItemSlot();
			}

			public bool TryGetFirstEmptySlot(out int slot)
			{
				slot = Player.PlayerController.FirstEmptyItemSlot();
				return slot != -1;
			}

			public bool TryAddItem(Item item, bool switchTo = true)
			{
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to add item from client.");
				}
				if (TryGetFirstEmptySlot(out var slot))
				{
					if (item.IsTwoHanded && !Player.HasFreeHands)
					{
						return false;
					}
					if (item.IsHeld)
					{
						item.RemoveFromHolder();
					}
					((NetworkBehaviour)item).NetworkObject.ChangeOwnership(Player.ClientId);
					if (item.IsTwoHanded)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (switchTo && Player.HasFreeHands)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else if (Player.PlayerController.currentItemSlot == slot)
					{
						SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					else
					{
						SetItemInSlotClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
					}
					return true;
				}
				return false;
			}

			public bool TryAddItemToSlot(Item item, int slot, bool switchTo = true)
			{
				//IL_007a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: 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_0089: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost)
				{
					throw new NoAuthorityException("Tried to add item from client.");
				}
				if (slot < Player.PlayerController.ItemSlots.Length && (Object)(object)Player.PlayerController.ItemSlots[slot] == (Object)null)
				{
					if (item.IsTwoHanded && !Player.HasFreeHands)
					{
						return false;
					}
		

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/LethalConfig/LethalConfig.dll

Decompiled 7 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using LethalConfig.AutoConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using LethalConfig.Mods;
using LethalConfig.MonoBehaviours;
using LethalConfig.MonoBehaviours.Components;
using LethalConfig.MonoBehaviours.Managers;
using LethalConfig.Settings;
using LethalConfig.Utils;
using Newtonsoft.Json;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
[CompilerGenerated]
[EditorBrowsable(EditorBrowsableState.Never)]
[GeneratedCode("Unity.MonoScriptGenerator.MonoScriptInfoGenerator", null)]
internal class UnitySourceGeneratedAssemblyMonoScriptTypes_v1
{
	private struct MonoScriptData
	{
		public byte[] FilePathsData;

		public byte[] TypesData;

		public int TotalTypes;

		public int TotalFiles;

		public bool IsEditorOnly;
	}

	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	private static MonoScriptData Get()
	{
		MonoScriptData result = default(MonoScriptData);
		result.FilePathsData = new byte[3641]
		{
			0, 0, 0, 2, 0, 0, 0, 49, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 65, 117, 116, 111, 67, 111,
			110, 102, 105, 103, 92, 65, 117, 116, 111, 67,
			111, 110, 102, 105, 103, 71, 101, 110, 101, 114,
			97, 116, 111, 114, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 45, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 65, 117, 116, 111, 67, 111, 110, 102, 105,
			103, 92, 67, 111, 110, 102, 105, 103, 69, 110,
			116, 114, 121, 80, 97, 116, 104, 46, 99, 115,
			0, 0, 0, 2, 0, 0, 0, 45, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 115, 92, 66, 97, 115, 101,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			53, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 92, 66,
			111, 111, 108, 67, 104, 101, 99, 107, 66, 111,
			120, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 53, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 92,
			69, 110, 117, 109, 68, 114, 111, 112, 68, 111,
			119, 110, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 56, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			92, 70, 108, 111, 97, 116, 73, 110, 112, 117,
			116, 70, 105, 101, 108, 100, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 52, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 115, 92, 70, 108, 111, 97, 116,
			83, 108, 105, 100, 101, 114, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 56, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 115, 92, 70, 108, 111, 97, 116,
			83, 116, 101, 112, 83, 108, 105, 100, 101, 114,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			54, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 92, 71,
			101, 110, 101, 114, 105, 99, 66, 117, 116, 116,
			111, 110, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 54, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			92, 73, 110, 116, 73, 110, 112, 117, 116, 70,
			105, 101, 108, 100, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 50, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 115, 92, 73, 110, 116, 83, 108, 105, 100,
			101, 114, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 50, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			92, 79, 112, 116, 105, 111, 110, 115, 92, 66,
			97, 115, 101, 79, 112, 116, 105, 111, 110, 115,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			55, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 92, 79,
			112, 116, 105, 111, 110, 115, 92, 66, 97, 115,
			101, 82, 97, 110, 103, 101, 79, 112, 116, 105,
			111, 110, 115, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 58, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			115, 92, 79, 112, 116, 105, 111, 110, 115, 92,
			66, 111, 111, 108, 67, 104, 101, 99, 107, 66,
			111, 120, 79, 112, 116, 105, 111, 110, 115, 46,
			99, 115, 0, 0, 0, 1, 0, 0, 0, 54,
			92, 65, 115, 115, 101, 116, 115, 92, 83, 99,
			114, 105, 112, 116, 115, 92, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 115, 92, 79, 112,
			116, 105, 111, 110, 115, 92, 67, 97, 110, 77,
			111, 100, 105, 102, 121, 82, 101, 115, 117, 108,
			116, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 58, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 92,
			79, 112, 116, 105, 111, 110, 115, 92, 69, 110,
			117, 109, 68, 114, 111, 112, 68, 111, 119, 110,
			79, 112, 116, 105, 111, 110, 115, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 61, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 115, 92, 79, 112, 116, 105,
			111, 110, 115, 92, 70, 108, 111, 97, 116, 73,
			110, 112, 117, 116, 70, 105, 101, 108, 100, 79,
			112, 116, 105, 111, 110, 115, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 57, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 115, 92, 79, 112, 116, 105, 111,
			110, 115, 92, 70, 108, 111, 97, 116, 83, 108,
			105, 100, 101, 114, 79, 112, 116, 105, 111, 110,
			115, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 61, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 92,
			79, 112, 116, 105, 111, 110, 115, 92, 70, 108,
			111, 97, 116, 83, 116, 101, 112, 83, 108, 105,
			100, 101, 114, 79, 112, 116, 105, 111, 110, 115,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			59, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 92, 79,
			112, 116, 105, 111, 110, 115, 92, 71, 101, 110,
			101, 114, 105, 99, 66, 117, 116, 116, 111, 110,
			79, 112, 116, 105, 111, 110, 115, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 59, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 115, 92, 79, 112, 116, 105,
			111, 110, 115, 92, 73, 110, 116, 73, 110, 112,
			117, 116, 70, 105, 101, 108, 100, 79, 112, 116,
			105, 111, 110, 115, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 55, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 115, 92, 79, 112, 116, 105, 111, 110, 115,
			92, 73, 110, 116, 83, 108, 105, 100, 101, 114,
			79, 112, 116, 105, 111, 110, 115, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 60, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 115, 92, 79, 112, 116, 105,
			111, 110, 115, 92, 84, 101, 120, 116, 73, 110,
			112, 117, 116, 70, 105, 101, 108, 100, 79, 112,
			116, 105, 111, 110, 115, 46, 99, 115, 0, 0,
			0, 1, 0, 0, 0, 55, 92, 65, 115, 115,
			101, 116, 115, 92, 83, 99, 114, 105, 112, 116,
			115, 92, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 115, 92, 84, 101, 120, 116, 73, 110,
			112, 117, 116, 70, 105, 101, 108, 100, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 46, 99,
			115, 0, 0, 0, 1, 0, 0, 0, 38, 92,
			65, 115, 115, 101, 116, 115, 92, 83, 99, 114,
			105, 112, 116, 115, 92, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 77, 97, 110,
			97, 103, 101, 114, 46, 99, 115, 0, 0, 0,
			2, 0, 0, 0, 37, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 76, 101, 116, 104, 97, 108, 67, 111, 110,
			102, 105, 103, 80, 108, 117, 103, 105, 110, 46,
			99, 115, 0, 0, 0, 1, 0, 0, 0, 27,
			92, 65, 115, 115, 101, 116, 115, 92, 83, 99,
			114, 105, 112, 116, 115, 92, 77, 111, 100, 115,
			92, 77, 111, 100, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 31, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 77, 111, 100, 115, 92, 77, 111, 100, 73,
			110, 102, 111, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 44, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			77, 111, 100, 115, 92, 84, 104, 117, 110, 100,
			101, 114, 115, 116, 111, 114, 101, 77, 97, 110,
			105, 102, 101, 115, 116, 46, 99, 115, 0, 0,
			0, 1, 0, 0, 0, 67, 92, 65, 115, 115,
			101, 116, 115, 92, 83, 99, 114, 105, 112, 116,
			115, 92, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 92, 67, 111, 109,
			112, 111, 110, 101, 110, 116, 115, 92, 66, 111,
			111, 108, 67, 104, 101, 99, 107, 66, 111, 120,
			67, 111, 110, 116, 114, 111, 108, 108, 101, 114,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			67, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 77, 111, 110,
			111, 66, 101, 104, 97, 118, 105, 111, 117, 114,
			115, 92, 67, 111, 109, 112, 111, 110, 101, 110,
			116, 115, 92, 69, 110, 117, 109, 68, 114, 111,
			112, 68, 111, 119, 110, 67, 111, 110, 116, 114,
			111, 108, 108, 101, 114, 46, 99, 115, 0, 0,
			0, 1, 0, 0, 0, 70, 92, 65, 115, 115,
			101, 116, 115, 92, 83, 99, 114, 105, 112, 116,
			115, 92, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 92, 67, 111, 109,
			112, 111, 110, 101, 110, 116, 115, 92, 70, 108,
			111, 97, 116, 73, 110, 112, 117, 116, 70, 105,
			101, 108, 100, 67, 111, 110, 116, 114, 111, 108,
			108, 101, 114, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 66, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 92, 67, 111, 109, 112, 111,
			110, 101, 110, 116, 115, 92, 70, 108, 111, 97,
			116, 83, 108, 105, 100, 101, 114, 67, 111, 110,
			116, 114, 111, 108, 108, 101, 114, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 70, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 92, 67,
			111, 109, 112, 111, 110, 101, 110, 116, 115, 92,
			70, 108, 111, 97, 116, 83, 116, 101, 112, 83,
			108, 105, 100, 101, 114, 67, 111, 110, 116, 114,
			111, 108, 108, 101, 114, 46, 99, 115, 0, 0,
			0, 1, 0, 0, 0, 68, 92, 65, 115, 115,
			101, 116, 115, 92, 83, 99, 114, 105, 112, 116,
			115, 92, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 92, 67, 111, 109,
			112, 111, 110, 101, 110, 116, 115, 92, 71, 101,
			110, 101, 114, 105, 99, 66, 117, 116, 116, 111,
			110, 67, 111, 110, 116, 114, 111, 108, 108, 101,
			114, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 68, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 92, 67, 111, 109, 112, 111, 110, 101,
			110, 116, 115, 92, 73, 110, 116, 73, 110, 112,
			117, 116, 70, 105, 101, 108, 100, 67, 111, 110,
			116, 114, 111, 108, 108, 101, 114, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 64, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 92, 67,
			111, 109, 112, 111, 110, 101, 110, 116, 115, 92,
			73, 110, 116, 83, 108, 105, 100, 101, 114, 67,
			111, 110, 116, 114, 111, 108, 108, 101, 114, 46,
			99, 115, 0, 0, 0, 2, 0, 0, 0, 64,
			92, 65, 115, 115, 101, 116, 115, 92, 83, 99,
			114, 105, 112, 116, 115, 92, 77, 111, 110, 111,
			66, 101, 104, 97, 118, 105, 111, 117, 114, 115,
			92, 67, 111, 109, 112, 111, 110, 101, 110, 116,
			115, 92, 77, 111, 100, 67, 111, 110, 102, 105,
			103, 67, 111, 110, 116, 114, 111, 108, 108, 101,
			114, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 69, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 92, 67, 111, 109, 112, 111, 110, 101,
			110, 116, 115, 92, 84, 101, 120, 116, 73, 110,
			112, 117, 116, 70, 105, 101, 108, 100, 67, 111,
			110, 116, 114, 111, 108, 108, 101, 114, 46, 99,
			115, 0, 0, 0, 1, 0, 0, 0, 47, 92,
			65, 115, 115, 101, 116, 115, 92, 83, 99, 114,
			105, 112, 116, 115, 92, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 92,
			67, 111, 110, 102, 105, 103, 73, 110, 102, 111,
			66, 111, 120, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 44, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 92, 67, 111, 110, 102, 105,
			103, 76, 105, 115, 116, 46, 99, 115, 0, 0,
			0, 1, 0, 0, 0, 44, 92, 65, 115, 115,
			101, 116, 115, 92, 83, 99, 114, 105, 112, 116,
			115, 92, 77, 111, 110, 111, 66, 101, 104, 97,
			118, 105, 111, 117, 114, 115, 92, 67, 111, 110,
			102, 105, 103, 77, 101, 110, 117, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 56, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 92, 67,
			111, 110, 102, 105, 103, 77, 101, 110, 117, 78,
			111, 116, 105, 102, 105, 99, 97, 116, 105, 111,
			110, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 48, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 92, 68, 101, 115, 99, 114, 105, 112,
			116, 105, 111, 110, 66, 111, 120, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 65, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 92, 77,
			97, 110, 97, 103, 101, 114, 115, 92, 67, 111,
			110, 102, 105, 103, 77, 101, 110, 117, 65, 117,
			100, 105, 111, 77, 97, 110, 97, 103, 101, 114,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			60, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 77, 111, 110,
			111, 66, 101, 104, 97, 118, 105, 111, 117, 114,
			115, 92, 77, 97, 110, 97, 103, 101, 114, 115,
			92, 67, 111, 110, 102, 105, 103, 77, 101, 110,
			117, 77, 97, 110, 97, 103, 101, 114, 46, 99,
			115, 0, 0, 0, 1, 0, 0, 0, 44, 92,
			65, 115, 115, 101, 116, 115, 92, 83, 99, 114,
			105, 112, 116, 115, 92, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 92,
			77, 111, 100, 73, 110, 102, 111, 66, 111, 120,
			46, 99, 115, 0, 0, 0, 1, 0, 0, 0,
			41, 92, 65, 115, 115, 101, 116, 115, 92, 83,
			99, 114, 105, 112, 116, 115, 92, 77, 111, 110,
			111, 66, 101, 104, 97, 118, 105, 111, 117, 114,
			115, 92, 77, 111, 100, 76, 105, 115, 116, 46,
			99, 115, 0, 0, 0, 1, 0, 0, 0, 45,
			92, 65, 115, 115, 101, 116, 115, 92, 83, 99,
			114, 105, 112, 116, 115, 92, 77, 111, 110, 111,
			66, 101, 104, 97, 118, 105, 111, 117, 114, 115,
			92, 77, 111, 100, 76, 105, 115, 116, 73, 116,
			101, 109, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 47, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 77,
			111, 110, 111, 66, 101, 104, 97, 118, 105, 111,
			117, 114, 115, 92, 83, 101, 99, 116, 105, 111,
			110, 72, 101, 97, 100, 101, 114, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 41, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 92, 84,
			111, 111, 108, 116, 105, 112, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 47, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 77, 111, 110, 111, 66, 101, 104,
			97, 118, 105, 111, 117, 114, 115, 92, 84, 111,
			111, 108, 116, 105, 112, 83, 121, 115, 116, 101,
			109, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 48, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 92, 84, 111, 111, 108, 116, 105, 112,
			84, 114, 105, 103, 103, 101, 114, 46, 99, 115,
			0, 0, 0, 1, 0, 0, 0, 46, 92, 65,
			115, 115, 101, 116, 115, 92, 83, 99, 114, 105,
			112, 116, 115, 92, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 92, 86,
			101, 114, 115, 105, 111, 110, 76, 97, 98, 101,
			108, 46, 99, 115, 0, 0, 0, 1, 0, 0,
			0, 45, 92, 65, 115, 115, 101, 116, 115, 92,
			83, 99, 114, 105, 112, 116, 115, 92, 80, 97,
			116, 99, 104, 101, 115, 92, 77, 101, 110, 117,
			77, 97, 110, 97, 103, 101, 114, 80, 97, 116,
			99, 104, 101, 115, 46, 99, 115, 0, 0, 0,
			1, 0, 0, 0, 50, 92, 65, 115, 115, 101,
			116, 115, 92, 83, 99, 114, 105, 112, 116, 115,
			92, 80, 97, 116, 99, 104, 101, 115, 92, 81,
			117, 105, 99, 107, 77, 101, 110, 117, 77, 97,
			110, 97, 103, 101, 114, 80, 97, 116, 99, 104,
			101, 115, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 43, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 85,
			116, 105, 108, 115, 92, 65, 115, 115, 101, 109,
			98, 108, 121, 69, 120, 116, 101, 110, 115, 105,
			111, 110, 115, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 31, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			85, 116, 105, 108, 115, 92, 65, 115, 115, 101,
			116, 115, 46, 99, 115, 0, 0, 0, 1, 0,
			0, 0, 33, 92, 65, 115, 115, 101, 116, 115,
			92, 83, 99, 114, 105, 112, 116, 115, 92, 85,
			116, 105, 108, 115, 92, 76, 111, 103, 85, 116,
			105, 108, 115, 46, 99, 115, 0, 0, 0, 1,
			0, 0, 0, 35, 92, 65, 115, 115, 101, 116,
			115, 92, 83, 99, 114, 105, 112, 116, 115, 92,
			85, 116, 105, 108, 115, 92, 77, 101, 110, 117,
			115, 85, 116, 105, 108, 115, 46, 99, 115, 0,
			0, 0, 1, 0, 0, 0, 34, 92, 65, 115,
			115, 101, 116, 115, 92, 83, 99, 114, 105, 112,
			116, 115, 92, 85, 116, 105, 108, 115, 92, 80,
			97, 116, 104, 85, 116, 105, 108, 115, 46, 99,
			115
		};
		result.TypesData = new byte[3298]
		{
			0, 0, 0, 0, 43, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 65, 117,
			116, 111, 67, 111, 110, 102, 105, 103, 124, 65,
			117, 116, 111, 67, 111, 110, 102, 105, 103, 71,
			101, 110, 101, 114, 97, 116, 111, 114, 0, 0,
			0, 0, 58, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 65, 117, 116, 111,
			67, 111, 110, 102, 105, 103, 46, 65, 117, 116,
			111, 67, 111, 110, 102, 105, 103, 71, 101, 110,
			101, 114, 97, 116, 111, 114, 124, 65, 117, 116,
			111, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 0, 0, 0, 0, 39, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 65,
			117, 116, 111, 67, 111, 110, 102, 105, 103, 124,
			67, 111, 110, 102, 105, 103, 69, 110, 116, 114,
			121, 80, 97, 116, 104, 0, 0, 0, 0, 39,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 46, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 115, 124, 66, 97, 115, 101, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 0,
			0, 0, 0, 44, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 124, 66,
			97, 115, 101, 86, 97, 108, 117, 101, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 0, 0,
			0, 0, 47, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 115, 124, 66, 111,
			111, 108, 67, 104, 101, 99, 107, 66, 111, 120,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			0, 0, 0, 0, 47, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 124,
			69, 110, 117, 109, 68, 114, 111, 112, 68, 111,
			119, 110, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 0, 0, 0, 0, 50, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			115, 124, 70, 108, 111, 97, 116, 73, 110, 112,
			117, 116, 70, 105, 101, 108, 100, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 0, 0, 0,
			0, 46, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 67, 111, 110, 102, 105,
			103, 73, 116, 101, 109, 115, 124, 70, 108, 111,
			97, 116, 83, 108, 105, 100, 101, 114, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 0, 0,
			0, 0, 50, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 115, 124, 70, 108,
			111, 97, 116, 83, 116, 101, 112, 83, 108, 105,
			100, 101, 114, 67, 111, 110, 102, 105, 103, 73,
			116, 101, 109, 0, 0, 0, 0, 48, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 115, 124, 71, 101, 110, 101, 114, 105, 99,
			66, 117, 116, 116, 111, 110, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 0, 0, 0, 0,
			48, 76, 101, 116, 104, 97, 108, 67, 111, 110,
			102, 105, 103, 46, 67, 111, 110, 102, 105, 103,
			73, 116, 101, 109, 115, 124, 73, 110, 116, 73,
			110, 112, 117, 116, 70, 105, 101, 108, 100, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 0,
			0, 0, 0, 44, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 115, 124, 73,
			110, 116, 83, 108, 105, 100, 101, 114, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 0, 0,
			0, 0, 44, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 115, 46, 79, 112,
			116, 105, 111, 110, 115, 124, 66, 97, 115, 101,
			79, 112, 116, 105, 111, 110, 115, 0, 0, 0,
			0, 49, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 67, 111, 110, 102, 105,
			103, 73, 116, 101, 109, 115, 46, 79, 112, 116,
			105, 111, 110, 115, 124, 66, 97, 115, 101, 82,
			97, 110, 103, 101, 79, 112, 116, 105, 111, 110,
			115, 0, 0, 0, 0, 52, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			46, 79, 112, 116, 105, 111, 110, 115, 124, 66,
			111, 111, 108, 67, 104, 101, 99, 107, 66, 111,
			120, 79, 112, 116, 105, 111, 110, 115, 0, 0,
			0, 0, 48, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 115, 46, 79, 112,
			116, 105, 111, 110, 115, 124, 67, 97, 110, 77,
			111, 100, 105, 102, 121, 82, 101, 115, 117, 108,
			116, 0, 0, 0, 0, 52, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 67,
			111, 110, 102, 105, 103, 73, 116, 101, 109, 115,
			46, 79, 112, 116, 105, 111, 110, 115, 124, 69,
			110, 117, 109, 68, 114, 111, 112, 68, 111, 119,
			110, 79, 112, 116, 105, 111, 110, 115, 0, 0,
			0, 0, 55, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 115, 46, 79, 112,
			116, 105, 111, 110, 115, 124, 70, 108, 111, 97,
			116, 73, 110, 112, 117, 116, 70, 105, 101, 108,
			100, 79, 112, 116, 105, 111, 110, 115, 0, 0,
			0, 0, 51, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 67, 111, 110, 102,
			105, 103, 73, 116, 101, 109, 115, 46, 79, 112,
			116, 105, 111, 110, 115, 124, 70, 108, 111, 97,
			116, 83, 108, 105, 100, 101, 114, 79, 112, 116,
			105, 111, 110, 115, 0, 0, 0, 0, 55, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 115, 46, 79, 112, 116, 105, 111, 110,
			115, 124, 70, 108, 111, 97, 116, 83, 116, 101,
			112, 83, 108, 105, 100, 101, 114, 79, 112, 116,
			105, 111, 110, 115, 0, 0, 0, 0, 53, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 115, 46, 79, 112, 116, 105, 111, 110,
			115, 124, 71, 101, 110, 101, 114, 105, 99, 66,
			117, 116, 116, 111, 110, 79, 112, 116, 105, 111,
			110, 115, 0, 0, 0, 0, 53, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			67, 111, 110, 102, 105, 103, 73, 116, 101, 109,
			115, 46, 79, 112, 116, 105, 111, 110, 115, 124,
			73, 110, 116, 73, 110, 112, 117, 116, 70, 105,
			101, 108, 100, 79, 112, 116, 105, 111, 110, 115,
			0, 0, 0, 0, 49, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 67, 111,
			110, 102, 105, 103, 73, 116, 101, 109, 115, 46,
			79, 112, 116, 105, 111, 110, 115, 124, 73, 110,
			116, 83, 108, 105, 100, 101, 114, 79, 112, 116,
			105, 111, 110, 115, 0, 0, 0, 0, 54, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 67, 111, 110, 102, 105, 103, 73, 116,
			101, 109, 115, 46, 79, 112, 116, 105, 111, 110,
			115, 124, 84, 101, 120, 116, 73, 110, 112, 117,
			116, 70, 105, 101, 108, 100, 79, 112, 116, 105,
			111, 110, 115, 0, 0, 0, 0, 49, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 67, 111, 110, 102, 105, 103, 73, 116, 101,
			109, 115, 124, 84, 101, 120, 116, 73, 110, 112,
			117, 116, 70, 105, 101, 108, 100, 67, 111, 110,
			102, 105, 103, 73, 116, 101, 109, 0, 0, 0,
			0, 32, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 124, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 77, 97, 110,
			97, 103, 101, 114, 0, 0, 0, 0, 23, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 124, 80, 108, 117, 103, 105, 110, 73, 110,
			102, 111, 0, 0, 0, 0, 31, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 124,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 80, 108, 117, 103, 105, 110, 0, 0,
			0, 0, 21, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 77, 111, 100, 115,
			124, 77, 111, 100, 0, 0, 0, 0, 25, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 77, 111, 100, 115, 124, 77, 111, 100,
			73, 110, 102, 111, 0, 0, 0, 0, 38, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 77, 111, 100, 115, 124, 84, 104, 117,
			110, 100, 101, 114, 115, 116, 111, 114, 101, 77,
			97, 110, 105, 102, 101, 115, 116, 0, 0, 0,
			0, 61, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 46,
			67, 111, 109, 112, 111, 110, 101, 110, 116, 115,
			124, 66, 111, 111, 108, 67, 104, 101, 99, 107,
			66, 111, 120, 67, 111, 110, 116, 114, 111, 108,
			108, 101, 114, 0, 0, 0, 0, 61, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 46, 67, 111, 109, 112,
			111, 110, 101, 110, 116, 115, 124, 69, 110, 117,
			109, 68, 114, 111, 112, 68, 111, 119, 110, 67,
			111, 110, 116, 114, 111, 108, 108, 101, 114, 0,
			0, 0, 0, 64, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 77, 111, 110,
			111, 66, 101, 104, 97, 118, 105, 111, 117, 114,
			115, 46, 67, 111, 109, 112, 111, 110, 101, 110,
			116, 115, 124, 70, 108, 111, 97, 116, 73, 110,
			112, 117, 116, 70, 105, 101, 108, 100, 67, 111,
			110, 116, 114, 111, 108, 108, 101, 114, 0, 0,
			0, 0, 60, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 77, 111, 110, 111,
			66, 101, 104, 97, 118, 105, 111, 117, 114, 115,
			46, 67, 111, 109, 112, 111, 110, 101, 110, 116,
			115, 124, 70, 108, 111, 97, 116, 83, 108, 105,
			100, 101, 114, 67, 111, 110, 116, 114, 111, 108,
			108, 101, 114, 0, 0, 0, 0, 64, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 46, 67, 111, 109, 112,
			111, 110, 101, 110, 116, 115, 124, 70, 108, 111,
			97, 116, 83, 116, 101, 112, 83, 108, 105, 100,
			101, 114, 67, 111, 110, 116, 114, 111, 108, 108,
			101, 114, 0, 0, 0, 0, 62, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 46, 67, 111, 109, 112, 111,
			110, 101, 110, 116, 115, 124, 71, 101, 110, 101,
			114, 105, 99, 66, 117, 116, 116, 111, 110, 67,
			111, 110, 116, 114, 111, 108, 108, 101, 114, 0,
			0, 0, 0, 62, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 77, 111, 110,
			111, 66, 101, 104, 97, 118, 105, 111, 117, 114,
			115, 46, 67, 111, 109, 112, 111, 110, 101, 110,
			116, 115, 124, 73, 110, 116, 73, 110, 112, 117,
			116, 70, 105, 101, 108, 100, 67, 111, 110, 116,
			114, 111, 108, 108, 101, 114, 0, 0, 0, 0,
			58, 76, 101, 116, 104, 97, 108, 67, 111, 110,
			102, 105, 103, 46, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 46, 67,
			111, 109, 112, 111, 110, 101, 110, 116, 115, 124,
			73, 110, 116, 83, 108, 105, 100, 101, 114, 67,
			111, 110, 116, 114, 111, 108, 108, 101, 114, 1,
			0, 0, 0, 58, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 77, 111, 110,
			111, 66, 101, 104, 97, 118, 105, 111, 117, 114,
			115, 46, 67, 111, 109, 112, 111, 110, 101, 110,
			116, 115, 124, 77, 111, 100, 67, 111, 110, 102,
			105, 103, 67, 111, 110, 116, 114, 111, 108, 108,
			101, 114, 1, 0, 0, 0, 58, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 46, 67, 111, 109, 112, 111,
			110, 101, 110, 116, 115, 124, 77, 111, 100, 67,
			111, 110, 102, 105, 103, 67, 111, 110, 116, 114,
			111, 108, 108, 101, 114, 0, 0, 0, 0, 63,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 46, 77, 111, 110, 111, 66, 101, 104,
			97, 118, 105, 111, 117, 114, 115, 46, 67, 111,
			109, 112, 111, 110, 101, 110, 116, 115, 124, 84,
			101, 120, 116, 73, 110, 112, 117, 116, 70, 105,
			101, 108, 100, 67, 111, 110, 116, 114, 111, 108,
			108, 101, 114, 0, 0, 0, 0, 41, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 124, 67, 111, 110, 102,
			105, 103, 73, 110, 102, 111, 66, 111, 120, 0,
			0, 0, 0, 38, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 77, 111, 110,
			111, 66, 101, 104, 97, 118, 105, 111, 117, 114,
			115, 124, 67, 111, 110, 102, 105, 103, 76, 105,
			115, 116, 0, 0, 0, 0, 38, 76, 101, 116,
			104, 97, 108, 67, 111, 110, 102, 105, 103, 46,
			77, 111, 110, 111, 66, 101, 104, 97, 118, 105,
			111, 117, 114, 115, 124, 67, 111, 110, 102, 105,
			103, 77, 101, 110, 117, 0, 0, 0, 0, 50,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 46, 77, 111, 110, 111, 66, 101, 104,
			97, 118, 105, 111, 117, 114, 115, 124, 67, 111,
			110, 102, 105, 103, 77, 101, 110, 117, 78, 111,
			116, 105, 102, 105, 99, 97, 116, 105, 111, 110,
			0, 0, 0, 0, 42, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 124, 68, 101, 115, 99, 114, 105, 112,
			116, 105, 111, 110, 66, 111, 120, 0, 0, 0,
			0, 59, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 46,
			77, 97, 110, 97, 103, 101, 114, 115, 124, 67,
			111, 110, 102, 105, 103, 77, 101, 110, 117, 65,
			117, 100, 105, 111, 77, 97, 110, 97, 103, 101,
			114, 0, 0, 0, 0, 54, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 77,
			111, 110, 111, 66, 101, 104, 97, 118, 105, 111,
			117, 114, 115, 46, 77, 97, 110, 97, 103, 101,
			114, 115, 124, 67, 111, 110, 102, 105, 103, 77,
			101, 110, 117, 77, 97, 110, 97, 103, 101, 114,
			0, 0, 0, 0, 38, 76, 101, 116, 104, 97,
			108, 67, 111, 110, 102, 105, 103, 46, 77, 111,
			110, 111, 66, 101, 104, 97, 118, 105, 111, 117,
			114, 115, 124, 77, 111, 100, 73, 110, 102, 111,
			66, 111, 120, 0, 0, 0, 0, 35, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 124, 77, 111, 100, 76,
			105, 115, 116, 0, 0, 0, 0, 39, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 124, 77, 111, 100, 76,
			105, 115, 116, 73, 116, 101, 109, 0, 0, 0,
			0, 41, 76, 101, 116, 104, 97, 108, 67, 111,
			110, 102, 105, 103, 46, 77, 111, 110, 111, 66,
			101, 104, 97, 118, 105, 111, 117, 114, 115, 124,
			83, 101, 99, 116, 105, 111, 110, 72, 101, 97,
			100, 101, 114, 0, 0, 0, 0, 35, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 124, 84, 111, 111, 108,
			116, 105, 112, 0, 0, 0, 0, 41, 76, 101,
			116, 104, 97, 108, 67, 111, 110, 102, 105, 103,
			46, 77, 111, 110, 111, 66, 101, 104, 97, 118,
			105, 111, 117, 114, 115, 124, 84, 111, 111, 108,
			116, 105, 112, 83, 121, 115, 116, 101, 109, 0,
			0, 0, 0, 42, 76, 101, 116, 104, 97, 108,
			67, 111, 110, 102, 105, 103, 46, 77, 111, 110,
			111, 66, 101, 104, 97, 118, 105, 111, 117, 114,
			115, 124, 84, 111, 111, 108, 116, 105, 112, 84,
			114, 105, 103, 103, 101, 114, 0, 0, 0, 0,
			40, 76, 101, 116, 104, 97, 108, 67, 111, 110,
			102, 105, 103, 46, 77, 111, 110, 111, 66, 101,
			104, 97, 118, 105, 111, 117, 114, 115, 124, 86,
			101, 114, 115, 105, 111, 110, 76, 97, 98, 101,
			108, 0, 0, 0, 0, 39, 76, 101, 116, 104,
			97, 108, 67, 111, 110, 102, 105, 103, 46, 80,
			97, 116, 99, 104, 101, 115, 124, 77, 101, 110,
			117, 77, 97, 110, 97, 103, 101, 114, 80, 97,
			116, 99, 104, 101, 115, 0, 0, 0, 0, 44,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 46, 80, 97, 116, 99, 104, 101, 115,
			124, 81, 117, 105, 99, 107, 77, 101, 110, 117,
			77, 97, 110, 97, 103, 101, 114, 80, 97, 116,
			99, 104, 101, 115, 0, 0, 0, 0, 37, 76,
			101, 116, 104, 97, 108, 67, 111, 110, 102, 105,
			103, 46, 85, 116, 105, 108, 115, 124, 65, 115,
			115, 101, 109, 98, 108, 121, 69, 120, 116, 101,
			110, 115, 105, 111, 110, 115, 0, 0, 0, 0,
			25, 76, 101, 116, 104, 97, 108, 67, 111, 110,
			102, 105, 103, 46, 85, 116, 105, 108, 115, 124,
			65, 115, 115, 101, 116, 115, 0, 0, 0, 0,
			27, 76, 101, 116, 104, 97, 108, 67, 111, 110,
			102, 105, 103, 46, 85, 116, 105, 108, 115, 124,
			76, 111, 103, 85, 116, 105, 108, 115, 0, 0,
			0, 0, 32, 76, 101, 116, 104, 97, 108, 67,
			111, 110, 102, 105, 103, 46, 83, 101, 116, 116,
			105, 110, 103, 115, 124, 77, 101, 110, 117, 115,
			85, 116, 105, 108, 115, 0, 0, 0, 0, 28,
			76, 101, 116, 104, 97, 108, 67, 111, 110, 102,
			105, 103, 46, 85, 116, 105, 108, 115, 124, 80,
			97, 116, 104, 85, 116, 105, 108, 115
		};
		result.TotalFiles = 61;
		result.TotalTypes = 65;
		result.IsEditorOnly = false;
		return result;
	}
}
namespace LethalConfig
{
	public static class LethalConfigManager
	{
		private static bool hasGeneratedMissingConfigs = false;

		internal static Dictionary<string, Mod> Mods { get; private set; } = new Dictionary<string, Mod>();


		private static Dictionary<Mod, Assembly> ModToAssemblyMap { get; set; } = new Dictionary<Mod, Assembly>();


		internal static void AutoGenerateMissingConfigsIfNeeded()
		{
			if (hasGeneratedMissingConfigs)
			{
				return;
			}
			Mod[] second = Mods.Values.ToArray();
			IEnumerable<BaseConfigItem> existingConfigsFlat = Mods.SelectMany((KeyValuePair<string, Mod> kv) => kv.Value.configItems);
			AutoConfigGenerator.AutoConfigItem[] array = AutoConfigGenerator.AutoGenerateConfigs();
			Dictionary<Mod, IEnumerable<BaseConfigItem>> dictionary = (from c in array
				group c.ConfigItem by ModForAssembly(c.Assembly) into kv
				where kv.Key != null
				select kv).SelectMany((IGrouping<Mod, BaseConfigItem> kv) => from c in kv.Select(delegate(BaseConfigItem c)
				{
					c.Owner = kv.Key;
					return c;
				})
				where !kv.Key.entriesToSkipAutoGen.Any((ConfigEntryPath path) => path.Matches(c))
				where existingConfigsFlat.FirstOrDefault((BaseConfigItem ec) => c.IsSameConfig(ec)) == null
				group c by c.Owner).ToDictionary((IGrouping<Mod, BaseConfigItem> kv) => kv.Key, (IGrouping<Mod, BaseConfigItem> kv) => kv.Select((BaseConfigItem c) => c));
			Mod[] array2 = dictionary.Keys.Except(second).ToArray();
			Mod[] array3 = array2;
			foreach (Mod obj in array3)
			{
				obj.IsAutoGenerated = true;
				obj.modInfo.Description += "\n*This mod entry was automatically generated as it does not use LethalConfig directly.";
			}
			foreach (KeyValuePair<Mod, IEnumerable<BaseConfigItem>> item in dictionary)
			{
				Assembly valueOrDefault = ModToAssemblyMap.GetValueOrDefault(item.Key);
				if (!(valueOrDefault != null))
				{
					continue;
				}
				foreach (BaseConfigItem item2 in item.Value)
				{
					AddConfigItemForAssembly(item2, valueOrDefault);
				}
			}
			LogUtils.LogInfo($"Generated {array2.Count()} mod entries.");
			LogUtils.LogInfo($"Generated {array.Length} configs, of which {dictionary.SelectMany((KeyValuePair<Mod, IEnumerable<BaseConfigItem>> kv) => kv.Value).Count()} were missing and registered.");
			hasGeneratedMissingConfigs = true;
		}

		public static void AddConfigItem(BaseConfigItem configItem)
		{
			if (AddConfigItemForAssembly(configItem, Assembly.GetCallingAssembly()))
			{
				LogUtils.LogInfo($"Registered config \"{configItem}\"");
			}
		}

		private static bool AddConfigItemForAssembly(BaseConfigItem configItem, Assembly assembly)
		{
			Mod mod = ModForAssembly(assembly);
			if (mod == null)
			{
				LogUtils.LogWarning("Mod for assembly not found.");
				return false;
			}
			configItem.Owner = mod;
			if (mod.configItems.Where((BaseConfigItem c) => c.IsSameConfig(configItem)).Count() > 0)
			{
				LogUtils.LogWarning($"Ignoring duplicated config \"{configItem}\"");
				return false;
			}
			mod.AddConfigItem(configItem);
			return true;
		}

		private static Mod ModForAssembly(Assembly assembly)
		{
			if (assembly.TryGetModInfo(out var modInfo))
			{
				if (Mods.TryGetValue(modInfo.GUID, out var value))
				{
					return value;
				}
				Mod mod = new Mod(modInfo);
				Mods.Add(modInfo.GUID, mod);
				ModToAssemblyMap.Add(mod, assembly);
				return mod;
			}
			return null;
		}

		public static void SetModIcon(Sprite sprite)
		{
			if (!((Object)(object)sprite == (Object)null))
			{
				Mod mod = ModForAssembly(Assembly.GetCallingAssembly());
				if (mod != null)
				{
					mod.modInfo.Icon = sprite;
				}
			}
		}

		public static void SetModDescription(string description)
		{
			if (description != null)
			{
				Mod mod = ModForAssembly(Assembly.GetCallingAssembly());
				if (mod != null)
				{
					mod.modInfo.Description = description;
				}
			}
		}

		public static void SkipAutoGenFor(string configSection)
		{
			ModForAssembly(Assembly.GetCallingAssembly())?.entriesToSkipAutoGen.Add(new ConfigEntryPath(configSection, "*"));
		}

		public static void SkipAutoGenFor(ConfigEntryBase configEntryBase)
		{
			ModForAssembly(Assembly.GetCallingAssembly())?.entriesToSkipAutoGen.Add(new ConfigEntryPath(configEntryBase.Definition.Section, configEntryBase.Definition.Key));
		}

		public static void SkipAutoGen()
		{
			ModForAssembly(Assembly.GetCallingAssembly())?.entriesToSkipAutoGen.Add(new ConfigEntryPath("*", "*"));
		}
	}
	internal static class PluginInfo
	{
		public const string Guid = "ainavt.lc.lethalconfig";

		public const string Name = "LethalConfig";

		public const string Version = "1.3.4";
	}
	[BepInPlugin("ainavt.lc.lethalconfig", "LethalConfig", "1.3.4")]
	internal class LethalConfigPlugin : BaseUnityPlugin
	{
		private enum TestEnum
		{
			None,
			First,
			Second
		}

		private static LethalConfigPlugin instance;

		private static Harmony harmony;

		private void Awake()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			if ((Object)(object)instance == (Object)null)
			{
				instance = this;
			}
			LogUtils.Init("ainavt.lc.lethalconfig");
			Assets.Init();
			harmony = new Harmony("ainavt.lc.lethalconfig");
			harmony.PatchAll();
			CreateExampleConfigs();
			LogUtils.LogInfo("LethalConfig loaded!");
		}

		private void CreateExampleConfigs()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: 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
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Expected O, but got Unknown
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Expected O, but got Unknown
			ConfigEntry<int> configEntry = ((BaseUnityPlugin)this).Config.Bind<int>("Example", "Int Slider", 30, new ConfigDescription("This is an integer slider. You can also type a value in the input field to the right of the slider.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			ConfigEntry<float> configEntry2 = ((BaseUnityPlugin)this).Config.Bind<float>("Example", "Float Slider", 0f, new ConfigDescription("This is a float slider. You can also type a value in the input field to the right of the slider.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-1f, 1f), Array.Empty<object>()));
			ConfigEntry<float> configEntry3 = ((BaseUnityPlugin)this).Config.Bind<float>("Example", "Float Step Slider", 0f, new ConfigDescription("This is a float step slider. It set values in increments. You can also type a value in the input field to the right of the slider.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-1f, 1f), Array.Empty<object>()));
			ConfigEntry<bool> configEntry4 = ((BaseUnityPlugin)this).Config.Bind<bool>("Example", "Bool Checkbox", false, new ConfigDescription("This is a bool checkbox.", (AcceptableValueBase)null, Array.Empty<object>()));
			ConfigEntry<TestEnum> configEntry5 = ((BaseUnityPlugin)this).Config.Bind<TestEnum>("Example", "Enum Dropdown", TestEnum.None, new ConfigDescription("This is a enum dropdown.", (AcceptableValueBase)null, Array.Empty<object>()));
			ConfigEntry<string> configEntry6 = ((BaseUnityPlugin)this).Config.Bind<string>("Example", "Text Input", "Example", "This is a text input field. It can have a limit of characters too.");
			ConfigEntry<int> configEntry7 = ((BaseUnityPlugin)this).Config.Bind<int>("Example", "Int Input", 50, "This is an integer input field.");
			ConfigEntry<float> configEntry8 = ((BaseUnityPlugin)this).Config.Bind<float>("Example", "Float Input", 0.5f, "This is a float input field.");
			LethalConfigManager.AddConfigItem(new IntSliderConfigItem(configEntry, requiresRestart: false));
			LethalConfigManager.AddConfigItem(new FloatSliderConfigItem(configEntry2, requiresRestart: false));
			LethalConfigManager.AddConfigItem(new FloatStepSliderConfigItem(configEntry3, new FloatStepSliderOptions
			{
				Step = 0.1f,
				RequiresRestart = false,
				Min = -1f,
				Max = 1f
			}));
			LethalConfigManager.AddConfigItem(new BoolCheckBoxConfigItem(configEntry4, requiresRestart: false));
			LethalConfigManager.AddConfigItem(new EnumDropDownConfigItem<TestEnum>(configEntry5, requiresRestart: false));
			LethalConfigManager.AddConfigItem(new TextInputFieldConfigItem(configEntry6, requiresRestart: false));
			LethalConfigManager.AddConfigItem(new GenericButtonConfigItem("Example", "Button", "This is a test button with a callback", "Open", delegate
			{
				ConfigMenuManager.Instance?.DisplayNotification("Buttons can be used to open custom menus or other things.", "OK");
			}));
			LethalConfigManager.AddConfigItem(new IntInputFieldConfigItem(configEntry7, new IntInputFieldOptions
			{
				Max = 150
			}));
			LethalConfigManager.AddConfigItem(new FloatInputFieldConfigItem(configEntry8, new FloatInputFieldOptions
			{
				Max = 2.5f
			}));
		}
	}
}
namespace LethalConfig.Settings
{
	internal static class MenusUtils
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__0_0;

			public static UnityAction <>9__0_1;

			public static Func<Button, GameObject> <>9__0_2;

			public static Func<GameObject, RectTransform> <>9__0_4;

			public static Func<RectTransform, float> <>9__0_5;

			public static Func<float, float, float> <>9__0_6;

			internal void <InjectMenu>b__0_0()
			{
				ConfigMenuManager.Instance.ShowConfigMenu();
			}

			internal void <InjectMenu>b__0_1()
			{
				ConfigMenuManager.Instance.menuAudio.PlayConfirmSFX();
			}

			internal GameObject <InjectMenu>b__0_2(Button b)
			{
				return ((Component)b).gameObject;
			}

			internal RectTransform <InjectMenu>b__0_4(GameObject b)
			{
				Transform transform = b.transform;
				return (RectTransform)(object)((transform is RectTransform) ? transform : null);
			}

			internal float <InjectMenu>b__0_5(RectTransform t)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return t.anchoredPosition.y;
			}

			internal float <InjectMenu>b__0_6(float y1, float y2)
			{
				return Mathf.Abs(y2 - y1);
			}
		}

		internal static void InjectMenu(Transform parentTransform, Transform mainButtonsTransform, GameObject quitButton)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Expected O, but got Unknown
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = Object.Instantiate<GameObject>(Assets.ConfigMenuManagerPrefab);
			obj.transform.SetParent(parentTransform);
			obj.transform.localPosition = Vector3.zero;
			GameObject obj2 = Object.Instantiate<GameObject>(Assets.ConfigMenuPrefab);
			obj2.transform.SetParent(parentTransform, false);
			obj2.transform.localPosition = Vector3.zero;
			obj2.transform.localScale = Vector3.one;
			obj2.transform.localRotation = Quaternion.identity;
			obj2.SetActive(false);
			GameObject obj3 = Object.Instantiate<GameObject>(Assets.ConfigMenuNotificationPrefab);
			obj3.transform.SetParent(parentTransform, false);
			obj3.transform.localPosition = Vector3.zero;
			obj3.transform.localScale = Vector3.one;
			obj3.transform.localRotation = Quaternion.identity;
			obj3.SetActive(false);
			GameObject clonedButton = Object.Instantiate<GameObject>(quitButton, mainButtonsTransform);
			((UnityEventBase)clonedButton.GetComponent<Button>().onClick).RemoveAllListeners();
			clonedButton.GetComponent<Button>().onClick = new ButtonClickedEvent();
			ButtonClickedEvent onClick = clonedButton.GetComponent<Button>().onClick;
			object obj4 = <>c.<>9__0_0;
			if (obj4 == null)
			{
				UnityAction val = delegate
				{
					ConfigMenuManager.Instance.ShowConfigMenu();
				};
				<>c.<>9__0_0 = val;
				obj4 = (object)val;
			}
			((UnityEvent)onClick).AddListener((UnityAction)obj4);
			ButtonClickedEvent onClick2 = clonedButton.GetComponent<Button>().onClick;
			object obj5 = <>c.<>9__0_1;
			if (obj5 == null)
			{
				UnityAction val2 = delegate
				{
					ConfigMenuManager.Instance.menuAudio.PlayConfirmSFX();
				};
				<>c.<>9__0_1 = val2;
				obj5 = (object)val2;
			}
			((UnityEvent)onClick2).AddListener((UnityAction)obj5);
			((TMP_Text)clonedButton.GetComponentInChildren<TextMeshProUGUI>()).text = "> LethalConfig";
			IEnumerable<GameObject> source = from b in ((Component)mainButtonsTransform).GetComponentsInChildren<Button>()
				select ((Component)b).gameObject;
			IEnumerable<float> enumerable = from t in source.Where((GameObject b) => (Object)(object)b != (Object)(object)clonedButton).Select(delegate(GameObject b)
				{
					Transform transform = b.transform;
					return (RectTransform)(object)((transform is RectTransform) ? transform : null);
				})
				select t.anchoredPosition.y;
			float num = enumerable.Zip(enumerable.Skip(1), (float y1, float y2) => Mathf.Abs(y2 - y1)).Min();
			foreach (GameObject item in source.Where((GameObject g) => (Object)(object)g != (Object)(object)quitButton))
			{
				RectTransform component = item.GetComponent<RectTransform>();
				component.anchoredPosition += new Vector2(0f, num);
			}
			clonedButton.GetComponent<RectTransform>().anchoredPosition = quitButton.GetComponent<RectTransform>().anchoredPosition + new Vector2(0f, num);
		}
	}
}
namespace LethalConfig.Utils
{
	internal static class AssemblyExtensions
	{
		internal static bool TryGetModInfo(this Assembly assembly, out ModInfo modInfo)
		{
			modInfo = new ModInfo();
			BepInPlugin val = assembly.FindPluginAttribute();
			if (val == null)
			{
				return false;
			}
			modInfo.Name = val.Name;
			modInfo.GUID = val.GUID;
			modInfo.Version = val.Version.ToString();
			return true;
		}

		internal static BepInPlugin FindPluginAttribute(this Assembly assembly)
		{
			Type[] array;
			try
			{
				array = assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				array = ex.Types.Where((Type t) => t != null).ToArray();
			}
			Type[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				BepInPlugin customAttribute = ((MemberInfo)array2[i]).GetCustomAttribute<BepInPlugin>();
				if (customAttribute != null)
				{
					return customAttribute;
				}
			}
			return null;
		}
	}
	internal static class Assets
	{
		private static AssetBundle assetBundle;

		internal static GameObject ConfigMenuManagerPrefab;

		internal static GameObject ConfigMenuNotificationPrefab;

		internal static GameObject ConfigMenuPrefab;

		internal static GameObject ModListItemPrefab;

		internal static GameObject SectionHeaderPrefab;

		internal static GameObject IntSliderPrefab;

		internal static GameObject FloatSliderPrefab;

		internal static GameObject FloatStepSliderPrefab;

		internal static GameObject BoolCheckBoxPrefab;

		internal static GameObject EnumDropDownPrefab;

		internal static GameObject TextInputFieldPrefab;

		internal static GameObject IntInputFieldPrefab;

		internal static GameObject FloatInputFieldPrefab;

		internal static GameObject GenericButtonPrefab;

		internal static Sprite DefaultModIcon;

		internal static Sprite LethalConfigModIcon;

		internal static void Init()
		{
			assetBundle = AssetBundle.LoadFromFile(PathUtils.PathForResourceInAssembly("ainavt_lethalconfig"));
			if ((Object)(object)assetBundle == (Object)null)
			{
				LogUtils.LogError("Failed to load LethalConfig bundle.");
				return;
			}
			LoadAsset<GameObject>("prefabs/ConfigMenuManager.prefab", out ConfigMenuManagerPrefab);
			LoadAsset<GameObject>("prefabs/ConfigMenuNotification.prefab", out ConfigMenuNotificationPrefab);
			LoadAsset<GameObject>("prefabs/ConfigMenu.prefab", out ConfigMenuPrefab);
			LoadAsset<GameObject>("prefabs/ModListItem.prefab", out ModListItemPrefab);
			LoadAsset<GameObject>("prefabs/components/SectionHeader.prefab", out SectionHeaderPrefab);
			LoadAsset<GameObject>("prefabs/components/IntSliderItem.prefab", out IntSliderPrefab);
			LoadAsset<GameObject>("prefabs/components/FloatSliderItem.prefab", out FloatSliderPrefab);
			LoadAsset<GameObject>("prefabs/components/FloatStepSliderItem.prefab", out FloatStepSliderPrefab);
			LoadAsset<GameObject>("prefabs/components/BoolCheckBoxItem.prefab", out BoolCheckBoxPrefab);
			LoadAsset<GameObject>("prefabs/components/EnumDropDownItem.prefab", out EnumDropDownPrefab);
			LoadAsset<GameObject>("prefabs/components/TextInputFieldItem.prefab", out TextInputFieldPrefab);
			LoadAsset<GameObject>("prefabs/components/IntInputFieldItem.prefab", out IntInputFieldPrefab);
			LoadAsset<GameObject>("prefabs/components/FloatInputFieldItem.prefab", out FloatInputFieldPrefab);
			LoadAsset<GameObject>("prefabs/components/GenericButtonItem.prefab", out GenericButtonPrefab);
			LoadAsset<Sprite>("sprite/unknown-icon.png", out DefaultModIcon);
			LoadAsset<Sprite>("icon.png", out LethalConfigModIcon);
			LogUtils.LogInfo("Finished loading assets.");
		}

		private static void LoadAsset<T>(string assetName, out T asset) where T : Object
		{
			string text = "Assets/" + assetName;
			asset = assetBundle.LoadAsset<T>(text);
			if ((Object)(object)asset == (Object)null)
			{
				LogUtils.LogError("Failed to load asset (" + text + ")");
			}
		}
	}
	internal static class LogUtils
	{
		private static Dictionary<Assembly, ManualLogSource> logSources = new Dictionary<Assembly, ManualLogSource>();

		public static void Init(string pluginGuid)
		{
			Assembly callingAssembly = Assembly.GetCallingAssembly();
			if (!logSources.ContainsKey(callingAssembly))
			{
				logSources.Add(callingAssembly, Logger.CreateLogSource(pluginGuid));
			}
		}

		public static void LogInfo(string message)
		{
			logSources[Assembly.GetCallingAssembly()].LogInfo((object)message);
		}

		public static void LogWarning(string message)
		{
			logSources[Assembly.GetCallingAssembly()].LogWarning((object)message);
		}

		public static void LogError(string message)
		{
			logSources[Assembly.GetCallingAssembly()].LogError((object)message);
		}

		public static void LogFatal(string message)
		{
			logSources[Assembly.GetCallingAssembly()].LogFatal((object)message);
		}
	}
	internal static class PathUtils
	{
		public static string PathForResourceInAssembly(string resourceName, Assembly assembly = null)
		{
			return Path.Combine(Path.GetDirectoryName((assembly ?? Assembly.GetCallingAssembly()).Location), resourceName);
		}
	}
}
namespace LethalConfig.Patches
{
	[HarmonyPatch(typeof(MenuManager))]
	internal class MenuManagerPatches
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void StartPostFix(MenuManager __instance)
		{
			((MonoBehaviour)__instance).StartCoroutine(DelayedMainMenuInjection());
		}

		private static IEnumerator DelayedMainMenuInjection()
		{
			yield return (object)new WaitForSeconds(0f);
			InjectToMainMenu();
		}

		private static void InjectToMainMenu()
		{
			LogUtils.LogInfo("Injecting mod config menu into main menu...");
			GameObject val = GameObject.Find("MenuContainer");
			Transform val2 = ((val != null) ? val.transform.Find("MainButtons") : null);
			object obj;
			if (val2 == null)
			{
				obj = null;
			}
			else
			{
				Transform obj2 = val2.Find("QuitButton");
				obj = ((obj2 != null) ? ((Component)obj2).gameObject : null);
			}
			GameObject val3 = (GameObject)obj;
			if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null) && !((Object)(object)val3 == (Object)null))
			{
				MenusUtils.InjectMenu(val.transform, val2, val3);
			}
		}
	}
	[HarmonyPatch(typeof(QuickMenuManager))]
	internal class QuickMenuManagerPatches
	{
		[HarmonyPatch("CloseQuickMenuPanels")]
		[HarmonyPostfix]
		public static void CloseQuickMenuPanelsPostFix(QuickMenuManager __instance)
		{
			ConfigMenu componentInChildren = ((Component)__instance.menuContainer.transform).GetComponentInChildren<ConfigMenu>(true);
			ConfigMenuNotification componentInChildren2 = ((Component)__instance.menuContainer.transform).GetComponentInChildren<ConfigMenuNotification>(true);
			componentInChildren?.Close(animated: false);
			componentInChildren2?.Close(animated: false);
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void StartPostFix(QuickMenuManager __instance)
		{
			LogUtils.LogInfo("Injecting mod config menu into quick menu...");
			GameObject menuContainer = __instance.menuContainer;
			Transform val = ((menuContainer != null) ? menuContainer.transform.Find("MainButtons") : null);
			GameObject val2 = ((val != null) ? ((Component)val.Find("Quit")).gameObject : null);
			if (!((Object)(object)menuContainer == (Object)null) && !((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null))
			{
				MenusUtils.InjectMenu(menuContainer.transform, val, val2);
			}
		}
	}
}
namespace LethalConfig.MonoBehaviours
{
	internal class ConfigInfoBox : MonoBehaviour
	{
		public TextMeshProUGUI configInfoText;

		public void SetConfigInfo(string configInfo)
		{
			((TMP_Text)configInfoText).text = configInfo;
		}
	}
	internal class ConfigList : MonoBehaviour
	{
		public GameObject listContainerObject;

		public DescriptionBox descriptionBox;

		internal void LoadConfigsForMod(Mod mod)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			ClearConfigList();
			foreach (IGrouping<string, BaseConfigItem> item in from c in mod.configItems
				group c by c.Section)
			{
				GameObject obj = Object.Instantiate<GameObject>(Assets.SectionHeaderPrefab);
				obj.GetComponent<SectionHeader>().SetSectionName(item.Key);
				obj.transform.SetParent(listContainerObject.transform);
				obj.transform.localPosition = Vector3.zero;
				obj.transform.localScale = Vector3.one;
				obj.transform.localRotation = Quaternion.identity;
				foreach (BaseConfigItem item2 in item)
				{
					GameObject val = item2.CreateGameObjectForConfig();
					ModConfigController controller = val.GetComponent<ModConfigController>();
					if (!controller.SetConfigItem(item2))
					{
						Object.DestroyImmediate((Object)(object)val.gameObject);
						return;
					}
					val.transform.SetParent(listContainerObject.transform);
					val.transform.localPosition = Vector3.zero;
					val.transform.localScale = Vector3.one;
					val.transform.localRotation = Quaternion.identity;
					controller.OnHoverEnter += delegate
					{
						descriptionBox.ShowConfigInfo(controller.GetDescription());
						ConfigMenuManager.Instance.menuAudio.PlayHoverSFX();
					};
				}
			}
		}

		private void ClearConfigList()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			foreach (Transform item in listContainerObject.transform)
			{
				Object.Destroy((Object)(object)((Component)item).gameObject);
			}
		}
	}
	internal class ConfigMenu : MonoBehaviour
	{
		public ConfigList configList;

		public Animator menuAnimator;

		private void Awake()
		{
			LethalConfigManager.AutoGenerateMissingConfigsIfNeeded();
		}

		public void Open()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			AnimatorStateInfo currentAnimatorStateInfo = menuAnimator.GetCurrentAnimatorStateInfo(0);
			if (!((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("ConfigMenuNormal") && !((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("ConfigMenuAppear"))
			{
				((Component)this).gameObject.SetActive(true);
				menuAnimator.SetTrigger("Open");
				((Component)this).transform.SetAsLastSibling();
			}
		}

		public void Close(bool animated = true)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			AnimatorStateInfo currentAnimatorStateInfo = menuAnimator.GetCurrentAnimatorStateInfo(0);
			if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("ConfigMenuClosed") || ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("ConfigMenuDisappear"))
			{
				return;
			}
			foreach (BaseConfigItem item in LethalConfigManager.Mods.SelectMany((KeyValuePair<string, Mod> m) => m.Value.configItems))
			{
				item.CancelChanges();
			}
			UpdateAppearanceOfCurrentComponents();
			if (!animated)
			{
				((Component)this).gameObject.SetActive(false);
				menuAnimator.SetTrigger("ForceClose");
			}
			else
			{
				menuAnimator.SetTrigger("Close");
			}
		}

		public void OnCloseAnimationEnd()
		{
			((Component)this).gameObject.SetActive(false);
		}

		public void OnCancelButtonClicked()
		{
			Close();
			ConfigMenuManager.Instance.menuAudio.PlayCancelSFX();
		}

		public void OnApplyButtonClicked()
		{
			List<BaseConfigItem> list = (from c in LethalConfigManager.Mods.SelectMany((KeyValuePair<string, Mod> m) => m.Value.configItems)
				where c.HasValueChanged
				select c).ToList();
			List<BaseConfigItem> list2 = list.Where((BaseConfigItem c) => c.RequiresRestart).ToList();
			foreach (BaseConfigItem item in list)
			{
				item.ApplyChanges();
			}
			UpdateAppearanceOfCurrentComponents();
			ConfigMenuManager.Instance.menuAudio.PlayConfirmSFX();
			LogUtils.LogInfo($"Saved config values for {list.Count} items.");
			LogUtils.LogInfo($"Modified {list2.Count} item(s) that requires a restart.");
			if (list2.Count > 0)
			{
				ConfigMenuManager.Instance.DisplayNotification("Some of the modified settings may require a restart to take effect.", "OK");
			}
		}

		private void UpdateAppearanceOfCurrentComponents()
		{
			ModConfigController[] componentsInChildren = ((Component)configList).GetComponentsInChildren<ModConfigController>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].UpdateAppearance();
			}
		}
	}
	internal class ConfigMenuNotification : MonoBehaviour
	{
		public TextMeshProUGUI messageTextComponent;

		public TextMeshProUGUI buttonTextComponent;

		public Animator notificationAnimator;

		public void SetNotificationContent(string text, string button)
		{
			((TMP_Text)messageTextComponent).text = text;
			((TMP_Text)buttonTextComponent).text = "[" + button + "]";
		}

		public void Open()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			AnimatorStateInfo currentAnimatorStateInfo = notificationAnimator.GetCurrentAnimatorStateInfo(0);
			if (!((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("NotificationNormal") && !((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("NotificationAppear"))
			{
				((Component)this).gameObject.SetActive(true);
				notificationAnimator.SetTrigger("Open");
				((Component)this).transform.SetAsLastSibling();
			}
		}

		public void Close(bool animated = true)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			AnimatorStateInfo currentAnimatorStateInfo = notificationAnimator.GetCurrentAnimatorStateInfo(0);
			if (!((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("NotificationClosed") && !((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("NotificationDisappear"))
			{
				if (!animated)
				{
					((Component)this).gameObject.SetActive(false);
					notificationAnimator.SetTrigger("ForceClose");
				}
				else
				{
					notificationAnimator.SetTrigger("Close");
				}
			}
		}

		public void OnButtonClick()
		{
			Close();
			ConfigMenuManager.Instance.menuAudio.PlayConfirmSFX();
		}

		public void OnCloseAnimationEnd()
		{
			((Component)this).gameObject.SetActive(false);
		}
	}
	internal class DescriptionBox : MonoBehaviour
	{
		public ModInfoBox modInfoBox;

		public ConfigInfoBox configInfoBox;

		private void Awake()
		{
			((Component)modInfoBox).gameObject.SetActive(false);
			((Component)configInfoBox).gameObject.SetActive(false);
		}

		public void ShowConfigInfo(string configInfo)
		{
			((Component)configInfoBox).gameObject.SetActive(true);
			configInfoBox.SetConfigInfo(configInfo);
			HideModInfo();
		}

		public void HideConfigInfo()
		{
			((Component)configInfoBox).gameObject.SetActive(false);
		}

		public void ShowModInfo(Mod mod)
		{
			((Component)modInfoBox).gameObject.SetActive(true);
			modInfoBox.SetModInfo(mod);
			HideConfigInfo();
		}

		public void HideModInfo()
		{
			((Component)modInfoBox).gameObject.SetActive(false);
		}
	}
	internal class ModInfoBox : MonoBehaviour
	{
		public Image modIconImage;

		public TextMeshProUGUI modInfoText;

		public void SetModInfo(Mod mod)
		{
			modIconImage.sprite = mod.modInfo.Icon;
			_ = $"{mod.modInfo}";
			((TMP_Text)modInfoText).text = $"{mod.modInfo}";
		}
	}
	internal class ModList : MonoBehaviour
	{
		public GameObject modItemPrefab;

		public GameObject listContainerObject;

		public ConfigList configList;

		public DescriptionBox descriptionBox;

		private List<ModListItem> _items;

		private void Awake()
		{
			_items = new List<ModListItem>();
			BuildModList();
		}

		private void BuildModList()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			_items.Clear();
			foreach (Transform item in listContainerObject.transform)
			{
				Object.Destroy((Object)(object)((Component)item).gameObject);
			}
			foreach (Mod mod in from m in LethalConfigManager.Mods.Values
				orderby m.modInfo.GUID != "ainavt.lc.lethalconfig", m.IsAutoGenerated, m.modInfo.Name
				select m)
			{
				GameObject val = Object.Instantiate<GameObject>(modItemPrefab, listContainerObject.transform);
				val.transform.localScale = Vector3.one;
				val.transform.localPosition = Vector3.zero;
				val.transform.localRotation = Quaternion.identity;
				ModListItem component = val.GetComponent<ModListItem>();
				component.mod = mod;
				component.modSelected += ModSelected;
				component.OnHoverEnter += delegate
				{
					descriptionBox.ShowModInfo(mod);
					ConfigMenuManager.Instance.menuAudio.PlayHoverSFX();
				};
				component.OnHoverExit += delegate
				{
					descriptionBox.HideModInfo();
				};
				_items.Add(val.GetComponent<ModListItem>());
			}
		}

		private void ModSelected(Mod mod)
		{
			ConfigMenuManager.Instance.menuAudio.PlayConfirmSFX();
			configList.LoadConfigsForMod(mod);
			_items.First((ModListItem i) => i.mod == mod).SetSelected(selected: true);
			foreach (ModListItem item in _items.Where((ModListItem i) => i.mod != mod))
			{
				item.SetSelected(selected: false);
			}
		}
	}
	internal class ModListItem : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public delegate void OnHoverHandler();

		internal delegate void ModSelectedHandler(Mod mod);

		public TextMeshProUGUI textMesh;

		public GameObject selectedBorder;

		public Image modIcon;

		private Mod _mod;

		internal Mod mod
		{
			get
			{
				return _mod;
			}
			set
			{
				_mod = value;
				((TMP_Text)textMesh).text = _mod.modInfo.Name;
				modIcon.sprite = _mod.modInfo.Icon;
			}
		}

		public event OnHoverHandler OnHoverEnter;

		public event OnHoverHandler OnHoverExit;

		internal event ModSelectedHandler modSelected;

		public void OnClick()
		{
			this.modSelected(_mod);
		}

		public void SetSelected(bool selected)
		{
			selectedBorder.SetActive(selected);
		}

		public void OnPointerEnter(PointerEventData eventData)
		{
			this.OnHoverEnter?.Invoke();
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			this.OnHoverExit?.Invoke();
		}

		public string GetDescription()
		{
			return _mod.modInfo.Name + "\n" + _mod.modInfo.GUID + "\n" + _mod.modInfo.Version;
		}
	}
	internal class SectionHeader : MonoBehaviour
	{
		public TextMeshProUGUI textMesh;

		public void SetSectionName(string sectionName)
		{
			((TMP_Text)textMesh).text = "[" + sectionName + "]";
		}
	}
	internal class Tooltip : MonoBehaviour
	{
		public TextMeshProUGUI textComponent;

		private RectTransform rectTransform;

		private Camera uiCamera;

		public void SetText(string text)
		{
			((TMP_Text)textComponent).text = text;
		}

		public void SetTarget(GameObject gameObject)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			((Component)this).transform.position = gameObject.transform.position;
		}
	}
	internal class TooltipSystem : MonoBehaviour
	{
		private static TooltipSystem instance;

		public Tooltip tooltip;

		private void Awake()
		{
			instance = this;
		}

		public static void Show(string content, GameObject target)
		{
			if (!((Object)(object)instance == (Object)null))
			{
				((Component)instance.tooltip).gameObject.SetActive(true);
				instance.tooltip.SetText(content);
				instance.tooltip.SetTarget(target);
			}
		}

		public static void Hide()
		{
			if (!((Object)(object)instance == (Object)null))
			{
				((Component)instance.tooltip).gameObject.SetActive(false);
			}
		}
	}
	internal class TooltipTrigger : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public string tooltipText;

		public void OnPointerEnter(PointerEventData eventData)
		{
			TooltipSystem.Show(tooltipText, ((Component)this).gameObject);
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			TooltipSystem.Hide();
		}
	}
	internal class VersionLabel : MonoBehaviour
	{
		private void Start()
		{
			((TMP_Text)((Component)this).GetComponent<TextMeshProUGUI>()).text = "LethalConfig v1.3.4";
		}
	}
}
namespace LethalConfig.MonoBehaviours.Managers
{
	internal class ConfigMenuAudioManager : MonoBehaviour
	{
		public AudioClip confirmSFX;

		public AudioClip cancelSFX;

		public AudioClip selectSFX;

		public AudioClip hoverSFX;

		public AudioClip changeValueSFX;

		public AudioSource audioSource;

		public void PlayConfirmSFX()
		{
			audioSource.PlayOneShot(confirmSFX);
		}

		public void PlayCancelSFX()
		{
			audioSource.PlayOneShot(cancelSFX);
		}

		public void PlayHoverSFX()
		{
			audioSource.PlayOneShot(hoverSFX);
		}

		public void PlaySelectSFX()
		{
			audioSource.PlayOneShot(selectSFX);
		}

		public void PlayChangeValueSFX()
		{
			audioSource.PlayOneShot(changeValueSFX);
		}
	}
	internal class ConfigMenuManager : MonoBehaviour
	{
		public ConfigMenuAudioManager menuAudio;

		public static ConfigMenuManager Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
		}

		private void OnDestroy()
		{
			Instance = null;
		}

		public void ShowConfigMenu()
		{
			Object.FindObjectOfType<ConfigMenu>(true)?.Open();
		}

		public void DisplayNotification(string message, string button)
		{
			ConfigMenuNotification configMenuNotification = Object.FindObjectOfType<ConfigMenuNotification>(true);
			if ((Object)(object)configMenuNotification == (Object)null)
			{
				LogUtils.LogWarning("Notification object not found");
				return;
			}
			configMenuNotification.SetNotificationContent(message, button);
			configMenuNotification.Open();
			EventSystem.current.SetSelectedGameObject(((Component)((Component)configMenuNotification).GetComponentInChildren<Button>()).gameObject);
		}
	}
}
namespace LethalConfig.MonoBehaviours.Components
{
	internal class BoolCheckBoxController : ModConfigController<BoolCheckBoxConfigItem, bool>
	{
		public Toggle toggleComponent;

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			toggleComponent.SetIsOnWithoutNotify(base.ConfigItem.CurrentValue);
		}

		protected override void OnSetConfigItem()
		{
			toggleComponent.SetIsOnWithoutNotify(base.ConfigItem.CurrentValue);
			UpdateAppearance();
		}

		public void OnCheckBoxValueChanged(bool value)
		{
			base.ConfigItem.CurrentValue = value;
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}
	}
	internal class EnumDropDownController : ModConfigController
	{
		public TMP_Dropdown dropdownComponent;

		private Type _enumType;

		private List<string> _enumNames = new List<string>();

		public override string GetDescription()
		{
			return base.GetDescription() + "\n\nDefault: " + Enum.GetName(_enumType, baseConfigItem.BoxedDefaultValue);
		}

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			int valueWithoutNotify = _enumNames.FindIndex((string e) => e == Enum.GetName(_enumType, baseConfigItem.CurrentBoxedValue));
			dropdownComponent.SetValueWithoutNotify(valueWithoutNotify);
		}

		protected override void OnSetConfigItem()
		{
			_enumType = baseConfigItem.BaseConfigEntry.SettingType;
			_enumNames = Enum.GetNames(_enumType).ToList();
			dropdownComponent.ClearOptions();
			dropdownComponent.AddOptions(_enumNames);
			int valueWithoutNotify = _enumNames.FindIndex((string e) => e == Enum.GetName(_enumType, baseConfigItem.CurrentBoxedValue));
			dropdownComponent.SetValueWithoutNotify(valueWithoutNotify);
			UpdateAppearance();
		}

		public void OnDropDownValueChanged(int index)
		{
			baseConfigItem.CurrentBoxedValue = Enum.Parse(_enumType, _enumNames[index]);
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}
	}
	internal class FloatInputFieldController : ModConfigController<FloatInputFieldConfigItem, float>
	{
		public TMP_InputField textInputField;

		public override string GetDescription()
		{
			string text = base.GetDescription();
			if (base.ConfigItem.MinValue != float.MinValue)
			{
				text += $"\nMin: {base.ConfigItem.MinValue:0.0#}";
			}
			if (base.ConfigItem.MaxValue != float.MaxValue)
			{
				text += $"\nMax: {base.ConfigItem.MaxValue:0.0#}";
			}
			return text;
		}

		protected override void OnSetConfigItem()
		{
			textInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue}");
			UpdateAppearance();
		}

		public void OnInputFieldEndEdit(string value)
		{
			if (float.TryParse(value, out var result))
			{
				base.ConfigItem.CurrentValue = Math.Clamp(result, base.ConfigItem.MinValue, base.ConfigItem.MaxValue);
			}
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}

		public override void UpdateAppearance()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			base.UpdateAppearance();
			textInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue}");
			((Transform)textInputField.textComponent.rectTransform).localPosition = Vector3.zero;
		}
	}
	internal class FloatSliderController : ModConfigController<FloatSliderConfigItem, float>
	{
		public Slider sliderComponent;

		public TMP_InputField valueInputField;

		public override string GetDescription()
		{
			return $"{base.GetDescription()}\nMin: {base.ConfigItem.MinValue:0.0#}\nMax: {base.ConfigItem.MaxValue:0.0#}";
		}

		protected override void OnSetConfigItem()
		{
			sliderComponent.SetValueWithoutNotify(base.ConfigItem.CurrentValue);
			sliderComponent.maxValue = base.ConfigItem.MaxValue;
			sliderComponent.minValue = base.ConfigItem.MinValue;
			UpdateAppearance();
		}

		public void OnSliderValueChanged(float value)
		{
			base.ConfigItem.CurrentValue = value;
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}

		public void OnInputFieldEndEdit(string value)
		{
			if (float.TryParse(value, out var result))
			{
				base.ConfigItem.CurrentValue = Math.Clamp(result, base.ConfigItem.MinValue, base.ConfigItem.MaxValue);
			}
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			sliderComponent.SetValueWithoutNotify(base.ConfigItem.CurrentValue);
			valueInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue:0.0#}");
		}
	}
	internal class FloatStepSliderController : ModConfigController<FloatStepSliderConfigItem, float>
	{
		public Slider sliderComponent;

		public TMP_InputField valueInputField;

		public override string GetDescription()
		{
			return $"{base.GetDescription()}\nMin: {base.ConfigItem.MinValue:0.0#}\nMax: {base.ConfigItem.MaxValue:0.0#}";
		}

		protected override void OnSetConfigItem()
		{
			sliderComponent.SetValueWithoutNotify(base.ConfigItem.CurrentValue);
			int num = (int)MathF.Ceiling((base.ConfigItem.MaxValue - base.ConfigItem.MinValue) / MathF.Max(base.ConfigItem.Step, float.Epsilon));
			sliderComponent.maxValue = num;
			sliderComponent.minValue = 0f;
			sliderComponent.wholeNumbers = true;
			UpdateAppearance();
		}

		public void OnSliderValueChanged(float value)
		{
			base.ConfigItem.CurrentValue = MathF.Round(base.ConfigItem.MinValue + base.ConfigItem.Step * (float)(int)value, 4);
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}

		public void OnInputFieldEndEdit(string value)
		{
			if (float.TryParse(value, out var result))
			{
				base.ConfigItem.CurrentValue = Math.Clamp(result, base.ConfigItem.MinValue, base.ConfigItem.MaxValue);
			}
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			sliderComponent.SetValueWithoutNotify((base.ConfigItem.CurrentValue - base.ConfigItem.MinValue) / MathF.Max(base.ConfigItem.Step, float.Epsilon));
			valueInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue:0.0#}");
		}
	}
	internal class GenericButtonController : ModConfigController
	{
		public TextMeshProUGUI buttonTextComponent;

		private GenericButtonConfigItem ConfigItem => baseConfigItem as GenericButtonConfigItem;

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			((TMP_Text)buttonTextComponent).text = ConfigItem?.ButtonOptions?.ButtonText ?? "Button";
		}

		protected override void OnSetConfigItem()
		{
			UpdateAppearance();
		}

		public void OnButtonClicked()
		{
			ConfigMenuManager.Instance.menuAudio.PlayConfirmSFX();
			ConfigItem?.ButtonOptions?.ButtonHandler?.Invoke();
		}
	}
	internal class IntInputFieldController : ModConfigController<IntInputFieldConfigItem, int>
	{
		public TMP_InputField textInputField;

		public override string GetDescription()
		{
			string text = base.GetDescription();
			if (base.ConfigItem.MinValue != int.MinValue)
			{
				text += $"\nMin: {base.ConfigItem.MinValue}";
			}
			if (base.ConfigItem.MaxValue != int.MaxValue)
			{
				text += $"\nMax: {base.ConfigItem.MaxValue}";
			}
			return text;
		}

		protected override void OnSetConfigItem()
		{
			textInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue}");
			UpdateAppearance();
		}

		public void OnInputFieldEndEdit(string value)
		{
			if (int.TryParse(value, out var result))
			{
				base.ConfigItem.CurrentValue = Math.Clamp(result, base.ConfigItem.MinValue, base.ConfigItem.MaxValue);
			}
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}

		public override void UpdateAppearance()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			base.UpdateAppearance();
			textInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue}");
			((Transform)textInputField.textComponent.rectTransform).localPosition = Vector3.zero;
		}
	}
	internal class IntSliderController : ModConfigController<IntSliderConfigItem, int>
	{
		public Slider sliderComponent;

		public TMP_InputField valueInputField;

		public override string GetDescription()
		{
			return $"{base.GetDescription()}\nMin: {base.ConfigItem.MinValue}\nMax: {base.ConfigItem.MaxValue}";
		}

		protected override void OnSetConfigItem()
		{
			sliderComponent.SetValueWithoutNotify((float)base.ConfigItem.CurrentValue);
			sliderComponent.maxValue = base.ConfigItem.MaxValue;
			sliderComponent.minValue = base.ConfigItem.MinValue;
			UpdateAppearance();
		}

		public void OnSliderValueChanged(float value)
		{
			base.ConfigItem.CurrentValue = (int)value;
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}

		public void OnInputFieldEndEdit(string value)
		{
			if (int.TryParse(value, out var result))
			{
				base.ConfigItem.CurrentValue = Math.Clamp(result, base.ConfigItem.MinValue, base.ConfigItem.MaxValue);
			}
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}

		public override void UpdateAppearance()
		{
			base.UpdateAppearance();
			sliderComponent.SetValueWithoutNotify((float)base.ConfigItem.CurrentValue);
			valueInputField.SetTextWithoutNotify($"{base.ConfigItem.CurrentValue}");
		}
	}
	internal abstract class ModConfigController : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
	{
		public delegate void OnHoverHandler();

		private readonly List<Selectable> _selectables = new List<Selectable>();

		protected BaseConfigItem baseConfigItem;

		protected bool isOnSetup;

		public TextMeshProUGUI nameTextComponent;

		public TooltipTrigger tooltipTrigger;

		protected CanModifyResult CanModify
		{
			get
			{
				if (baseConfigItem.Options.CanModifyCallback == null)
				{
					return true;
				}
				return baseConfigItem.Options.CanModifyCallback();
			}
		}

		public event OnHoverHandler OnHoverEnter;

		public event OnHoverHandler OnHoverExit;

		protected virtual void Awake()
		{
			((Behaviour)tooltipTrigger).enabled = false;
			if (_selectables.Count <= 0)
			{
				_selectables.AddRange(((Component)this).GetComponentsInChildren<Selectable>());
			}
		}

		public virtual bool SetConfigItem(BaseConfigItem configItem)
		{
			baseConfigItem = configItem;
			isOnSetup = true;
			OnSetConfigItem();
			isOnSetup = false;
			if (baseConfigItem.Options.CanModifyCallback != null)
			{
				tooltipTrigger.tooltipText = "<b>Modifying this entry is currently disabled:</b>\n<b>" + CanModify.Reason + "</b>";
			}
			return true;
		}

		protected abstract void OnSetConfigItem();

		public virtual void UpdateAppearance()
		{
			((TMP_Text)nameTextComponent).text = (baseConfigItem.HasValueChanged ? "* " : "") + baseConfigItem.Name;
			CanModifyResult canModify = CanModify;
			foreach (Selectable selectable in _selectables)
			{
				selectable.interactable = canModify;
			}
			((Behaviour)tooltipTrigger).enabled = !canModify;
		}

		public virtual void ResetToDefault()
		{
			ConfigMenuManager.Instance.menuAudio.PlayConfirmSFX();
			baseConfigItem.ChangeToDefault();
			UpdateAppearance();
		}

		public virtual string GetDescription()
		{
			string text = "<b>" + baseConfigItem.Name + "</b>";
			if (baseConfigItem.IsAutoGenerated)
			{
				text += "\n\n<b>*This config entry was automatically generated and may require a restart*</b>";
			}
			else if (baseConfigItem.RequiresRestart)
			{
				text += "\n\n<b>*REQUIRES RESTART*</b>";
			}
			return text + "\n\n" + baseConfigItem.Description;
		}

		public void OnPointerEnter(PointerEventData eventData)
		{
			this.OnHoverEnter?.Invoke();
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			this.OnHoverExit?.Invoke();
		}
	}
	internal abstract class ModConfigController<T, V> : ModConfigController where T : BaseValueConfigItem<V>
	{
		public T ConfigItem => (T)baseConfigItem;

		public override string GetDescription()
		{
			return $"{base.GetDescription()}\n\nDefault: {ConfigItem.Defaultvalue}";
		}

		public override bool SetConfigItem(BaseConfigItem configItem)
		{
			if (!(configItem is T))
			{
				LogUtils.LogError("Expected config item of type " + typeof(T).Name + ", but got " + configItem.GetType().Name + " instead.");
				return false;
			}
			return base.SetConfigItem(configItem);
		}
	}
	internal class TextInputFieldController : ModConfigController<TextInputFieldConfigItem, string>
	{
		public TMP_InputField textInputField;

		protected override void OnSetConfigItem()
		{
			textInputField.SetTextWithoutNotify(base.ConfigItem.CurrentValue);
			UpdateAppearance();
		}

		public void OnInputFieldEndEdit(string value)
		{
			base.ConfigItem.CurrentValue = value;
			UpdateAppearance();
			ConfigMenuManager.Instance.menuAudio.PlayChangeValueSFX();
		}

		public override void UpdateAppearance()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			base.UpdateAppearance();
			textInputField.SetTextWithoutNotify(base.ConfigItem.CurrentValue);
			((Transform)textInputField.textComponent.rectTransform).localPosition = Vector3.zero;
		}
	}
}
namespace LethalConfig.Mods
{
	internal class Mod
	{
		public ModInfo modInfo;

		public bool IsAutoGenerated;

		public List<BaseConfigItem> configItems;

		public List<ConfigEntryPath> entriesToSkipAutoGen;

		internal Mod(ModInfo modInfo)
		{
			configItems = new List<BaseConfigItem>();
			entriesToSkipAutoGen = new List<ConfigEntryPath>();
			this.modInfo = modInfo;
			TryResolveIconAndDesc();
		}

		internal void TryResolveIconAndDesc()
		{
			if (modInfo.TryGetPluginInfo(out var pluginInfo))
			{
				string text = Path.GetFullPath(pluginInfo.Location);
				DirectoryInfo parent = Directory.GetParent(text);
				while (parent != null && !string.Equals(parent.Name, "plugins", StringComparison.OrdinalIgnoreCase))
				{
					text = parent.FullName;
					parent = Directory.GetParent(text);
				}
				if (!text.EndsWith(".dll"))
				{
					string iconPath = Directory.EnumerateFiles(text, "icon.png", SearchOption.AllDirectories).FirstOrDefault();
					LoadIcon(iconPath);
					string manifestPath = Directory.EnumerateFiles(text, "manifest.json", SearchOption.AllDirectories).FirstOrDefault();
					LoadDesc(manifestPath);
				}
			}
		}

		private void LoadIcon(string iconPath)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_0044: 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)
			try
			{
				if (iconPath != null)
				{
					Texture2D val = new Texture2D(256, 256);
					if (ImageConversion.LoadImage(val, File.ReadAllBytes(iconPath)))
					{
						modInfo.Icon = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
					}
				}
			}
			catch
			{
			}
		}

		private void LoadDesc(string manifestPath)
		{
			try
			{
				if (manifestPath != null)
				{
					ThunderstoreManifest thunderstoreManifest = JsonConvert.DeserializeObject<ThunderstoreManifest>(File.ReadAllText(manifestPath));
					if (thunderstoreManifest != null)
					{
						modInfo.Description = thunderstoreManifest.Description;
					}
				}
			}
			catch
			{
			}
		}

		internal void AddConfigItem(BaseConfigItem item)
		{
			configItems.Add(item);
		}
	}
	internal class ModInfo
	{
		internal string Name { get; set; }

		internal string GUID { get; set; }

		internal string Version { get; set; }

		internal string Description { get; set; } = "";


		internal Sprite Icon { get; set; } = Assets.DefaultModIcon;


		public override string ToString()
		{
			return "<b>" + Name + "</b>\n" + GUID + "\nv" + Version + "\n\n" + Description;
		}

		public bool TryGetPluginInfo(out PluginInfo pluginInfo)
		{
			return Chainloader.PluginInfos.TryGetValue(GUID, out pluginInfo);
		}
	}
	internal class ThunderstoreManifest
	{
		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("version_number")]
		public string VersionNumber { get; set; }

		[JsonProperty("website_url")]
		public string WebsiteURL { get; set; }

		[JsonProperty("description")]
		public string Description { get; set; }

		[JsonProperty("dependencies")]
		public IList<string> Dependencies { get; set; }
	}
}
namespace LethalConfig.ConfigItems
{
	public abstract class BaseConfigItem
	{
		internal ConfigEntryBase BaseConfigEntry { get; private set; }

		internal BaseOptions Options { get; }

		internal bool RequiresRestart => Options.RequiresRestart;

		internal Mod Owner { get; set; }

		internal bool IsAutoGenerated { get; set; }

		private string UnderlyingSection
		{
			get
			{
				ConfigEntryBase baseConfigEntry = BaseConfigEntry;
				return ((baseConfigEntry != null) ? baseConfigEntry.Definition.Section : null) ?? string.Empty;
			}
		}

		private string UnderlyingName
		{
			get
			{
				ConfigEntryBase baseConfigEntry = BaseConfigEntry;
				return ((baseConfigEntry != null) ? baseConfigEntry.Definition.Key : null) ?? string.Empty;
			}
		}

		private string UnderlyingDescription
		{
			get
			{
				ConfigEntryBase baseConfigEntry = BaseConfigEntry;
				return ((baseConfigEntry != null) ? baseConfigEntry.Description.Description : null) ?? string.Empty;
			}
		}

		internal string Section => Options.Section ?? UnderlyingSection;

		internal string Name => Options.Name ?? UnderlyingName;

		internal string Description => Options.Description ?? UnderlyingDescription;

		internal object CurrentBoxedValue { get; set; }

		internal object OriginalBoxedValue
		{
			get
			{
				ConfigEntryBase baseConfigEntry = BaseConfigEntry;
				if (baseConfigEntry == null)
				{
					return null;
				}
				return baseConfigEntry.BoxedValue;
			}
		}

		internal object BoxedDefaultValue
		{
			get
			{
				ConfigEntryBase baseConfigEntry = BaseConfigEntry;
				if (baseConfigEntry == null)
				{
					return null;
				}
				return baseConfigEntry.DefaultValue;
			}
		}

		internal bool HasValueChanged
		{
			get
			{
				object currentBoxedValue = CurrentBoxedValue;
				if (currentBoxedValue == null)
				{
					return false;
				}
				return !currentBoxedValue.Equals(OriginalBoxedValue);
			}
		}

		internal abstract GameObject CreateGameObjectForConfig();

		internal void ApplyChanges()
		{
			if (BaseConfigEntry != null)
			{
				BaseConfigEntry.BoxedValue = CurrentBoxedValue;
			}
		}

		internal void CancelChanges()
		{
			CurrentBoxedValue = OriginalBoxedValue;
		}

		internal void ChangeToDefault()
		{
			CurrentBoxedValue = BoxedDefaultValue;
		}

		internal BaseConfigItem(BaseOptions options)
			: this(null, options)
		{
		}

		internal BaseConfigItem(ConfigEntryBase configEntry, BaseOptions options)
		{
			BaseConfigEntry = configEntry;
			Options = options;
			CurrentBoxedValue = OriginalBoxedValue;
		}

		internal bool IsSameConfig(BaseConfigItem configItem)
		{
			bool num = configItem.UnderlyingSection == UnderlyingSection;
			bool flag = configItem.UnderlyingName == UnderlyingName;
			bool flag2 = configItem.Owner.modInfo.GUID == Owner.modInfo.GUID;
			return num && flag && flag2;
		}
	}
	public abstract class BaseValueConfigItem<T> : BaseConfigItem
	{
		internal ConfigEntry<T> ConfigEntry => (ConfigEntry<T>)(object)base.BaseConfigEntry;

		internal T CurrentValue
		{
			get
			{
				return (T)base.CurrentBoxedValue;
			}
			set
			{
				base.CurrentBoxedValue = value;
			}
		}

		internal T OriginalValue => ConfigEntry.Value;

		internal T Defaultvalue => (T)((ConfigEntryBase)ConfigEntry).DefaultValue;

		internal BaseValueConfigItem(ConfigEntry<T> configEntry, BaseOptions options)
			: base((ConfigEntryBase)(object)configEntry, options)
		{
			CurrentValue = OriginalValue;
		}

		public override string ToString()
		{
			return base.Owner.modInfo.Name + "/" + ((ConfigEntryBase)ConfigEntry).Definition.Section + "/" + ((ConfigEntryBase)ConfigEntry).Definition.Key;
		}
	}
	public class BoolCheckBoxConfigItem : BaseValueConfigItem<bool>
	{
		public BoolCheckBoxConfigItem(ConfigEntry<bool> configEntry)
			: this(configEntry, requiresRestart: true)
		{
		}

		public BoolCheckBoxConfigItem(ConfigEntry<bool> configEntry, bool requiresRestart)
			: this(configEntry, new BoolCheckBoxOptions
			{
				RequiresRestart = requiresRestart
			})
		{
		}

		public BoolCheckBoxConfigItem(ConfigEntry<bool> configEntry, BoolCheckBoxOptions options)
			: base(configEntry, (BaseOptions)options)
		{
		}

		internal override GameObject CreateGameObjectForConfig()
		{
			return Object.Instantiate<GameObject>(Assets.BoolCheckBoxPrefab);
		}
	}
	public class EnumDropDownConfigItem<T> : BaseValueConfigItem<T> where T : Enum
	{
		public EnumDropDownConfigItem(ConfigEntry<T> configEntry)
			: this(configEntry, requiresRestart: true)
		{
		}

		public EnumDropDownConfigItem(ConfigEntry<T> configEntry, bool requiresRestart)
			: this(configEntry, new EnumDropDownOptions
			{
				RequiresRestart = requiresRestart
			})
		{
		}

		public EnumDropDownConfigItem(ConfigEntry<T> configEntry, EnumDropDownOptions options)
			: base(configEntry, (BaseOptions)options)
		{
		}

		internal override GameObject CreateGameObjectForConfig()
		{
			return Object.Instantiate<GameObject>(Assets.EnumDropDownPrefab);
		}
	}
	public sealed class FloatInputFieldConfigItem : BaseValueConfigItem<float>
	{
		internal float MaxValue { get; private set; }

		internal float MinValue { get; private set; }

		public FloatInputFieldConfigItem(ConfigEntry<float> configEntry)
			: this(configEntry, requiresRestart: true)
		{
		}

		public FloatInputFieldConfigItem(ConfigEntry<float> configEntry, bool requiresRestart)
			: this(configEntry, GetDefaultOptions(configEntry, requiresRestart))
		{
		}

		public FloatInputFieldConfigItem(ConfigEntry<float> configEntry, FloatInputFieldOptions options)
			: base(configEntry, (BaseOptions)options)
		{
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)configEntry).Description.AcceptableValues;
			MinValue = (options.IsMinSet ? options.Min : ((acceptableValues as AcceptableValueRange<float>)?.MinValue ?? 0f));
			MaxValue = (options.IsMaxSet ? options.Max : ((acceptableValues as AcceptableValueRange<float>)?.MaxValue ?? 1f));
		}

		internal override GameObject CreateGameObjectForConfig()
		{
			return Object.Instantiate<GameObject>(Assets.FloatInputFieldPrefab);
		}

		private static FloatInputFieldOptions GetDefaultOptions(ConfigEntry<float> configEntry, bool requiresRestart = true)
		{
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)configEntry).Description.AcceptableValues;
			return new FloatInputFieldOptions
			{
				Min = ((acceptableValues as AcceptableValueRange<float>)?.MinValue ?? float.MinValue),
				Max = ((acceptableValues as AcceptableValueRange<float>)?.MaxValue ?? float.MaxValue),
				RequiresRestart = requiresRestart
			};
		}
	}
	public sealed class FloatSliderConfigItem : BaseValueConfigItem<float>
	{
		internal float MaxValue { get; private set; }

		internal float MinValue { get; private set; }

		public FloatSliderConfigItem(ConfigEntry<float> configEntry)
			: this(configEntry, requiresRestart: true)
		{
		}

		public FloatSliderConfigItem(ConfigEntry<float> configEntry, bool requiresRestart)
			: this(configEntry, GetDefaultOptions(configEntry, requiresRestart))
		{
		}

		public FloatSliderConfigItem(ConfigEntry<float> configEntry, FloatSliderOptions options)
			: base(configEntry, (BaseOptions)options)
		{
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)configEntry).Description.AcceptableValues;
			MinValue = (options.IsMinSet ? options.Min : ((acceptableValues as AcceptableValueRange<float>)?.MinValue ?? 0f));
			MaxValue = (options.IsMaxSet ? options.Max : ((acceptableValues as AcceptableValueRange<float>)?.MaxValue ?? 1f));
		}

		internal override GameObject CreateGameObjectForConfig()
		{
			return Object.Instantiate<GameObject>(Assets.FloatSliderPrefab);
		}

		private static FloatSliderOptions GetDefaultOptions(ConfigEntry<float> configEntry, bool requiresRestart = true)
		{
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)configEntry).Description.AcceptableValues;
			return new FloatSliderOptions
			{
				Min = ((acceptableValues as AcceptableValueRange<float>)?.MinValue ?? 0f),
				Max = ((acceptableValues as AcceptableValueRange<float>)?.MaxValue ?? 1f),
				RequiresRestart = requiresRestart
			};
		}
	}
	public sealed class FloatStepSliderConfigItem : BaseValueConfigItem<float>
	{
		internal float MaxValue { get; private set; }

		internal float MinValue { get; private set; }

		internal float Step { get; private set; }

		public FloatStepSliderConfigItem(ConfigEntry<float> configEntry)
			: this(configEntry, requiresRestart: true)
		{
		}

		public FloatStepSliderConfigItem(ConfigEntry<float> configEntry, bool requiresRestart)
			: this(configEntry, GetDefaultOptions(configEntry, requiresRestart))
		{
		}

		public FloatStepSliderConfigItem(ConfigEntry<float> configEntry, FloatStepSliderOptions options)
			: base(configEntry, (BaseOptions)options)
		{
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)configEntry).Description.AcceptableValues;
			MinValue = (options.IsMinSet ? options.Min : ((acceptableValues as AcceptableValueRange<float>)?.MinValue ?? 0f));
			MaxValue = (options.IsMaxSet ? options.Max : ((acceptableValues as AcceptableValueRange<float>)?.MaxValue ?? 1f));
			Step = options.Step;
		}

		internal override GameObject CreateGameObjectForConfig()
		{
			return Object.Instantiate<GameObject>(Assets.FloatStepSliderPrefab);
		}

		private static FloatStepSliderOptions GetDefaultOptions(ConfigEntry<float> configEntry, bool requiresRestart = true)
		{
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)configEntry).Description.AcceptableValues;
			return new FloatStepSliderOptions
			{
				Min = ((acceptableValues as AcceptableValueRange<float>)?.MinValue ?? 0f),
				Max = ((acceptableValues as AcceptableValueRange<float>)?.MaxValue ?? 1f),
				Step = 0.1f,
				RequiresRestart = requiresRestart
			};
		}
	}
	public class GenericButtonConfigItem : BaseConfigItem
	{
		public GenericButtonOptions ButtonOptions => base.Options as GenericButtonOptions;

		public GenericButtonConfigItem(string section, string name, string description, string buttonText, GenericButtonOptions.GenericButtonHandler buttonHandler)
			: base(new GenericButtonOptions
			{
				Section = section,
				Name = name,
				Description = description,
				ButtonText = buttonText,
				ButtonHandler = buttonHandler,
				RequiresRestart = false
			})
		{
		}

		internal override GameObject CreateGameObjectForConfig()
		{
			return Object.Instantiate<GameObject>(Assets.GenericButtonPrefab);
		}
	}
	public sealed class IntInputFieldConfigItem : BaseValueConfigItem<int>
	{
		internal int MaxValue { get; private set; }

		internal int MinValue { get; private set; }

		public IntInputFieldConfigItem(ConfigEntry<int> configEntry)
			: this(configEntry, requiresRestart: true)
		{
		}

		public IntInputFieldConfigItem(ConfigEntry<int> configEntry, bool requiresRestart)
			: this(configEntry, GetDefaultOptions(configEntry, requiresRestart))
		{
		}

		public IntInputFieldConfigItem(ConfigEntry<int> configEntry, IntInputFieldOptions options)
			: base(configEntry, (BaseOptions)options)
		{
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)configEntry).Description.AcceptableValues;
			MinValue = (options.IsMinSet ? options.Min : ((acceptableValues as AcceptableValueRange<int>)?.MinValue ?? 0));
			MaxValue = (options.IsMaxSet ? options.Max : ((acceptableValues as AcceptableValueRange<int>)?.MaxValue ?? 100));
		}

		internal override GameObject CreateGameObjectForConfig()
		{
			return Object.Instantiate<GameObject>(Assets.IntInputFieldPrefab);
		}

		private static IntInputFieldOptions GetDefaultOptions(ConfigEntry<int> configEntry, bool requiresRestart = true)
		{
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)configEntry).Description.AcceptableValues;
			return new IntInputFieldOptions
			{
				Min = ((acceptableValues as AcceptableValueRange<int>)?.MinValue ?? int.MinValue),
				Max = ((acceptableValues as AcceptableValueRange<int>)?.MaxValue ?? int.MaxValue),
				RequiresRestart = requiresRestart
			};
		}
	}
	public sealed class IntSliderConfigItem : BaseValueConfigItem<int>
	{
		internal int MaxValue { get; private set; }

		internal int MinValue { get; private set; }

		public IntSliderConfigItem(ConfigEntry<int> configEntry)
			: this(configEntry, requiresRestart: true)
		{
		}

		public IntSliderConfigItem(ConfigEntry<int> configEntry, bool requiresRestart)
			: this(configEntry, GetDefaultOptions(configEntry, requiresRestart))
		{
		}

		public IntSliderConfigItem(ConfigEntry<int> configEntry, IntSliderOptions options)
			: base(configEntry, (BaseOptions)options)
		{
			AcceptableValueBase acceptableValues = ((ConfigEntryBase)configEntry).Description.AcceptableValues;
			MinValue = (options.IsMinSet ? options.Min : ((acceptableValues as AcceptableValueRange<int>)?.MinValue ?? 0));
			MaxValue = (options.IsMaxSet ? options.Max : ((acceptableValues as AcceptableValueRange<int>)?.MaxValue ?? 100));
		}

		internal override GameObject CreateGameObjectForConfig()
		{
			return Object.Instantiate<GameObject>(A

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/LethalEscape/LethalEscape.dll

Decompiled 7 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("LethalEscape")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("A template for Lethal Company")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LethalEscape")]
[assembly: AssemblyTitle("LethalEscape")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalEscape
{
	internal class LETimerFunctions : MonoBehaviour
	{
		public static float MinuteEscapeTimerPuffer;

		public static float MinuteEscapeTimerBracken;

		public static float MinuteEscapeTimerHoardingBug;

		public static LETimerFunctions instance;

		private void Awake()
		{
			instance = this;
		}

		private void Update()
		{
			MinuteEscapeTimerBracken += Time.deltaTime;
			MinuteEscapeTimerHoardingBug += Time.deltaTime;
			MinuteEscapeTimerPuffer += Time.deltaTime;
		}
	}
	[BepInPlugin("xCeezy.LethalEscape", "Lethal Escape", "0.8.2")]
	public class Plugin : BaseUnityPlugin
	{
		public static GameObject ExtraValues;

		private const string modGUID = "xCeezy.LethalEscape";

		private const string modName = "Lethal Escape";

		private const string modVersion = "0.8.2";

		private Harmony _harmony = new Harmony("LethalEscape");

		public static ManualLogSource mls;

		public static float TimeStartTeleport;

		public static ConfigEntry<bool> CanThumperEscape;

		public static ConfigEntry<bool> CanBrackenEscape;

		public static ConfigEntry<bool> CanJesterEscape;

		public static ConfigEntry<bool> CanHoardingBugEscape;

		public static ConfigEntry<bool> CanCoilHeadEscape;

		public static ConfigEntry<bool> CanSpiderEscape;

		public static ConfigEntry<bool> CanNutCrackerEscape;

		public static ConfigEntry<bool> CanHygrodereEscape;

		public static ConfigEntry<bool> CanPufferEscape;

		public static float JesterSpeedWindup;

		public static ConfigEntry<float> BrackenChanceToEscapeEveryMinute;

		public static ConfigEntry<float> PufferChanceToEscapeEveryMinute;

		public static ConfigEntry<float> HoardingBugChanceToEscapeEveryMinute;

		public static ConfigEntry<float> HoardingBugChanceToNestNearShip;

		public static ConfigEntry<float> HoardingBugChanceToSpawnOutside;

		public static ConfigEntry<float> BrackenChanceToSpawnOutside;

		public static ConfigEntry<float> PufferChanceToSpawnOutside;

		public static ConfigEntry<float> JesterChanceToSpawnOutside;

		public static ConfigEntry<float> HygrodereChanceToSpawnOutside;

		public static ConfigEntry<float> NutCrackerChanceToSpawnOutside;

		public static ConfigEntry<float> ThumperChanceToSpawnOutside;

		public static ConfigEntry<float> SpiderChanceToSpawnOutside;

		public static ConfigEntry<float> JesterSpeedIncreasePerSecond;

		public static ConfigEntry<float> MaxJesterOutsideSpeed;

		public static ConfigEntry<float> BrackenEscapeDelay;

		public static ConfigEntry<float> ThumperEscapeDelay;

		public static ConfigEntry<int> SpiderMinWebsOutside;

		public static ConfigEntry<int> SpiderMaxWebsOutside;

		private void Awake()
		{
			//IL_03b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bd: Expected O, but got Unknown
			CanThumperEscape = ((BaseUnityPlugin)this).Config.Bind<bool>("Can Monster Escape", "ThumperEscape", true, "Whether or not the Thumper can escape");
			CanBrackenEscape = ((BaseUnityPlugin)this).Config.Bind<bool>("Can Monster Escape", "BrackenEscape", true, "Whether or not the Bracken can escape");
			CanJesterEscape = ((BaseUnityPlugin)this).Config.Bind<bool>("Can Monster Escape", "JesterEscape", true, "Whether or not the Jester can escape");
			CanHoardingBugEscape = ((BaseUnityPlugin)this).Config.Bind<bool>("Can Monster Escape", "HoardingBugEscape", true, "Whether or not the Hoarding Bugs can escape");
			CanCoilHeadEscape = ((BaseUnityPlugin)this).Config.Bind<bool>("Can Monster Escape", "CoilHeadEscape", true, "Whether or not Coil Head can escape");
			CanSpiderEscape = ((BaseUnityPlugin)this).Config.Bind<bool>("Can Monster Escape", "SpiderEscape", true, "Whether or not the Spider can escape");
			CanNutCrackerEscape = ((BaseUnityPlugin)this).Config.Bind<bool>("Can Monster Escape", "NutCrackerEscape", true, "Whether or not the Nut Cracker can escape");
			CanHygrodereEscape = ((BaseUnityPlugin)this).Config.Bind<bool>("Can Monster Escape", "HygrodereEscape", false, "Whether or not the Hygrodere/Slime can escape");
			CanPufferEscape = ((BaseUnityPlugin)this).Config.Bind<bool>("Can Monster Escape", "CanPufferEscape", true, "Whether or not the Puffer/Spore Lizard can escape");
			ThumperChanceToSpawnOutside = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Escape Settings", "ThumperSpawnOutsideChance", 5f, "The chance that the Thumper will spawn outside");
			BrackenChanceToSpawnOutside = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Escape Settings", "BrackenSpawnOutsideChance", 10f, "The chance that the Bracken will spawn outside");
			JesterChanceToSpawnOutside = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Escape Settings", "JesterSpawnOutsideChance", 0f, "The chance that the Jester will spawn outside");
			HoardingBugChanceToSpawnOutside = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Escape Settings", "HoardingBugSpawnOutsideChance", 30f, "The chance that the Hoarding Bug will spawn outside");
			SpiderChanceToSpawnOutside = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Escape Settings", "SpiderSpawnOutsideChance", 5f, "The chance that the Spider will spawn outside");
			NutCrackerChanceToSpawnOutside = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Escape Settings", "NutCrackerSpawnOutsideChance", 5f, "The chance that the NutCracker will spawn outside");
			HygrodereChanceToSpawnOutside = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Escape Settings", "HygrodereSpawnOutsideChance", 0f, "The chance that the Hygrodere will spawn outside");
			PufferChanceToSpawnOutside = ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Escape Settings", "PufferSpawnOutsideChance", 5f, "The chance that the Puffer will spawn outside");
			PufferChanceToEscapeEveryMinute = ((BaseUnityPlugin)this).Config.Bind<float>("Escape Settings", "Puffer Escape Chance", 10f, "The chance that the Puffer/Spore Lizard will escape randomly every minute");
			BrackenChanceToEscapeEveryMinute = ((BaseUnityPlugin)this).Config.Bind<float>("Escape Settings", "Bracken Escape Chance", 10f, "The chance that the Bracken will escape randomly every minute");
			HoardingBugChanceToEscapeEveryMinute = ((BaseUnityPlugin)this).Config.Bind<float>("Escape Settings", "HoardingBug Escape Chance", 15f, "The chance that the Hoarding Bug will escape randomly every minute");
			HoardingBugChanceToNestNearShip = ((BaseUnityPlugin)this).Config.Bind<float>("Escape Settings", "HoardingBugShipNestChance", 50f, "The chance that the Hoarding Bug will make their nest at/near the ship");
			BrackenEscapeDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Escape Settings", "Bracken Escape Delay", 5f, "Time it takes for the Bracken to follow a player outside");
			ThumperEscapeDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Escape Settings", "Thumper Escape Delay", -5f, "Time it takes for the Thumper to follow a player outside which is based on how long the player was seen minus this value (Might break when under -15 and will force thumper outside when it sees someone when above 0)");
			SpiderMaxWebsOutside = ((BaseUnityPlugin)this).Config.Bind<int>("Escape Settings", "Max Spider Webs Outside", 28, "The maximum amount of spider webs the game will allow the spider to create webs outside (Vanilla game is 7 or 9 if update 47)");
			SpiderMinWebsOutside = ((BaseUnityPlugin)this).Config.Bind<int>("Escape Settings", "Min Spider Webs Outside", 20, "The minimum amount of spider webs the game will allow the spider to create webs outside (Vanilla game is 4 or 6 if update 47)");
			JesterSpeedIncreasePerSecond = ((BaseUnityPlugin)this).Config.Bind<float>("Escape Settings", "Jester Speed Increase", 1.35f, "How much speed the jester gets per second");
			MaxJesterOutsideSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Escape Settings", "Jester Outside Speed", 10f, "The max speed the Jester moves while outside (5 is the speed its at while in the box and 18 is jesters max speed inside the facility)");
			if ((Object)(object)ExtraValues == (Object)null)
			{
				ExtraValues = new GameObject();
				Object.DontDestroyOnLoad((Object)(object)ExtraValues);
				((Object)ExtraValues).hideFlags = (HideFlags)61;
				ExtraValues.AddComponent<LETimerFunctions>();
			}
			mls = Logger.CreateLogSource("GameMaster");
			mls.LogInfo((object)"Loaded xCeezy.LethalEscape. Patching.");
			_harmony.PatchAll(typeof(Plugin));
		}

		[HarmonyPatch(typeof(CrawlerAI), "Update")]
		[HarmonyPrefix]
		private static void CrawlerLEPrefixAI(CrawlerAI __instance)
		{
			if (((EnemyAI)__instance).isEnemyDead || !CanThumperEscape.Value || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				return;
			}
			if (!((EnemyAI)__instance).isOutside)
			{
				if (((EnemyAI)__instance).currentBehaviourStateIndex != 0 && __instance.noticePlayerTimer < ThumperEscapeDelay.Value && (Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null && !((EnemyAI)__instance).targetPlayer.isInsideFactory)
				{
					SendEnemyOutside((EnemyAI)(object)__instance);
				}
			}
			else if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
		}

		[HarmonyPatch(typeof(CrawlerAI), "OnCollideWithPlayer")]
		[HarmonyPostfix]
		public static void ThumperAILEOutsideAttack(CrawlerAI __instance, ref Collider other)
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			if (!((EnemyAI)__instance).isEnemyDead && ((EnemyAI)__instance).isOutside && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component != (Object)null && !component.isPlayerDead && component.isPlayerControlled && (Object)(object)component != (Object)(object)GameNetworkManager.Instance.localPlayerController && !((double)__instance.timeSinceHittingPlayer <= 0.65) && !(((EnemyAI)__instance).stunNormalizedTimer > 0f))
				{
					__instance.timeSinceHittingPlayer = 0f;
					((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
					component.DamagePlayer(40, true, true, (CauseOfDeath)6, 0, false, default(Vector3));
					component.DamagePlayerFromOtherClientServerRpc(40, Vector3.zero, -1);
					((EnemyAI)__instance).agent.speed = 0f;
					__instance.HitPlayerServerRpc((int)component.playerClientId);
					component.JumpToFearLevel(1f, true);
				}
			}
		}

		[HarmonyPatch(typeof(CrawlerAI), "Start")]
		[HarmonyPostfix]
		private static void CrawlerAILEPostfixStart(CrawlerAI __instance)
		{
			if (((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && ThumperChanceToSpawnOutside.Value != 0f && (float)Random.Range(1, 100) <= ThumperChanceToSpawnOutside.Value)
			{
				SendEnemyOutside((EnemyAI)(object)__instance);
			}
		}

		[HarmonyPatch(typeof(JesterAI), "Update")]
		[HarmonyPrefix]
		private static void JesterLEPrefixAI(JesterAI __instance)
		{
			if (((EnemyAI)__instance).isEnemyDead || !CanJesterEscape.Value || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				return;
			}
			if (!((EnemyAI)__instance).isOutside)
			{
				if (((EnemyAI)__instance).currentBehaviourStateIndex == 2 && (Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null && !((EnemyAI)__instance).targetPlayer.isInsideFactory)
				{
					JesterSpeedWindup = 0f;
					SendEnemyOutside((EnemyAI)(object)__instance, SpawnOnDoor: false);
				}
			}
			else if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
		}

		[HarmonyPatch(typeof(JesterAI), "Update")]
		[HarmonyPostfix]
		private static void JesterLEPostfixAI(JesterAI __instance)
		{
			if (!CanJesterEscape.Value || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost || !((EnemyAI)__instance).isOutside)
			{
				return;
			}
			if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
			bool flag = false;
			for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++)
			{
				if (StartOfRound.Instance.allPlayerScripts[i].isPlayerControlled && !StartOfRound.Instance.allPlayerScripts[i].isInsideFactory)
				{
					flag = true;
				}
			}
			if (flag)
			{
				((EnemyAI)__instance).SwitchToBehaviourState(2);
				((EnemyAI)__instance).agent.stoppingDistance = 0f;
			}
			JesterSpeedWindup = Mathf.Clamp(JesterSpeedWindup + Time.deltaTime * JesterSpeedIncreasePerSecond.Value, 0f, MaxJesterOutsideSpeed.Value);
			((EnemyAI)__instance).agent.speed = JesterSpeedWindup;
		}

		[HarmonyPatch(typeof(JesterAI), "OnCollideWithPlayer")]
		[HarmonyPostfix]
		public static void JesterAILEOutsideAttack(JesterAI __instance, ref Collider other)
		{
			if (!((EnemyAI)__instance).isEnemyDead && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && ((EnemyAI)__instance).isOutside)
			{
				if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
				{
					((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
				}
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component != (Object)null && !component.isPlayerDead && component.isPlayerControlled && (Object)(object)component != (Object)(object)GameNetworkManager.Instance.localPlayerController && Object.op_Implicit((Object)(object)((Component)other).gameObject.GetComponent<PlayerControllerB>()) && ((EnemyAI)__instance).currentBehaviourStateIndex == 2)
				{
					__instance.KillPlayerServerRpc((int)component.playerClientId);
				}
			}
		}

		[HarmonyPatch(typeof(JesterAI), "Start")]
		[HarmonyPostfix]
		private static void JesterAILEPostfixStart(JesterAI __instance)
		{
			if (((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && JesterChanceToSpawnOutside.Value != 0f && (float)Random.Range(1, 100) <= JesterChanceToSpawnOutside.Value)
			{
				SendEnemyOutside((EnemyAI)(object)__instance);
			}
		}

		[HarmonyPatch(typeof(FlowermanAI), "Update")]
		[HarmonyPrefix]
		private static void FlowermanAILEPrefixAI(FlowermanAI __instance)
		{
			if (((EnemyAI)__instance).isEnemyDead || !CanBrackenEscape.Value || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				return;
			}
			if (!((EnemyAI)__instance).isOutside)
			{
				if ((Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null && !((EnemyAI)__instance).targetPlayer.isInsideFactory && (((EnemyAI)__instance).currentBehaviourStateIndex == 1 || __instance.evadeStealthTimer > 0f) && Time.time - TimeStartTeleport >= BrackenEscapeDelay.Value + 5f)
				{
					TimeStartTeleport = Time.time;
				}
				if (Time.time - TimeStartTeleport > BrackenEscapeDelay.Value && Time.time - TimeStartTeleport < BrackenEscapeDelay.Value + 5f)
				{
					SendEnemyOutside((EnemyAI)(object)__instance);
				}
				else if (LETimerFunctions.MinuteEscapeTimerBracken >= 60f && (Object)(object)((EnemyAI)__instance).targetPlayer == (Object)null)
				{
					LETimerFunctions.MinuteEscapeTimerBracken = 0f;
					if (BrackenChanceToEscapeEveryMinute.Value != 0f && (float)Random.Range(1, 100) <= BrackenChanceToEscapeEveryMinute.Value)
					{
						SendEnemyOutside((EnemyAI)(object)__instance, SpawnOnDoor: false);
					}
				}
			}
			else if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
		}

		[HarmonyPatch(typeof(FlowermanAI), "Update")]
		[HarmonyPostfix]
		private static void FlowermanAILEPostfixAI(FlowermanAI __instance)
		{
			if (!((EnemyAI)__instance).isEnemyDead && CanBrackenEscape.Value && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && ((EnemyAI)__instance).isOutside && ((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
		}

		[HarmonyPatch(typeof(FlowermanAI), "OnCollideWithPlayer")]
		[HarmonyPostfix]
		public static void FlowerManAILEOutsideAttack(FlowermanAI __instance, ref Collider other, bool ___startingKillAnimationLocalClient)
		{
			if (!((EnemyAI)__instance).isEnemyDead && ((EnemyAI)__instance).isOutside && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component != (Object)null && !component.isPlayerDead && component.isPlayerControlled && (Object)(object)component != (Object)(object)GameNetworkManager.Instance.localPlayerController && !__instance.inKillAnimation && !___startingKillAnimationLocalClient)
				{
					__instance.KillPlayerAnimationServerRpc((int)component.playerClientId);
					___startingKillAnimationLocalClient = true;
				}
			}
		}

		[HarmonyPatch(typeof(FlowermanAI), "Start")]
		[HarmonyPostfix]
		private static void FlowermanAILEPostfixStart(FlowermanAI __instance)
		{
			TimeStartTeleport = 0f;
			if (((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && BrackenChanceToSpawnOutside.Value != 0f && (float)Random.Range(1, 100) <= BrackenChanceToSpawnOutside.Value)
			{
				SendEnemyOutside((EnemyAI)(object)__instance);
			}
		}

		[HarmonyPatch(typeof(HoarderBugAI), "Update")]
		[HarmonyPrefix]
		private static void HoardingBugAILEPrefixAI(HoarderBugAI __instance)
		{
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			if (((EnemyAI)__instance).isEnemyDead || !CanHoardingBugEscape.Value || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				return;
			}
			if (!((EnemyAI)__instance).isOutside)
			{
				if ((Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null && !((EnemyAI)__instance).targetPlayer.isInsideFactory && __instance.searchForPlayer.inProgress)
				{
					SendEnemyOutside((EnemyAI)(object)__instance);
				}
				else
				{
					if (!(LETimerFunctions.MinuteEscapeTimerHoardingBug >= 60f) || !((Object)(object)((EnemyAI)__instance).targetPlayer == (Object)null))
					{
						return;
					}
					LETimerFunctions.MinuteEscapeTimerHoardingBug = 0f;
					if ((float)Random.Range(1, 100) <= HoardingBugChanceToEscapeEveryMinute.Value / (float)Object.FindObjectsOfType(typeof(HoarderBugAI)).Length)
					{
						SendEnemyOutside((EnemyAI)(object)__instance, SpawnOnDoor: false);
						if (HoardingBugChanceToNestNearShip.Value != 0f && (float)Random.Range(1, 100) <= HoardingBugChanceToNestNearShip.Value)
						{
							StartOfRound val = (StartOfRound)Object.FindObjectOfType(typeof(StartOfRound));
							Transform val2 = ((EnemyAI)__instance).ChooseClosestNodeToPosition(val.elevatorTransform.position, false, 0);
							__instance.nestPosition = val2.position;
						}
					}
				}
			}
			else if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
		}

		[HarmonyPatch(typeof(HoarderBugAI), "OnCollideWithPlayer")]
		[HarmonyPostfix]
		public static void HoardingBugAILEOutsideAttack(HoarderBugAI __instance, ref Collider other)
		{
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: 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)
			if (!((EnemyAI)__instance).isEnemyDead && ((EnemyAI)__instance).isOutside && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component != (Object)null && !component.isPlayerDead && component.isPlayerControlled && (Object)(object)component != (Object)(object)GameNetworkManager.Instance.localPlayerController && !((double)__instance.timeSinceHittingPlayer <= 0.5) && !(((EnemyAI)__instance).stunNormalizedTimer > 0f) && __instance.inChase)
				{
					__instance.timeSinceHittingPlayer = 0f;
					component.DamagePlayer(30, true, true, (CauseOfDeath)6, 0, false, default(Vector3));
					component.DamagePlayerFromOtherClientServerRpc(30, Vector3.zero, -1);
					__instance.HitPlayerServerRpc();
				}
			}
		}

		[HarmonyPatch(typeof(HoarderBugAI), "Start")]
		[HarmonyPostfix]
		private static void HoardingBugAILEPostfixStart(HoarderBugAI __instance)
		{
			if (((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && HoardingBugChanceToSpawnOutside.Value != 0f && (float)Random.Range(1, 100) <= HoardingBugChanceToSpawnOutside.Value)
			{
				SendEnemyOutside((EnemyAI)(object)__instance);
			}
		}

		[HarmonyPatch(typeof(SpringManAI), "Update")]
		[HarmonyPrefix]
		private static void CoilHeadAILEPrefixAI(SpringManAI __instance)
		{
			if (((EnemyAI)__instance).isEnemyDead || !CanCoilHeadEscape.Value || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				return;
			}
			if (!((EnemyAI)__instance).isOutside)
			{
				if ((Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null && !((EnemyAI)__instance).targetPlayer.isInsideFactory)
				{
					SendEnemyOutside((EnemyAI)(object)__instance, SpawnOnDoor: false);
				}
			}
			else if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
		}

		[HarmonyPatch(typeof(SpringManAI), "OnCollideWithPlayer")]
		[HarmonyPostfix]
		public static void CoilHeadAILEOutsideAttack(SpringManAI __instance, ref Collider other)
		{
			//IL_00df: 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_00f0: Unknown result type (might be due to invalid IL or missing references)
			if (!((EnemyAI)__instance).isEnemyDead && ((EnemyAI)__instance).isOutside && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component != (Object)null && !component.isPlayerDead && component.isPlayerControlled && (Object)(object)component != (Object)(object)GameNetworkManager.Instance.localPlayerController && !__instance.stoppingMovement && ((EnemyAI)__instance).currentBehaviourStateIndex == 1 && !(__instance.timeSinceHittingPlayer >= 0f) && !(((EnemyAI)__instance).stunNormalizedTimer > 0f))
				{
					__instance.timeSinceHittingPlayer = 0.2f;
					component.DamagePlayer(90, true, true, (CauseOfDeath)6, 2, false, default(Vector3));
					component.DamagePlayerFromOtherClientServerRpc(90, Vector3.zero, -1);
					component.JumpToFearLevel(1f, true);
				}
			}
		}

		[HarmonyPatch(typeof(SandSpiderAI), "Update")]
		[HarmonyPrefix]
		private static void SpiderAILEPrefixAI(SandSpiderAI __instance)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			if (((EnemyAI)__instance).isEnemyDead || !CanSpiderEscape.Value || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				return;
			}
			if (!((EnemyAI)__instance).isOutside)
			{
				if ((Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null && !((EnemyAI)__instance).targetPlayer.isInsideFactory)
				{
					SendEnemyOutside((EnemyAI)(object)__instance, SpawnOnDoor: false);
					__instance.meshContainerPosition = ((EnemyAI)__instance).serverPosition;
					__instance.meshContainerTarget = ((EnemyAI)__instance).serverPosition;
					__instance.maxWebTrapsToPlace += Random.Range(SpiderMinWebsOutside.Value, SpiderMaxWebsOutside.Value);
				}
			}
			else if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
		}

		[HarmonyPatch(typeof(SandSpiderAI), "OnCollideWithPlayer")]
		[HarmonyPostfix]
		public static void SpiderAILEOutsideAttack(SandSpiderAI __instance, ref Collider other)
		{
			//IL_00c7: 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)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			if (!((EnemyAI)__instance).isEnemyDead && ((EnemyAI)__instance).isOutside && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component != (Object)null && !component.isPlayerDead && component.isPlayerControlled && (Object)(object)component != (Object)(object)GameNetworkManager.Instance.localPlayerController && !__instance.onWall && !(__instance.timeSinceHittingPlayer <= 1f) && !(((EnemyAI)__instance).stunNormalizedTimer > 0f))
				{
					__instance.timeSinceHittingPlayer = 0f;
					component.DamagePlayer(90, true, true, (CauseOfDeath)6, 0, false, default(Vector3));
					component.DamagePlayerFromOtherClientServerRpc(90, Vector3.zero, -1);
					__instance.HitPlayerServerRpc((int)component.playerClientId);
				}
			}
		}

		[HarmonyPatch(typeof(SandSpiderAI), "Start")]
		[HarmonyPostfix]
		private static void SpiderAILEPostfixStart(SandSpiderAI __instance)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			if (((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && SpiderChanceToSpawnOutside.Value != 0f && (float)Random.Range(1, 100) <= SpiderChanceToSpawnOutside.Value)
			{
				SendEnemyOutside((EnemyAI)(object)__instance);
				__instance.meshContainerPosition = ((EnemyAI)__instance).serverPosition;
				__instance.meshContainerTarget = ((EnemyAI)__instance).serverPosition;
				__instance.maxWebTrapsToPlace = Random.Range(SpiderMinWebsOutside.Value, SpiderMaxWebsOutside.Value);
			}
		}

		[HarmonyPatch(typeof(NutcrackerEnemyAI), "Update")]
		[HarmonyPrefix]
		private static void NutCrackerAILEPrefixAI(NutcrackerEnemyAI __instance)
		{
			if (((EnemyAI)__instance).isEnemyDead || !CanNutCrackerEscape.Value || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				return;
			}
			if (!((EnemyAI)__instance).isOutside)
			{
				if ((Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null && !((EnemyAI)__instance).targetPlayer.isInsideFactory)
				{
					SendEnemyOutside((EnemyAI)(object)__instance);
				}
			}
			else if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
		}

		[HarmonyPatch(typeof(NutcrackerEnemyAI), "OnCollideWithPlayer")]
		[HarmonyPostfix]
		public static void NutCrackerAILEOutsideAttack(NutcrackerEnemyAI __instance, ref Collider other)
		{
			if (!((EnemyAI)__instance).isEnemyDead && ((EnemyAI)__instance).isOutside && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component != (Object)null && !component.isPlayerDead && component.isPlayerControlled && (Object)(object)component != (Object)(object)GameNetworkManager.Instance.localPlayerController && !(((EnemyAI)__instance).stunNormalizedTimer >= 0f) && !(__instance.timeSinceHittingPlayer < 1f))
				{
					__instance.timeSinceHittingPlayer = 0f;
					__instance.LegKickPlayerServerRpc((int)component.playerClientId);
				}
			}
		}

		[HarmonyPatch(typeof(NutcrackerEnemyAI), "Start")]
		[HarmonyPostfix]
		private static void NutCrackerAILEPostfixStart(NutcrackerEnemyAI __instance)
		{
			if (((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && NutCrackerChanceToSpawnOutside.Value != 0f && (float)Random.Range(1, 100) <= NutCrackerChanceToSpawnOutside.Value)
			{
				SendEnemyOutside((EnemyAI)(object)__instance);
			}
		}

		[HarmonyPatch(typeof(BlobAI), "Update")]
		[HarmonyPrefix]
		private static void BlobAILEPrefixAI(BlobAI __instance)
		{
			if (((EnemyAI)__instance).isEnemyDead || !CanHygrodereEscape.Value || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				return;
			}
			if (!((EnemyAI)__instance).isOutside)
			{
				if ((Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null && !((EnemyAI)__instance).targetPlayer.isInsideFactory)
				{
					SendEnemyOutside((EnemyAI)(object)__instance, SpawnOnDoor: false);
					__instance.centerPoint = ((Component)__instance).transform;
				}
			}
			else if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
		}

		[HarmonyPatch(typeof(BlobAI), "OnCollideWithPlayer")]
		[HarmonyPostfix]
		public static void BlobAILEOutsideAttack(BlobAI __instance, ref Collider other)
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			if (((EnemyAI)__instance).isEnemyDead || !((EnemyAI)__instance).isOutside || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				return;
			}
			PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
			if ((Object)(object)component != (Object)null && !component.isPlayerDead && component.isPlayerControlled && (Object)(object)component != (Object)(object)GameNetworkManager.Instance.localPlayerController && !(__instance.timeSinceHittingLocalPlayer < 0.25f) && (!(__instance.tamedTimer > 0f) || !(__instance.angeredTimer < 0f)))
			{
				__instance.timeSinceHittingLocalPlayer = 0f;
				component.DamagePlayerFromOtherClientServerRpc(35, Vector3.zero, -1);
				component.DamagePlayer(35, true, true, (CauseOfDeath)0, 0, false, default(Vector3));
				if (component.isPlayerDead)
				{
					__instance.SlimeKillPlayerEffectServerRpc((int)component.playerClientId);
				}
			}
		}

		[HarmonyPatch(typeof(BlobAI), "Start")]
		[HarmonyPostfix]
		private static void HygrodereAILEPostfixStart(BlobAI __instance)
		{
			if (((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && HygrodereChanceToSpawnOutside.Value != 0f && (float)Random.Range(1, 100) <= HygrodereChanceToSpawnOutside.Value)
			{
				SendEnemyOutside((EnemyAI)(object)__instance);
				__instance.centerPoint = ((Component)__instance).transform;
			}
		}

		[HarmonyPatch(typeof(PufferAI), "Update")]
		[HarmonyPrefix]
		private static void PufferAILEPrefixAI(PufferAI __instance)
		{
			if (((EnemyAI)__instance).isEnemyDead || !CanPufferEscape.Value || !((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				return;
			}
			if (!((EnemyAI)__instance).isOutside)
			{
				if ((Object)(object)((EnemyAI)__instance).targetPlayer != (Object)null && !((EnemyAI)__instance).targetPlayer.isInsideFactory)
				{
					SendEnemyOutside((EnemyAI)(object)__instance, SpawnOnDoor: false);
				}
				else if (LETimerFunctions.MinuteEscapeTimerPuffer >= 60f && (Object)(object)((EnemyAI)__instance).targetPlayer == (Object)null)
				{
					LETimerFunctions.MinuteEscapeTimerPuffer = 0f;
					if (PufferChanceToEscapeEveryMinute.Value != 0f && (float)Random.Range(1, 100) <= PufferChanceToEscapeEveryMinute.Value)
					{
						SendEnemyOutside((EnemyAI)(object)__instance, SpawnOnDoor: false);
					}
				}
			}
			else if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				((EnemyAI)__instance).ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
		}

		[HarmonyPatch(typeof(PufferAI), "OnCollideWithPlayer")]
		[HarmonyPostfix]
		public static void PufferAILEOutsideAttack(PufferAI __instance, ref Collider other)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: 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)
			if (!((EnemyAI)__instance).isEnemyDead && ((EnemyAI)__instance).isOutside && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost)
			{
				PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>();
				if ((Object)(object)component != (Object)null && !component.isPlayerDead && component.isPlayerControlled && (Object)(object)component != (Object)(object)GameNetworkManager.Instance.localPlayerController && !(__instance.timeSinceHittingPlayer <= 1f))
				{
					__instance.timeSinceHittingPlayer = 0f;
					component.DamagePlayer(20, true, true, (CauseOfDeath)6, 0, false, default(Vector3));
					component.DamagePlayerFromOtherClientServerRpc(20, Vector3.zero, -1);
					__instance.BitePlayerServerRpc((int)component.playerClientId);
				}
			}
		}

		[HarmonyPatch(typeof(PufferAI), "Start")]
		[HarmonyPostfix]
		private static void PufferAILEPostfixStart(PufferAI __instance)
		{
			if (((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && PufferChanceToSpawnOutside.Value != 0f && (float)Random.Range(1, 100) <= PufferChanceToSpawnOutside.Value)
			{
				SendEnemyOutside((EnemyAI)(object)__instance);
			}
		}

		public static void SendEnemyInside(EnemyAI __instance)
		{
			//IL_0069: 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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: 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_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			__instance.isOutside = false;
			__instance.allAINodes = GameObject.FindGameObjectsWithTag("AINode");
			EntranceTeleport[] array = Object.FindObjectsOfType<EntranceTeleport>(false);
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i].entranceId == 0 && !array[i].isEntranceToBuilding)
				{
					__instance.serverPosition = array[i].entrancePoint.position;
					break;
				}
			}
			Transform val = __instance.ChooseClosestNodeToPosition(__instance.serverPosition, false, 0);
			if (Vector3.Magnitude(val.position - __instance.serverPosition) > 10f)
			{
				__instance.serverPosition = val.position;
				((Component)__instance).transform.position = __instance.serverPosition;
			}
			((Component)__instance).transform.position = __instance.serverPosition;
			__instance.agent.Warp(__instance.serverPosition);
			__instance.SyncPositionToClients();
		}

		public static void SendEnemyOutside(EnemyAI __instance, bool SpawnOnDoor = true)
		{
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: 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)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: 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)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			__instance.isOutside = true;
			__instance.allAINodes = GameObject.FindGameObjectsWithTag("OutsideAINode");
			EntranceTeleport[] array = Object.FindObjectsOfType<EntranceTeleport>(false);
			float num = 999f;
			for (int i = 0; i < array.Length; i++)
			{
				if (!array[i].isEntranceToBuilding)
				{
					continue;
				}
				for (int j = 0; j < StartOfRound.Instance.connectedPlayersAmount + 1; j++)
				{
					if (!StartOfRound.Instance.allPlayerScripts[j].isInsideFactory & (Vector3.Magnitude(((Component)StartOfRound.Instance.allPlayerScripts[j]).transform.position - array[i].entrancePoint.position) < num))
					{
						num = Vector3.Magnitude(((Component)StartOfRound.Instance.allPlayerScripts[j]).transform.position - array[i].entrancePoint.position);
						__instance.serverPosition = array[i].entrancePoint.position;
					}
				}
			}
			if (((NetworkBehaviour)__instance).OwnerClientId != GameNetworkManager.Instance.localPlayerController.actualClientId)
			{
				__instance.ChangeOwnershipOfEnemy(GameNetworkManager.Instance.localPlayerController.actualClientId);
			}
			Transform val = __instance.ChooseClosestNodeToPosition(__instance.serverPosition, false, 0);
			if (Vector3.Magnitude(val.position - __instance.serverPosition) > 10f || !SpawnOnDoor)
			{
				__instance.serverPosition = val.position;
			}
			((Component)__instance).transform.position = __instance.serverPosition;
			__instance.agent.Warp(__instance.serverPosition);
			__instance.SyncPositionToClients();
			if ((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null)
			{
				__instance.EnableEnemyMesh(!StartOfRound.Instance.hangarDoorsClosed || !GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom, false);
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/LethalExpansion.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Adapters;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using LethalExpansion.Extenders;
using LethalExpansion.Patches;
using LethalExpansion.Patches.Monsters;
using LethalExpansion.Utils;
using LethalExpansion.Utils.HUD;
using LethalSDK.Component;
using LethalSDK.ScriptableObjects;
using LethalSDK.Utils;
using TMPro;
using Unity.AI.Navigation;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Audio;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Mono.Security")]
[assembly: IgnoresAccessChecksTo("Newtonsoft.Json")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AccessibilityModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AIModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AndroidJNIModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AnimationModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AssetBundleModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.AudioModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ClothModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ClusterInputModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ClusterRendererModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ContentLoadModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.CoreModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.CrashReportingModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.DirectorModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine")]
[assembly: IgnoresAccessChecksTo("UnityEngine.DSPGraphModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.GameCenterModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.GIModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.GridModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.HotReloadModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ImageConversionModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.IMGUIModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.InputLegacyModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.InputModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.JSONSerializeModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.LocalizationModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ParticleSystemModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.PerformanceReportingModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.Physics2DModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.PhysicsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ProfilerModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.PropertiesModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.RuntimeInitializeOnLoadManagerInitializerModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ScreenCaptureModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SharedInternalsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SpriteMaskModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SpriteShapeModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.StreamingModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SubstanceModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.SubsystemsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TerrainModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TerrainPhysicsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TextCoreFontEngineModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TextCoreTextEngineModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TextRenderingModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TilemapModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.TLSModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UIElementsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UIModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UmbraModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityAnalyticsCommonModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityAnalyticsModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityConnectModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityCurlModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityTestProtocolModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityWebRequestAssetBundleModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityWebRequestAudioModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityWebRequestModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityWebRequestTextureModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UnityWebRequestWWWModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.VehiclesModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.VFXModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.VideoModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.VirtualTexturingModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.VRModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.WindModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.XRModule")]
[assembly: AssemblyCompany("LethalExpansion")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+6d25ed6204e3cd169601ec9c0f5974b954cffc33")]
[assembly: AssemblyProduct("LethalExpansion")]
[assembly: AssemblyTitle("LethalExpansion")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
public class AutoScrollText : MonoBehaviour
{
	public TextMeshProUGUI textMeshPro;

	public float scrollSpeed = 15f;

	private Vector2 startPosition;

	private float textHeight;

	private bool startScrolling = false;

	private bool isWaitingToReset = false;

	private float displayHeight;

	private float fontSize;

	private void Start()
	{
		textMeshPro = ((Component)this).GetComponent<TextMeshProUGUI>();
		InitializeScrolling();
	}

	private void InitializeScrolling()
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)textMeshPro != (Object)null)
		{
			startPosition = ((TMP_Text)textMeshPro).rectTransform.anchoredPosition;
			textHeight = ((TMP_Text)textMeshPro).preferredHeight;
			displayHeight = ((TMP_Text)textMeshPro).rectTransform.sizeDelta.y;
			fontSize = ((TMP_Text)textMeshPro).fontSize;
		}
		((MonoBehaviour)this).StartCoroutine(WaitBeforeScrolling(5f));
	}

	private IEnumerator WaitBeforeScrolling(float waitTime)
	{
		yield return (object)new WaitForSeconds(waitTime);
		startScrolling = true;
	}

	private IEnumerator WaitBeforeResetting(float waitTime)
	{
		isWaitingToReset = true;
		yield return (object)new WaitForSeconds(waitTime);
		((TMP_Text)textMeshPro).rectTransform.anchoredPosition = startPosition;
		isWaitingToReset = false;
		((MonoBehaviour)this).StartCoroutine(WaitBeforeScrolling(5f));
	}

	private void Update()
	{
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)textMeshPro != (Object)null && startScrolling && !isWaitingToReset)
		{
			RectTransform rectTransform = ((TMP_Text)textMeshPro).rectTransform;
			rectTransform.anchoredPosition += new Vector2(0f, scrollSpeed * Time.deltaTime);
			if (((TMP_Text)textMeshPro).rectTransform.anchoredPosition.y >= startPosition.y + textHeight - displayHeight - fontSize)
			{
				startScrolling = false;
				((MonoBehaviour)this).StartCoroutine(WaitBeforeResetting(5f));
			}
		}
	}

	public void ResetScrolling()
	{
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		((MonoBehaviour)this).StopAllCoroutines();
		if ((Object)(object)textMeshPro != (Object)null)
		{
			((TMP_Text)textMeshPro).rectTransform.anchoredPosition = startPosition;
		}
		isWaitingToReset = false;
		InitializeScrolling();
	}
}
public class TooltipHandler : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler
{
	private string description;

	private string netinfo;

	public static RectTransform ModSettingsToolTipPanel;

	public static TMP_Text ModSettingsToolTipPanelDescription;

	public static TMP_Text ModSettingsToolTipPanelNetInfo;

	public int index;

	private float delay = 0.5f;

	private bool isPointerOver = false;

	public void OnPointerEnter(PointerEventData eventData)
	{
		isPointerOver = true;
		((MonoBehaviour)this).StartCoroutine(ShowTooltipAfterDelay());
	}

	public void OnPointerExit(PointerEventData eventData)
	{
		isPointerOver = false;
		((Component)ModSettingsToolTipPanel).gameObject.SetActive(false);
	}

	private IEnumerator ShowTooltipAfterDelay()
	{
		yield return (object)new WaitForSeconds(delay);
		if (isPointerOver)
		{
			ModSettingsToolTipPanel.anchoredPosition = new Vector2(-30f, ((Component)this).GetComponent<RectTransform>().anchoredPosition.y + -80f);
			description = ConfigManager.Instance.FindDescription(index);
			(bool, bool) info = ConfigManager.Instance.FindNetInfo(index);
			netinfo = "Network synchronization: " + (info.Item1 ? "Yes" : "No") + "\nMod required by clients: " + (info.Item2 ? "No" : "Yes");
			ModSettingsToolTipPanelDescription.text = description;
			ModSettingsToolTipPanelNetInfo.text = netinfo;
			((Component)ModSettingsToolTipPanel).gameObject.SetActive(true);
		}
	}
}
public class ConfigItem
{
	public string Key { get; set; }

	public Type type { get; set; }

	public object Value { get; set; }

	public object DefaultValue { get; set; }

	public string Tab { get; set; }

	public string Description { get; set; }

	public object MinValue { get; set; }

	public object MaxValue { get; set; }

	public bool Sync { get; set; }

	public bool Hidden { get; set; }

	public bool Optional { get; set; }

	public bool RequireRestart { get; set; }

	public ConfigItem(string key, object defaultValue, string tab, string description, object minValue = null, object maxValue = null, bool sync = true, bool optional = false, bool hidden = false, bool requireRestart = false)
	{
		Key = key;
		DefaultValue = defaultValue;
		type = defaultValue.GetType();
		Tab = tab;
		Description = description;
		if (minValue != null && maxValue != null)
		{
			if (minValue.GetType() == type && maxValue.GetType() == type)
			{
				MinValue = minValue;
				MaxValue = maxValue;
			}
		}
		else
		{
			MinValue = null;
			MaxValue = null;
		}
		Sync = sync;
		Optional = optional;
		Hidden = hidden;
		Value = DefaultValue;
		RequireRestart = requireRestart;
	}
}
namespace LethalExpansion
{
	[BepInPlugin("LethalExpansion", "LethalExpansion", "1.3.25")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class LethalExpansion : BaseUnityPlugin
	{
		private enum compatibility
		{
			unknown,
			perfect,
			good,
			medium,
			bad,
			critical
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<PluginInfo, bool> <>9__31_1;

			public static UnityAction <>9__31_0;

			public static Func<PluginInfo, bool> <>9__31_2;

			public static Func<AudioMixerGroup, bool> <>9__32_0;

			public static Func<GameObject, bool> <>9__32_1;

			public static Func<AudioMixerGroup, bool> <>9__32_2;

			public static Func<AudioMixerGroup, bool> <>9__32_3;

			public static Func<AudioMixerGroup, bool> <>9__32_4;

			public static Func<PluginInfo, bool> <>9__35_0;

			public static Func<PluginInfo, bool> <>9__35_1;

			public static Func<PluginInfo, bool> <>9__35_2;

			public static Func<PluginInfo, bool> <>9__35_3;

			internal bool <OnSceneLoaded>b__31_1(PluginInfo p)
			{
				return p.Metadata.GUID == "CoomfyDungeon";
			}

			internal void <OnSceneLoaded>b__31_0()
			{
				ConfigManager.Instance.SetItemValue("CoomfyDungeonCompatibility", value: true);
				ConfigManager.Instance.SetEntryValue("CoomfyDungeonCompatibility", value: true);
			}

			internal bool <OnSceneLoaded>b__31_2(PluginInfo p)
			{
				return p.Metadata.GUID == "BiggerLobby";
			}

			internal bool <LoadCustomMoon>b__32_0(AudioMixerGroup a)
			{
				return ((Object)a).name == "Master";
			}

			internal bool <LoadCustomMoon>b__32_1(GameObject o)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				Scene scene = o.scene;
				return ((Scene)(ref scene)).name != "InitSceneLaunchOptions";
			}

			internal bool <LoadCustomMoon>b__32_2(AudioMixerGroup a)
			{
				return ((Object)a).name == "Master";
			}

			internal bool <LoadCustomMoon>b__32_3(AudioMixerGroup a)
			{
				return ((Object)a).name == "Master";
			}

			internal bool <LoadCustomMoon>b__32_4(AudioMixerGroup a)
			{
				return ((Object)a).name == "Master";
			}

			internal bool <waitForSession>b__35_0(PluginInfo p)
			{
				return p.Metadata.GUID == "BrutalCompanyPlus";
			}

			internal bool <waitForSession>b__35_1(PluginInfo p)
			{
				return p.Metadata.GUID == "LethalAdjustments";
			}

			internal bool <waitForSession>b__35_2(PluginInfo p)
			{
				return p.Metadata.GUID == "CoomfyDungeon";
			}

			internal bool <waitForSession>b__35_3(PluginInfo p)
			{
				return p.Metadata.GUID == "299792458.MoreMoneyStart";
			}
		}

		private const string PluginGUID = "LethalExpansion";

		private const string PluginName = "LethalExpansion";

		private const string VersionString = "1.3.25";

		public static readonly Version ModVersion = new Version("1.3.25");

		public static readonly int[] CompatibleGameVersions = new int[4] { 45, 47, 48, 49 };

		private readonly Dictionary<string, compatibility> CompatibleMods = new Dictionary<string, compatibility>
		{
			{
				"com.sinai.unityexplorer",
				compatibility.medium
			},
			{
				"HDLethalCompany",
				compatibility.good
			},
			{
				"LC_API",
				compatibility.good
			},
			{
				"me.swipez.melonloader.morecompany",
				compatibility.medium
			},
			{
				"BrutalCompanyPlus",
				compatibility.medium
			},
			{
				"MoonOfTheDay",
				compatibility.good
			},
			{
				"Television_Controller",
				compatibility.bad
			},
			{
				"beeisyou.LandmineFix",
				compatibility.perfect
			},
			{
				"LethalAdjustments",
				compatibility.good
			},
			{
				"CoomfyDungeon",
				compatibility.bad
			},
			{
				"BiggerLobby",
				compatibility.critical
			},
			{
				"KoderTech.BoomboxController",
				compatibility.good
			},
			{
				"299792458.MoreMoneyStart",
				compatibility.good
			}
		};

		private List<PluginInfo> loadedPlugins = new List<PluginInfo>();

		public static bool sessionWaiting = true;

		public static bool hostDataWaiting = true;

		public static bool ishost = false;

		public static bool alreadypatched = false;

		public static bool weathersReadyToShare = false;

		public static bool isInGame = false;

		public static bool dungeonGeneratorReady = false;

		public static int delayedLevelChange = -1;

		public static string lastKickReason = string.Empty;

		private static readonly Harmony Harmony = new Harmony("LethalExpansion");

		public static ManualLogSource Log = new ManualLogSource("LethalExpansion");

		public static ConfigFile config;

		public GameObject SpaceLight;

		public GameObject terrainfixer;

		public static Transform currentWaterSurface;

		private int width = 256;

		private int height = 256;

		private int depth = 20;

		private float scale = 20f;

		private void Awake()
		{
			//IL_0c42: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c48: Expected O, but got Unknown
			//IL_0c91: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c9e: Expected O, but got Unknown
			//IL_0ca3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cb0: Expected O, but got Unknown
			//IL_0d17: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d24: Expected O, but got Unknown
			//IL_0d2b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d38: Expected O, but got Unknown
			//IL_0d56: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d5b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d67: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"PluginName: LethalExpansion, VersionString: 1.3.25 is loading...");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Getting other plugins list");
			loadedPlugins = GetLoadedPlugins();
			foreach (PluginInfo loadedPlugin in loadedPlugins)
			{
				if (!(loadedPlugin.Metadata.GUID != "LethalExpansion"))
				{
					continue;
				}
				if (CompatibleMods.ContainsKey(loadedPlugin.Metadata.GUID))
				{
					switch (CompatibleMods[loadedPlugin.Metadata.GUID])
					{
					case compatibility.unknown:
						Console.BackgroundColor = ConsoleColor.Gray;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					case compatibility.perfect:
						Console.BackgroundColor = ConsoleColor.Blue;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					case compatibility.good:
						Console.BackgroundColor = ConsoleColor.Green;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					case compatibility.medium:
						Console.BackgroundColor = ConsoleColor.Yellow;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogWarning((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					case compatibility.bad:
						Console.BackgroundColor = ConsoleColor.Red;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogError((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					case compatibility.critical:
						Console.BackgroundColor = ConsoleColor.Magenta;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogFatal((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					default:
						Console.BackgroundColor = ConsoleColor.Gray;
						((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
						Console.ResetColor();
						((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}");
						break;
					}
					((BaseUnityPlugin)this).Logger.LogInfo((object)"------------------------------");
				}
				else
				{
					Console.BackgroundColor = ConsoleColor.Gray;
					((BaseUnityPlugin)this).Logger.LogInfo((object)"                              ");
					Console.ResetColor();
					((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {compatibility.unknown}");
					((BaseUnityPlugin)this).Logger.LogInfo((object)"------------------------------");
				}
			}
			config = ((BaseUnityPlugin)this).Config;
			ConfigManager.Instance.AddItem(new ConfigItem("GlobalTimeSpeedMultiplier", 1.4f, "Time", "Change the global time speed", 0.1f, 3f));
			ConfigManager.Instance.AddItem(new ConfigItem("NumberOfHours", 18, "Time", "Max lenght of an Expedition in hours. (Begin at 6 AM | 18 = Midnight)", 6, 20));
			ConfigManager.Instance.AddItem(new ConfigItem("DeadlineDaysAmount", 3, "Expeditions", "Change amount of days for the Quota.", 1, 9));
			ConfigManager.Instance.AddItem(new ConfigItem("StartingCredits", 60, "Expeditions", "Change amount of starting Credit.", 0, 1000));
			ConfigManager.Instance.AddItem(new ConfigItem("MoonsRoutePricesMultiplier", 1f, "Moons", "Change the Cost of the Moon Routes.", 0f, 5f));
			ConfigManager.Instance.AddItem(new ConfigItem("StartingQuota", 130, "Expeditions", "Change the starting Quota.", 0, 1000, sync: true, optional: true));
			ConfigManager.Instance.AddItem(new ConfigItem("ScrapAmountMultiplier", 1f, "Dungeons", "Change the amount of Scraps in dungeons.", 0f, 10f));
			ConfigManager.Instance.AddItem(new ConfigItem("ScrapValueMultiplier", 0.4f, "Dungeons", "Change the value of Scraps.", 0f, 10f));
			ConfigManager.Instance.AddItem(new ConfigItem("MapSizeMultiplier", 1.5f, "Dungeons", "Change the size of the Dungeons. (Can crash when under 1.0)", 0.8f, 10f));
			ConfigManager.Instance.AddItem(new ConfigItem("PreventMineToExplodeWithItems", false, "Dungeons", "Prevent Landmines to explode by dropping items on them"));
			ConfigManager.Instance.AddItem(new ConfigItem("MineActivationWeight", 0.15f, "Dungeons", "Set the minimal weight to prevent Landmine's explosion (0.15 = 16 lb, Player = 2.0)", 0.01f, 5f));
			ConfigManager.Instance.AddItem(new ConfigItem("WeightUnit", 0, "HUD", "Change the carried Weight unit : 0 = Pounds (lb), 1 = Kilograms (kg) and 2 = Both", 0, 2, sync: false));
			ConfigManager.Instance.AddItem(new ConfigItem("ConvertPoundsToKilograms", true, "HUD", "Convert Pounds into Kilograms (16 lb = 7 kg) (Only effective if WeightUnit = 1)", null, null, sync: false));
			ConfigManager.Instance.AddItem(new ConfigItem("PreventScrapWipeWhenAllPlayersDie", false, "Expeditions", "Prevent the Scraps Wipe when all players die."));
			ConfigManager.Instance.AddItem(new ConfigItem("24HoursClock", false, "HUD", "Display a 24h clock instead of 12h.", null, null, sync: false));
			ConfigManager.Instance.AddItem(new ConfigItem("ClockAlwaysVisible", false, "HUD", "Display clock while inside of the Ship."));
			ConfigManager.Instance.AddItem(new ConfigItem("AutomaticDeadline", false, "Expeditions", "Automatically increase the Deadline depending of the required quota."));
			ConfigManager.Instance.AddItem(new ConfigItem("AutomaticDeadlineStage", 300, "Expeditions", "Increase the quota deadline of one day each time the quota exceeds this value.", 100, 3000));
			ConfigManager.Instance.AddItem(new ConfigItem("LoadModules", true, "Modules", "Load SDK Modules that add new content to the game. Disable it to play with Vanilla players. (RESTART REQUIRED)", null, null, sync: false, optional: false, hidden: false, requireRestart: true));
			ConfigManager.Instance.AddItem(new ConfigItem("MaxItemsInShip", 45, "Expeditions", "Change the Items cap can be kept in the ship.", 10, 500));
			ConfigManager.Instance.AddItem(new ConfigItem("ShowMoonWeatherInCatalogue", true, "HUD", "Display the current weather of Moons in the Terminal's Moon Catalogue."));
			ConfigManager.Instance.AddItem(new ConfigItem("ShowMoonRankInCatalogue", false, "HUD", "Display the rank of Moons in the Terminal's Moon Catalogue."));
			ConfigManager.Instance.AddItem(new ConfigItem("ShowMoonPriceInCatalogue", false, "HUD", "Display the route price of Moons in the Terminal's Moon Catalogue."));
			ConfigManager.Instance.AddItem(new ConfigItem("QuotaIncreaseSteepness", 16, "Expeditions", "Change the Quota Increase Steepness. (Highter = less steep exponential increase)", 0, 32));
			ConfigManager.Instance.AddItem(new ConfigItem("QuotaBaseIncrease", 100, "Expeditions", "Change the Quota Base Increase.", 0, 300));
			ConfigManager.Instance.AddItem(new ConfigItem("KickPlayerWithoutMod", false, "Lobby", "Kick the players without Lethal Expansion installer. (Will be kicked anyway if LoadModules is True)"));
			ConfigManager.Instance.AddItem(new ConfigItem("BrutalCompanyPlusCompatibility", false, "Compatibility", "Leave Brutal Company Plus control the Quota settings."));
			ConfigManager.Instance.AddItem(new ConfigItem("LethalAdjustmentsCompatibility", false, "Compatibility", "Leave Lethal Adjustments control the Dungeon settings."));
			ConfigManager.Instance.AddItem(new ConfigItem("CoomfyDungeonCompatibility", false, "Compatibility", "Let Coomfy Dungeons control the Dungeon size & scrap settings."));
			ConfigManager.Instance.AddItem(new ConfigItem("MoreMoneyStartCompatibility", false, "Compatibility", "Let MoreMoneyStart control the Starting credits amount."));
			ConfigManager.Instance.AddItem(new ConfigItem("SettingsDebug", false, "Debug", "Show an output of every settings in the Console. (The Console must listen Info messages)", null, null, sync: false));
			ConfigManager.Instance.AddItem(new ConfigItem("LegacyMoonLoading", false, "Modules", "Roll back to Synchronous moon loading. (Freeze the game longer and highter chance of crash)"));
			ConfigManager.Instance.ReadConfig();
			((BaseUnityPlugin)this).Config.SettingChanged += ConfigSettingChanged;
			AssetBundlesManager.Instance.LoadAllAssetBundles();
			SceneManager.sceneLoaded += OnSceneLoaded;
			SceneManager.sceneUnloaded += OnSceneUnloaded;
			Harmony.PatchAll(typeof(GameNetworkManager_Patch));
			Harmony.PatchAll(typeof(Terminal_Patch));
			Harmony.PatchAll(typeof(MenuManager_Patch));
			Harmony.PatchAll(typeof(GrabbableObject_Patch));
			Harmony.PatchAll(typeof(RoundManager_Patch));
			Harmony.PatchAll(typeof(TimeOfDay_Patch));
			Harmony.PatchAll(typeof(HUDManager_Patch));
			Harmony.PatchAll(typeof(StartOfRound_Patch));
			Harmony.PatchAll(typeof(EntranceTeleport_Patch));
			Harmony.PatchAll(typeof(Landmine_Patch));
			Harmony.PatchAll(typeof(AudioReverbTrigger_Patch));
			Harmony.PatchAll(typeof(InteractTrigger_Patch));
			Harmony.PatchAll(typeof(RuntimeDungeon));
			Harmony val = new Harmony("LethalExpansion");
			MethodInfo methodInfo = AccessTools.Method(typeof(BaboonBirdAI), "GrabScrap", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(HoarderBugAI), "GrabItem", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(MonsterGrabItem_Patch), "MonsterGrabItem", (Type[])null, (Type[])null);
			val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			MethodInfo methodInfo4 = AccessTools.Method(typeof(HoarderBugAI), "DropItem", (Type[])null, (Type[])null);
			MethodInfo methodInfo5 = AccessTools.Method(typeof(MonsterGrabItem_Patch), "MonsterDropItem_Patch", (Type[])null, (Type[])null);
			MethodInfo methodInfo6 = AccessTools.Method(typeof(HoarderBugAI), "KillEnemy", (Type[])null, (Type[])null);
			MethodInfo methodInfo7 = AccessTools.Method(typeof(MonsterGrabItem_Patch), "KillEnemy_Patch", (Type[])null, (Type[])null);
			val.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(methodInfo5), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			val.Patch((MethodBase)methodInfo6, (HarmonyMethod)null, new HarmonyMethod(methodInfo7), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
			HDRenderPipelineAsset val2 = (HDRenderPipelineAsset)(object)((currentRenderPipeline is HDRenderPipelineAsset) ? currentRenderPipeline : null);
			if ((Object)(object)val2 != (Object)null)
			{
				RenderPipelineSettings currentPlatformRenderPipelineSettings = val2.currentPlatformRenderPipelineSettings;
				currentPlatformRenderPipelineSettings.supportWater = true;
				val2.currentPlatformRenderPipelineSettings = currentPlatformRenderPipelineSettings;
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Water support applied to the HDRenderPipelineAsset.");
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"HDRenderPipelineAsset not found.");
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"PluginName: LethalExpansion, VersionString: 1.3.25 is loaded.");
		}

		private List<PluginInfo> GetLoadedPlugins()
		{
			return Chainloader.PluginInfos.Values.ToList();
		}

		private float[,] GenerateHeights()
		{
			float[,] array = new float[width, height];
			for (int i = 0; i < width; i++)
			{
				for (int j = 0; j < height; j++)
				{
					array[i, j] = CalculateHeight(i, j);
				}
			}
			return array;
		}

		private float CalculateHeight(int x, int y)
		{
			float num = (float)x / (float)width * scale;
			float num2 = (float)y / (float)height * scale;
			return Mathf.PerlinNoise(num, num2);
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e6: Expected O, but got Unknown
			//IL_0411: Unknown result type (might be due to invalid IL or missing references)
			//IL_0429: Unknown result type (might be due to invalid IL or missing references)
			//IL_0430: Expected O, but got Unknown
			//IL_0457: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0783: Unknown result type (might be due to invalid IL or missing references)
			//IL_0772: Unknown result type (might be due to invalid IL or missing references)
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Loading scene: " + ((Scene)(ref scene)).name));
			if (((Scene)(ref scene)).name == "MainMenu")
			{
				sessionWaiting = true;
				hostDataWaiting = true;
				ishost = false;
				alreadypatched = false;
				dungeonGeneratorReady = false;
				delayedLevelChange = -1;
				isInGame = false;
				AssetGather.Instance.AddAudioMixer(GameObject.Find("Canvas/MenuManager").GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer);
				SettingsMenu.Instance.InitSettingsMenu();
				if (lastKickReason != null && lastKickReason.Length > 0)
				{
					PopupManager.Instance.InstantiatePopup(scene, "Kicked from Lobby", "You have been kicked\r\nReason: " + lastKickReason, "Ok", "Ignore");
				}
				if (!ConfigManager.Instance.FindEntryValue<bool>("CoomfyDungeonCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "CoomfyDungeon"))
				{
					PopupManager instance = PopupManager.Instance;
					Scene sceneFocus = scene;
					object obj = <>c.<>9__31_0;
					if (obj == null)
					{
						UnityAction val = delegate
						{
							ConfigManager.Instance.SetItemValue("CoomfyDungeonCompatibility", value: true);
							ConfigManager.Instance.SetEntryValue("CoomfyDungeonCompatibility", value: true);
						};
						<>c.<>9__31_0 = val;
						obj = (object)val;
					}
					instance.InstantiatePopup(sceneFocus, "CoomfyDungeon mod found", "Warning: CoomfyDungeon is incompatible with LethalExpansion, Would you like to enable the compatibility mode? Otherwise dungeon generation Desync may occurs!", "Yes", "No", (UnityAction)obj, null, 20, 18);
				}
				if (loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "BiggerLobby"))
				{
					PopupManager.Instance.InstantiatePopup(scene, "BiggerLobby mod found", "Warning: BiggerLobby is incompatible with LethalExpansion, host/client synchronization will break and dungeon generation Desync may occurs!", "Ok", "Ignore", null, null, 20, 18);
				}
			}
			if (((Scene)(ref scene)).name == "CompanyBuilding")
			{
				if ((Object)(object)SpaceLight != (Object)null)
				{
					SpaceLight.SetActive(false);
				}
				if ((Object)(object)terrainfixer != (Object)null)
				{
					terrainfixer.SetActive(false);
				}
				dungeonGeneratorReady = true;
			}
			if (((Scene)(ref scene)).name == "SampleSceneRelay")
			{
				SpaceLight = Object.Instantiate<GameObject>(AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Prefabs/SpaceLight.prefab"));
				SceneManager.MoveGameObjectToScene(SpaceLight, scene);
				Mesh mesh = AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Meshes/MonitorWall.fbx").GetComponent<MeshFilter>().mesh;
				GameObject val2 = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube");
				val2.GetComponent<MeshFilter>().mesh = mesh;
				MeshRenderer component = val2.GetComponent<MeshRenderer>();
				GameObject val3 = Object.Instantiate<GameObject>(GameObject.Find("Systems/GameSystems/TimeAndWeather/Flooding"));
				Object.Destroy((Object)(object)val3.GetComponent<FloodWeather>());
				((Object)val3).name = "WaterSurface";
				val3.transform.position = Vector3.zero;
				((Component)val3.transform.Find("Water")).GetComponent<MeshFilter>().sharedMesh = null;
				SpawnPrefab.Instance.waterSurface = val3;
				((Renderer)component).materials = (Material[])(object)new Material[9]
				{
					((Renderer)component).materials[0],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[1],
					((Renderer)component).materials[2]
				};
				((Component)StartOfRound.Instance.screenLevelDescription).gameObject.AddComponent<AutoScrollText>();
				AssetGather.Instance.AddAudioMixer(GameObject.Find("Systems/Audios/DiageticBackground").GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer);
				terrainfixer = new GameObject();
				((Object)terrainfixer).name = "terrainfixer";
				terrainfixer.transform.position = new Vector3(0f, -500f, 0f);
				Terrain val4 = terrainfixer.AddComponent<Terrain>();
				TerrainData val5 = new TerrainData();
				val5.heightmapResolution = width + 1;
				val5.size = new Vector3((float)width, (float)depth, (float)height);
				val5.SetHeights(0, 0, GenerateHeights());
				val4.terrainData = val5;
				Terminal_Patch.ResetFireExitAmounts();
				Object[] array = Resources.FindObjectsOfTypeAll(typeof(Volume));
				for (int i = 0; i < array.Length; i++)
				{
					Object obj2 = array[i];
					if ((Object)(object)((Volume)((obj2 is Volume) ? obj2 : null)).sharedProfile == (Object)null)
					{
						Object obj3 = array[i];
						((Volume)((obj3 is Volume) ? obj3 : null)).sharedProfile = AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<VolumeProfile>("Assets/Mods/LethalExpansion/Sky and Fog Global Volume Profile.asset");
					}
				}
				waitForSession().GetAwaiter();
				isInGame = true;
			}
			if (((Scene)(ref scene)).name.StartsWith("Level"))
			{
				if ((Object)(object)SpaceLight != (Object)null)
				{
					SpaceLight.SetActive(false);
				}
				if ((Object)(object)terrainfixer != (Object)null)
				{
					terrainfixer.SetActive(false);
				}
				dungeonGeneratorReady = true;
				if (ConfigManager.Instance.FindItemValue<bool>("SettingsDebug"))
				{
					foreach (ConfigItem item in ConfigManager.Instance.GetAll())
					{
						Log.LogInfo((object)"==========");
						Log.LogInfo((object)item.Key);
						Log.LogInfo(item.Value);
						Log.LogInfo(item.DefaultValue);
						Log.LogInfo((object)item.Sync);
					}
				}
			}
			if (!(((Scene)(ref scene)).name == "InitSceneLaunchOptions") || !isInGame)
			{
				return;
			}
			if ((Object)(object)SpaceLight != (Object)null)
			{
				SpaceLight.SetActive(false);
			}
			if ((Object)(object)terrainfixer != (Object)null)
			{
				terrainfixer.SetActive(false);
			}
			GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects();
			foreach (GameObject val6 in rootGameObjects)
			{
				val6.SetActive(false);
			}
			if (ConfigManager.Instance.FindItemValue<bool>("SettingsDebug"))
			{
				foreach (ConfigItem item2 in ConfigManager.Instance.GetAll())
				{
					Log.LogInfo((object)"==========");
					Log.LogInfo((object)item2.Key);
					Log.LogInfo(item2.Value);
					Log.LogInfo(item2.DefaultValue);
					Log.LogInfo((object)item2.Sync);
				}
			}
			if (ConfigManager.Instance.FindItemValue<bool>("LegacyMoonLoading"))
			{
				LoadCustomMoon(scene).RunSynchronously();
			}
			else
			{
				LoadCustomMoon(scene).GetAwaiter();
			}
		}

		private async Task LoadCustomMoon(Scene scene)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			await Task.Delay(400);
			try
			{
				if ((Object)(object)Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab != (Object)null && (Object)(object)Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab.transform != (Object)null)
				{
					CheckRiskyComponents(Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab.transform, Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MoonName);
					GameObject mainPrefab = Object.Instantiate<GameObject>(Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab);
					currentWaterSurface = mainPrefab.transform.Find("Environment/Water");
					if ((Object)(object)mainPrefab != (Object)null)
					{
						SceneManager.MoveGameObjectToScene(mainPrefab, scene);
						Transform DiageticBackground = mainPrefab.transform.Find("Systems/Audio/DiageticBackground");
						if ((Object)(object)DiageticBackground != (Object)null)
						{
							((Component)DiageticBackground).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null);
						}
						Terrain[] Terrains = mainPrefab.GetComponentsInChildren<Terrain>();
						if (Terrains != null && Terrains.Length != 0)
						{
							Terrain[] array = Terrains;
							foreach (Terrain terrain in array)
							{
								terrain.drawInstanced = true;
							}
						}
					}
				}
				string[] _tmp = new string[5] { "MapPropsContainer", "OutsideAINode", "SpawnDenialPoint", "ItemShipLandingNode", "OutsideLevelNavMesh" };
				string[] array2 = _tmp;
				foreach (string s in array2)
				{
					if ((Object)(object)GameObject.FindGameObjectWithTag(s) == (Object)null || GameObject.FindGameObjectsWithTag(s).Any(delegate(GameObject o)
					{
						//IL_0001: Unknown result type (might be due to invalid IL or missing references)
						//IL_0006: Unknown result type (might be due to invalid IL or missing references)
						Scene scene2 = o.scene;
						return ((Scene)(ref scene2)).name != "InitSceneLaunchOptions";
					}))
					{
						GameObject obj = new GameObject();
						((Object)obj).name = s;
						obj.tag = s;
						obj.transform.position = new Vector3(0f, -200f, 0f);
						SceneManager.MoveGameObjectToScene(obj, scene);
					}
				}
				await Task.Delay(200);
				GameObject DropShip = GameObject.Find("ItemShipAnimContainer");
				if ((Object)(object)DropShip != (Object)null)
				{
					Transform ItemShip = DropShip.transform.Find("ItemShip");
					if ((Object)(object)ItemShip != (Object)null)
					{
						((Component)ItemShip).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null);
					}
					Transform ItemShipMusicClose = DropShip.transform.Find("ItemShip/Music");
					if ((Object)(object)ItemShipMusicClose != (Object)null)
					{
						((Component)ItemShipMusicClose).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null);
					}
					Transform ItemShipMusicFar = DropShip.transform.Find("ItemShip/Music/Music (1)");
					if ((Object)(object)ItemShipMusicFar != (Object)null)
					{
						((Component)ItemShipMusicFar).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null);
					}
				}
				await Task.Delay(200);
				RuntimeDungeon runtimeDungeon2 = Object.FindObjectOfType<RuntimeDungeon>(false);
				if ((Object)(object)runtimeDungeon2 == (Object)null)
				{
					GameObject dungeonGenerator = new GameObject();
					((Object)dungeonGenerator).name = "DungeonGenerator";
					dungeonGenerator.tag = "DungeonGenerator";
					dungeonGenerator.transform.position = new Vector3(0f, -200f, 0f);
					runtimeDungeon2 = dungeonGenerator.AddComponent<RuntimeDungeon>();
					runtimeDungeon2.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0];
					runtimeDungeon2.Generator.LengthMultiplier = 0.8f;
					runtimeDungeon2.Generator.PauseBetweenRooms = 0.2f;
					runtimeDungeon2.GenerateOnStart = false;
					runtimeDungeon2.Root = dungeonGenerator;
					runtimeDungeon2.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0];
					UnityNavMeshAdapter dungeonNavMesh = dungeonGenerator.AddComponent<UnityNavMeshAdapter>();
					dungeonNavMesh.BakeMode = (RuntimeNavMeshBakeMode)3;
					dungeonNavMesh.LayerMask = LayerMask.op_Implicit(35072);
					SceneManager.MoveGameObjectToScene(dungeonGenerator, scene);
				}
				else if ((Object)(object)runtimeDungeon2.Generator.DungeonFlow == (Object)null)
				{
					runtimeDungeon2.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0];
				}
				dungeonGeneratorReady = true;
				GameObject OutOfBounds = GameObject.CreatePrimitive((PrimitiveType)3);
				((Object)OutOfBounds).name = "OutOfBounds";
				OutOfBounds.layer = 13;
				OutOfBounds.transform.position = new Vector3(0f, -300f, 0f);
				OutOfBounds.transform.localScale = new Vector3(1000f, 5f, 1000f);
				BoxCollider boxCollider = OutOfBounds.GetComponent<BoxCollider>();
				((Collider)boxCollider).isTrigger = true;
				OutOfBounds.AddComponent<OutOfBoundsTrigger>();
				Rigidbody rigidbody = OutOfBounds.AddComponent<Rigidbody>();
				rigidbody.useGravity = false;
				rigidbody.isKinematic = true;
				rigidbody.collisionDetectionMode = (CollisionDetectionMode)1;
				SceneManager.MoveGameObjectToScene(OutOfBounds, scene);
				await Task.Delay(200);
			}
			catch (Exception ex2)
			{
				Exception ex = ex2;
				Log.LogError((object)ex);
			}
		}

		private void CheckRiskyComponents(Transform root, string objname)
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			try
			{
				Component[] components = ((Component)root).GetComponents<Component>();
				Component[] array = components;
				foreach (Component component in array)
				{
					if (!ComponentWhitelists.moonPrefabWhitelist.Any((Type whitelistType) => ((object)component).GetType() == whitelistType))
					{
						Log.LogWarning((object)(((object)component).GetType().Name + " component is not native of Unity or LethalSDK. It can contains malwares. From " + objname + "."));
					}
				}
				foreach (Transform item in root)
				{
					Transform root2 = item;
					CheckRiskyComponents(root2, objname);
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)ex.Message);
			}
		}

		private void OnSceneUnloaded(Scene scene)
		{
			if (((Scene)(ref scene)).name.Length > 0)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Unloading scene: " + ((Scene)(ref scene)).name));
			}
			if (((Scene)(ref scene)).name.StartsWith("Level") || ((Scene)(ref scene)).name == "CompanyBuilding" || (((Scene)(ref scene)).name == "InitSceneLaunchOptions" && isInGame))
			{
				if ((Object)(object)SpaceLight != (Object)null)
				{
					SpaceLight.SetActive(true);
				}
				if ((Object)(object)currentWaterSurface != (Object)null)
				{
					currentWaterSurface = null;
				}
				dungeonGeneratorReady = false;
				Terminal_Patch.ResetFireExitAmounts();
			}
		}

		private async Task waitForSession()
		{
			while (sessionWaiting)
			{
				await Task.Delay(1000);
			}
			if (!ishost)
			{
				while (!sessionWaiting && hostDataWaiting)
				{
					NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.request, "hostconfig", string.Empty, 0L);
					await Task.Delay(3000);
				}
			}
			else
			{
				for (int i = 0; i < ConfigManager.Instance.GetAll().Count; i++)
				{
					if (ConfigManager.Instance.MustBeSync(i))
					{
						ConfigManager.Instance.SetItemValue(i, ConfigManager.Instance.FindEntryValue(i));
					}
				}
			}
			bool patchGlobalTimeSpeedMultiplier = true;
			bool patchNumberOfHours = true;
			bool patchDeadlineDaysAmount = true;
			bool patchStartingQuota = true;
			bool patchStartingCredits = true;
			bool patchBaseIncrease = true;
			bool patchIncreaseSteepness = true;
			bool patchScrapValueMultiplier = true;
			bool patchScrapAmountMultiplier = true;
			bool patchMapSizeMultiplier = true;
			bool patchMaxShipItemCapacity = true;
			if (ConfigManager.Instance.FindItemValue<bool>("BrutalCompanyPlusCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "BrutalCompanyPlus"))
			{
				patchDeadlineDaysAmount = false;
				patchStartingQuota = false;
				patchStartingCredits = false;
				patchBaseIncrease = false;
				patchIncreaseSteepness = false;
			}
			if (ConfigManager.Instance.FindItemValue<bool>("LethalAdjustmentsCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "LethalAdjustments"))
			{
				patchScrapValueMultiplier = false;
				patchScrapAmountMultiplier = false;
				patchMapSizeMultiplier = false;
			}
			if (ConfigManager.Instance.FindItemValue<bool>("CoomfyDungeonCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "CoomfyDungeon"))
			{
				patchScrapAmountMultiplier = false;
				patchMapSizeMultiplier = false;
			}
			if (ConfigManager.Instance.FindItemValue<bool>("MoreMoneyStartCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "299792458.MoreMoneyStart"))
			{
				patchStartingCredits = false;
			}
			if (patchGlobalTimeSpeedMultiplier)
			{
				TimeOfDay.Instance.globalTimeSpeedMultiplier = ConfigManager.Instance.FindItemValue<float>("GlobalTimeSpeedMultiplier");
			}
			if (patchNumberOfHours)
			{
				TimeOfDay.Instance.numberOfHours = ConfigManager.Instance.FindItemValue<int>("NumberOfHours");
			}
			if (patchDeadlineDaysAmount)
			{
				TimeOfDay.Instance.quotaVariables.deadlineDaysAmount = ConfigManager.Instance.FindItemValue<int>("DeadlineDaysAmount");
			}
			if (patchStartingQuota)
			{
				TimeOfDay.Instance.quotaVariables.startingQuota = ConfigManager.Instance.FindItemValue<int>("StartingQuota");
			}
			if (patchStartingCredits)
			{
				TimeOfDay.Instance.quotaVariables.startingCredits = ConfigManager.Instance.FindItemValue<int>("StartingCredits");
			}
			if (patchBaseIncrease)
			{
				TimeOfDay.Instance.quotaVariables.baseIncrease = ConfigManager.Instance.FindItemValue<int>("QuotaBaseIncrease");
			}
			if (patchIncreaseSteepness)
			{
				TimeOfDay.Instance.quotaVariables.increaseSteepness = ConfigManager.Instance.FindItemValue<int>("QuotaIncreaseSteepness");
			}
			if (patchScrapValueMultiplier)
			{
				RoundManager.Instance.scrapValueMultiplier = ConfigManager.Instance.FindItemValue<float>("ScrapValueMultiplier");
			}
			if (patchScrapAmountMultiplier)
			{
				RoundManager.Instance.scrapAmountMultiplier = ConfigManager.Instance.FindItemValue<float>("ScrapAmountMultiplier");
			}
			if (patchMapSizeMultiplier)
			{
				RoundManager.Instance.mapSizeMultiplier = ConfigManager.Instance.FindItemValue<float>("MapSizeMultiplier");
			}
			if (patchMaxShipItemCapacity)
			{
				StartOfRound.Instance.maxShipItemCapacity = ConfigManager.Instance.FindItemValue<int>("MaxItemsInShip");
			}
			if (!alreadypatched)
			{
				Terminal_Patch.MainPatch(GameObject.Find("TerminalScript").GetComponent<Terminal>());
				alreadypatched = true;
			}
		}

		private void ConfigSettingChanged(object sender, EventArgs e)
		{
			SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null);
			if (val != null)
			{
				Log.LogInfo((object)$"{val.ChangedSetting.Definition.Key} Changed to {val.ChangedSetting.BoxedValue}");
			}
		}
	}
}
namespace LethalExpansion.Utils
{
	public class AssetBundlesManager
	{
		private static AssetBundlesManager _instance;

		public AssetBundle mainAssetBundle = AssetBundle.LoadFromFile(Assembly.GetExecutingAssembly().Location.Replace("LethalExpansion.dll", "lethalexpansion.lem"));

		public Dictionary<string, (AssetBundle, ModManifest)> assetBundles = new Dictionary<string, (AssetBundle, ModManifest)>();

		public readonly string[] forcedNative = new string[1] { "lethalexpansion" };

		public DirectoryInfo modPath = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);

		public DirectoryInfo modDirectory;

		public DirectoryInfo pluginsDirectory;

		public static AssetBundlesManager Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new AssetBundlesManager();
				}
				return _instance;
			}
		}

		public (AssetBundle, ModManifest) Load(string name)
		{
			return assetBundles[name.ToLower()];
		}

		public void LoadAllAssetBundles()
		{
			modDirectory = modPath.Parent;
			pluginsDirectory = modDirectory;
			while (pluginsDirectory != null && pluginsDirectory.Name != "plugins")
			{
				pluginsDirectory = pluginsDirectory.Parent;
			}
			if (pluginsDirectory != null)
			{
				LethalExpansion.Log.LogInfo((object)("Plugins folder found: " + pluginsDirectory.FullName));
				LethalExpansion.Log.LogInfo((object)("Mod path is: " + modDirectory.FullName));
				if (modDirectory.FullName == pluginsDirectory.FullName)
				{
					LethalExpansion.Log.LogWarning((object)("LethalExpansion is Rooting the Plugins folder, this is not recommended. " + modDirectory.FullName));
				}
				string[] files = Directory.GetFiles(pluginsDirectory.FullName, "*.lem", SearchOption.AllDirectories);
				foreach (string file in files)
				{
					LoadBundle(file);
				}
			}
			else
			{
				LethalExpansion.Log.LogWarning((object)"Mod is not in a plugins folder.");
			}
		}

		public void LoadBundle(string file)
		{
			if (forcedNative.Contains<string>(Path.GetFileNameWithoutExtension(file)) && !file.Contains(modDirectory.FullName))
			{
				LethalExpansion.Log.LogWarning((object)("Illegal usage of reserved Asset Bundle name: " + Path.GetFileNameWithoutExtension(file) + " at: " + file + "."));
			}
			else
			{
				if (!(Path.GetFileName(file) != "lethalexpansion.lem"))
				{
					return;
				}
				if (!assetBundles.ContainsKey(Path.GetFileNameWithoutExtension(file)))
				{
					Stopwatch stopwatch = new Stopwatch();
					AssetBundle val = null;
					try
					{
						stopwatch.Start();
						val = AssetBundle.LoadFromFile(file);
						stopwatch.Stop();
					}
					catch (Exception ex)
					{
						LethalExpansion.Log.LogError((object)ex);
					}
					if ((Object)(object)val != (Object)null)
					{
						string text = "Assets/Mods/" + Path.GetFileNameWithoutExtension(file) + "/ModManifest.asset";
						ModManifest modManifest = val.LoadAsset<ModManifest>(text);
						if ((Object)(object)modManifest != (Object)null)
						{
							if (forcedNative.Contains(modManifest.modName.ToLower()) && !file.Contains(modDirectory.FullName))
							{
								LethalExpansion.Log.LogWarning((object)("Illegal usage of reserved Mod name: " + modManifest.modName));
								val.Unload(true);
								LethalExpansion.Log.LogInfo((object)("AssetBundle unloaded: " + Path.GetFileName(file)));
							}
							else if (!assetBundles.Any((KeyValuePair<string, (AssetBundle, ModManifest)> b) => b.Value.Item2.modName == modManifest.modName))
							{
								LethalExpansion.Log.LogInfo((object)string.Format("Module found: {0} v{1} Loaded in {2}ms", modManifest.modName, (modManifest.GetVersion() != null) ? ((object)modManifest.GetVersion()).ToString() : "0.0.0.0", stopwatch.ElapsedMilliseconds));
								if (modManifest.GetVersion() == null || ((object)modManifest.GetVersion()).ToString() == "0.0.0.0")
								{
									LethalExpansion.Log.LogWarning((object)("Module " + modManifest.modName + " have no version number, this is unsafe!"));
								}
								assetBundles.Add(Path.GetFileNameWithoutExtension(file).ToLower(), (val, modManifest));
							}
							else
							{
								LethalExpansion.Log.LogWarning((object)("Another mod with same name is already loaded: " + modManifest.modName));
								val.Unload(true);
								LethalExpansion.Log.LogInfo((object)("AssetBundle unloaded: " + Path.GetFileName(file)));
							}
						}
						else
						{
							LethalExpansion.Log.LogWarning((object)("AssetBundle have no ModManifest: " + Path.GetFileName(file)));
							val.Unload(true);
							LethalExpansion.Log.LogInfo((object)("AssetBundle unloaded: " + Path.GetFileName(file)));
						}
					}
					else
					{
						LethalExpansion.Log.LogWarning((object)("File is not an AssetBundle: " + Path.GetFileName(file)));
					}
				}
				else
				{
					LethalExpansion.Log.LogWarning((object)("AssetBundle with same name already loaded: " + Path.GetFileName(file)));
				}
			}
		}

		public bool BundleLoaded(string bundleName)
		{
			return assetBundles.ContainsKey(bundleName.ToLower());
		}

		public bool BundlesLoaded(string[] bundleNames)
		{
			foreach (string text in bundleNames)
			{
				if (!assetBundles.ContainsKey(text.ToLower()))
				{
					return false;
				}
			}
			return true;
		}

		public bool IncompatibleBundlesLoaded(string[] bundleNames)
		{
			foreach (string text in bundleNames)
			{
				if (assetBundles.ContainsKey(text.ToLower()))
				{
					return true;
				}
			}
			return false;
		}
	}
	public class AssetGather
	{
		private static AssetGather _instance;

		public Dictionary<string, AudioClip> audioClips = new Dictionary<string, AudioClip>();

		public Dictionary<string, (AudioMixer, AudioMixerGroup[])> audioMixers = new Dictionary<string, (AudioMixer, AudioMixerGroup[])>();

		public Dictionary<string, GameObject> planetPrefabs = new Dictionary<string, GameObject>();

		public Dictionary<string, GameObject> mapObjects = new Dictionary<string, GameObject>();

		public Dictionary<string, SpawnableOutsideObject> outsideObjects = new Dictionary<string, SpawnableOutsideObject>();

		public Dictionary<string, Item> scraps = new Dictionary<string, Item>();

		public Dictionary<string, LevelAmbienceLibrary> levelAmbiances = new Dictionary<string, LevelAmbienceLibrary>();

		public Dictionary<string, EnemyType> enemies = new Dictionary<string, EnemyType>();

		public Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();

		public static AssetGather Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new AssetGather();
				}
				return _instance;
			}
		}

		public void GetList()
		{
			LethalExpansion.Log.LogInfo((object)"===Audio Clips===");
			foreach (KeyValuePair<string, AudioClip> audioClip in audioClips)
			{
				LethalExpansion.Log.LogInfo((object)audioClip.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Audio Mixers===");
			foreach (KeyValuePair<string, (AudioMixer, AudioMixerGroup[])> audioMixer in audioMixers)
			{
				LethalExpansion.Log.LogInfo((object)audioMixer.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Planet Prefabs===");
			foreach (KeyValuePair<string, GameObject> planetPrefab in planetPrefabs)
			{
				LethalExpansion.Log.LogInfo((object)planetPrefab.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Map Objects===");
			foreach (KeyValuePair<string, GameObject> mapObject in mapObjects)
			{
				LethalExpansion.Log.LogInfo((object)mapObject.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Outside Objects===");
			foreach (KeyValuePair<string, SpawnableOutsideObject> outsideObject in outsideObjects)
			{
				LethalExpansion.Log.LogInfo((object)outsideObject.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Scraps===");
			foreach (KeyValuePair<string, Item> scrap in scraps)
			{
				LethalExpansion.Log.LogInfo((object)scrap.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Level Ambiances===");
			foreach (KeyValuePair<string, LevelAmbienceLibrary> levelAmbiance in levelAmbiances)
			{
				LethalExpansion.Log.LogInfo((object)levelAmbiance.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Enemies===");
			foreach (KeyValuePair<string, EnemyType> enemy in enemies)
			{
				LethalExpansion.Log.LogInfo((object)enemy.Key);
			}
			LethalExpansion.Log.LogInfo((object)"===Sprites===");
			foreach (KeyValuePair<string, Sprite> sprite in sprites)
			{
				LethalExpansion.Log.LogInfo((object)sprite.Key);
			}
		}

		public void AddAudioClip(AudioClip clip)
		{
			if ((Object)(object)clip != (Object)null && !audioClips.ContainsKey(((Object)clip).name) && !audioClips.ContainsValue(clip))
			{
				audioClips.Add(((Object)clip).name, clip);
			}
		}

		public void AddAudioClip(string name, AudioClip clip)
		{
			if ((Object)(object)clip != (Object)null && !audioClips.ContainsKey(name) && !audioClips.ContainsValue(clip))
			{
				audioClips.Add(name, clip);
			}
		}

		public void AddAudioClip(AudioClip[] clips)
		{
			foreach (AudioClip val in clips)
			{
				if ((Object)(object)val != (Object)null && !audioClips.ContainsKey(((Object)val).name) && !audioClips.ContainsValue(val))
				{
					audioClips.Add(((Object)val).name, val);
				}
			}
		}

		public void AddAudioClip(string[] names, AudioClip[] clips)
		{
			for (int i = 0; i < clips.Length && i < names.Length; i++)
			{
				if ((Object)(object)clips[i] != (Object)null && !audioClips.ContainsKey(names[i]) && !audioClips.ContainsValue(clips[i]))
				{
					audioClips.Add(names[i], clips[i]);
				}
			}
		}

		public void AddAudioMixer(AudioMixer mixer)
		{
			if (!((Object)(object)mixer != (Object)null) || audioMixers.ContainsKey(((Object)mixer).name))
			{
				return;
			}
			List<AudioMixerGroup> list = new List<AudioMixerGroup>();
			AudioMixerGroup[] array = mixer.FindMatchingGroups(string.Empty);
			foreach (AudioMixerGroup val in array)
			{
				if ((Object)(object)val != (Object)null && !list.Contains(val))
				{
					list.Add(val);
				}
			}
			audioMixers.Add(((Object)mixer).name, (mixer, list.ToArray()));
		}

		public void AddPlanetPrefabs(GameObject prefab)
		{
			if ((Object)(object)prefab != (Object)null && !planetPrefabs.ContainsKey(((Object)prefab).name) && !planetPrefabs.ContainsValue(prefab))
			{
				planetPrefabs.Add(((Object)prefab).name, prefab);
			}
		}

		public void AddPlanetPrefabs(string name, GameObject prefab)
		{
			if ((Object)(object)prefab != (Object)null && !planetPrefabs.ContainsKey(name) && !planetPrefabs.ContainsValue(prefab))
			{
				planetPrefabs.Add(name, prefab);
			}
		}

		public void AddMapObjects(GameObject mapObject)
		{
			if ((Object)(object)mapObject != (Object)null && !mapObjects.ContainsKey(((Object)mapObject).name) && !mapObjects.ContainsValue(mapObject))
			{
				mapObjects.Add(((Object)mapObject).name, mapObject);
			}
		}

		public void AddOutsideObject(SpawnableOutsideObject outsideObject)
		{
			if ((Object)(object)outsideObject != (Object)null && !outsideObjects.ContainsKey(((Object)outsideObject).name) && !outsideObjects.ContainsValue(outsideObject))
			{
				outsideObjects.Add(((Object)outsideObject).name, outsideObject);
			}
		}

		public void AddScrap(Item scrap)
		{
			if ((Object)(object)scrap != (Object)null && !scraps.ContainsKey(((Object)scrap).name) && !scraps.ContainsValue(scrap))
			{
				scraps.Add(((Object)scrap).name, scrap);
			}
		}

		public void AddLevelAmbiances(LevelAmbienceLibrary levelAmbiance)
		{
			if ((Object)(object)levelAmbiance != (Object)null && !levelAmbiances.ContainsKey(((Object)levelAmbiance).name) && !levelAmbiances.ContainsValue(levelAmbiance))
			{
				levelAmbiances.Add(((Object)levelAmbiance).name, levelAmbiance);
			}
		}

		public void AddEnemies(EnemyType enemie)
		{
			if ((Object)(object)enemie != (Object)null && !enemies.ContainsKey(((Object)enemie).name) && !enemies.ContainsValue(enemie))
			{
				enemies.Add(((Object)enemie).name, enemie);
			}
		}

		public void AddSprites(Sprite sprite)
		{
			if ((Object)(object)sprite != (Object)null && !sprites.ContainsKey(((Object)sprite).name) && !sprites.ContainsValue(sprite))
			{
				sprites.Add(((Object)sprite).name, sprite);
			}
		}

		public void AddSprites(string name, Sprite sprite)
		{
			if ((Object)(object)sprite != (Object)null && !sprites.ContainsKey(name) && !sprites.ContainsValue(sprite))
			{
				sprites.Add(name, sprite);
			}
		}
	}
	public class ChatMessageProcessor
	{
		public static bool ProcessMessage(string message)
		{
			if (Regex.IsMatch(message, "^\\[sync\\].*\\[sync\\]$"))
			{
				try
				{
					string value = Regex.Match(message, "^\\[sync\\](.*)\\[sync\\]$").Groups[1].Value;
					string[] array = value.Split('|');
					if (array.Length == 3)
					{
						NetworkPacketManager.packetType packetType = (NetworkPacketManager.packetType)int.Parse(array[0]);
						string[] array2 = array[1].Split('>');
						ulong num = ulong.Parse(array2[0]);
						long num2 = long.Parse(array2[1]);
						string[] array3 = array[2].Split('=');
						string header = array3[0];
						string packet = array3[1];
						if (num2 == -1 || num2 == (long)((NetworkBehaviour)RoundManager.Instance).NetworkManager.LocalClientId)
						{
							if (num != 0)
							{
								NetworkPacketManager.Instance.CancelTimeout((long)num);
							}
							LethalExpansion.Log.LogInfo((object)message);
							switch (packetType)
							{
							case NetworkPacketManager.packetType.request:
								ProcessRequest(num, header, packet);
								break;
							case NetworkPacketManager.packetType.data:
								ProcessData(num, header, packet);
								break;
							case NetworkPacketManager.packetType.other:
								LethalExpansion.Log.LogInfo((object)"Unsupported type.");
								break;
							default:
								LethalExpansion.Log.LogInfo((object)"Unrecognized type.");
								break;
							}
						}
					}
					return true;
				}
				catch (Exception ex)
				{
					LethalExpansion.Log.LogError((object)ex);
					return false;
				}
			}
			return false;
		}

		private static void ProcessRequest(ulong sender, string header, string packet)
		{
			try
			{
				switch (header)
				{
				case "clientinfo":
				{
					if (LethalExpansion.ishost || sender != 0)
					{
						break;
					}
					string text2 = LethalExpansion.ModVersion.ToString() + "$";
					foreach (KeyValuePair<string, (AssetBundle, ModManifest)> assetBundle in AssetBundlesManager.Instance.assetBundles)
					{
						text2 = text2 + assetBundle.Key + "v" + ((object)assetBundle.Value.Item2.GetVersion()).ToString() + "&";
					}
					text2 = text2.Remove(text2.Length - 1);
					NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "clientinfo", text2, 0L);
					break;
				}
				case "hostconfig":
					if (LethalExpansion.ishost && sender != 0)
					{
						NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.request, "clientinfo", string.Empty, (long)sender);
					}
					break;
				case "hostweathers":
					if (LethalExpansion.ishost && sender != 0L && LethalExpansion.weathersReadyToShare)
					{
						string text = string.Empty;
						int[] currentWeathers = StartOfRound_Patch.currentWeathers;
						foreach (int num in currentWeathers)
						{
							text = text + num + "&";
						}
						text = text.Remove(text.Length - 1);
						NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "hostweathers", text, (long)sender, waitForAnswer: false);
					}
					break;
				default:
					LethalExpansion.Log.LogInfo((object)"Unrecognized command.");
					break;
				}
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex);
			}
		}

		private static void ProcessData(ulong sender, string header, string packet)
		{
			//IL_04de: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				switch (header)
				{
				case "clientinfo":
				{
					if (!LethalExpansion.ishost || sender == 0)
					{
						break;
					}
					string[] array = ((!packet.Contains('$')) ? new string[1] { packet } : packet.Split('$'));
					string text = string.Empty;
					foreach (KeyValuePair<string, (AssetBundle, ModManifest)> assetBundle in AssetBundlesManager.Instance.assetBundles)
					{
						text = text + assetBundle.Key + "v" + ((object)assetBundle.Value.Item2.GetVersion()).ToString() + "&";
					}
					if (text.Length > 0)
					{
						text = text.Remove(text.Length - 1);
					}
					if (array[0] != LethalExpansion.ModVersion.ToString())
					{
						if (StartOfRound.Instance.ClientPlayerList.ContainsKey(sender))
						{
							LethalExpansion.Log.LogError((object)$"Kicking {sender} for wrong version.");
							NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "kickreason", "Wrong version.", (long)sender);
							StartOfRound.Instance.KickPlayer(StartOfRound.Instance.ClientPlayerList[sender]);
						}
						break;
					}
					if (array.Length > 1 && array[1] != text)
					{
						if (StartOfRound.Instance.ClientPlayerList.ContainsKey(sender))
						{
							LethalExpansion.Log.LogError((object)$"Kicking {sender} for wrong bundles.");
							NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "kickreason", "Wrong bundles.", (long)sender);
							StartOfRound.Instance.KickPlayer(StartOfRound.Instance.ClientPlayerList[sender]);
						}
						break;
					}
					string text2 = string.Empty;
					foreach (ConfigItem item in ConfigManager.Instance.GetAll())
					{
						switch (item.type.Name)
						{
						case "Int32":
							text2 = text2 + "i" + ((int)item.Value).ToString(CultureInfo.InvariantCulture);
							break;
						case "Single":
							text2 = text2 + "f" + ((float)item.Value).ToString(CultureInfo.InvariantCulture);
							break;
						case "Boolean":
							text2 = text2 + "b" + (bool)item.Value;
							break;
						case "String":
							text2 = text2 + "s" + item;
							break;
						}
						text2 += "&";
					}
					text2 = text2.Remove(text2.Length - 1);
					NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "hostconfig", text2, (long)sender);
					break;
				}
				case "hostconfig":
				{
					if (LethalExpansion.ishost || sender != 0)
					{
						break;
					}
					string[] array2 = packet.Split('&');
					LethalExpansion.Log.LogInfo((object)("Received host config: " + packet));
					for (int i = 0; i < array2.Length; i++)
					{
						if (i < ConfigManager.Instance.GetCount() && ConfigManager.Instance.MustBeSync(i))
						{
							ConfigManager.Instance.SetItemValue(i, array2[i].Substring(1), array2[i][0]);
						}
					}
					LethalExpansion.hostDataWaiting = false;
					LethalExpansion.Log.LogInfo((object)"Updated config");
					break;
				}
				case "hostweathers":
				{
					if (LethalExpansion.ishost || sender != 0)
					{
						break;
					}
					string[] array3 = packet.Split('&');
					LethalExpansion.Log.LogInfo((object)("Received host weathers: " + packet));
					StartOfRound_Patch.currentWeathers = new int[array3.Length];
					for (int j = 0; j < array3.Length; j++)
					{
						int result = 0;
						if (int.TryParse(array3[j], out result))
						{
							StartOfRound_Patch.currentWeathers[j] = result;
							StartOfRound.Instance.levels[j].currentWeather = (LevelWeatherType)result;
						}
					}
					break;
				}
				case "kickreason":
					if (!LethalExpansion.ishost && sender == 0)
					{
						LethalExpansion.lastKickReason = packet;
					}
					break;
				default:
					LethalExpansion.Log.LogInfo((object)"Unrecognized property.");
					break;
				}
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex);
			}
		}
	}
	public class ComponentWhitelists
	{
		public static List<Type> moonPrefabWhitelist = new List<Type>
		{
			typeof(Transform),
			typeof(MeshFilter),
			typeof(MeshRenderer),
			typeof(SkinnedMeshRenderer),
			typeof(MeshCollider),
			typeof(BoxCollider),
			typeof(SphereCollider),
			typeof(CapsuleCollider),
			typeof(SphereCollider),
			typeof(TerrainCollider),
			typeof(WheelCollider),
			typeof(ArticulationBody),
			typeof(ConstantForce),
			typeof(ConfigurableJoint),
			typeof(FixedJoint),
			typeof(HingeJoint),
			typeof(Cloth),
			typeof(Rigidbody),
			typeof(NetworkObject),
			typeof(NetworkRigidbody),
			typeof(NetworkTransform),
			typeof(NetworkAnimator),
			typeof(Animator),
			typeof(Animation),
			typeof(Terrain),
			typeof(Tree),
			typeof(WindZone),
			typeof(DecalProjector),
			typeof(LODGroup),
			typeof(Light),
			typeof(HDAdditionalLightData),
			typeof(LightProbeGroup),
			typeof(LightProbeProxyVolume),
			typeof(LocalVolumetricFog),
			typeof(OcclusionArea),
			typeof(OcclusionPortal),
			typeof(ReflectionProbe),
			typeof(PlanarReflectionProbe),
			typeof(HDAdditionalReflectionData),
			typeof(Skybox),
			typeof(SortingGroup),
			typeof(SpriteRenderer),
			typeof(Volume),
			typeof(AudioSource),
			typeof(AudioReverbZone),
			typeof(AudioReverbFilter),
			typeof(AudioChorusFilter),
			typeof(AudioDistortionFilter),
			typeof(AudioEchoFilter),
			typeof(AudioHighPassFilter),
			typeof(AudioLowPassFilter),
			typeof(AudioListener),
			typeof(LensFlare),
			typeof(TrailRenderer),
			typeof(LineRenderer),
			typeof(ParticleSystem),
			typeof(ParticleSystemRenderer),
			typeof(ParticleSystemForceField),
			typeof(Projector),
			typeof(VideoPlayer),
			typeof(NavMeshSurface),
			typeof(NavMeshModifier),
			typeof(NavMeshModifierVolume),
			typeof(NavMeshLink),
			typeof(NavMeshObstacle),
			typeof(OffMeshLink),
			typeof(SI_AudioReverbPresets),
			typeof(SI_AudioReverbTrigger),
			typeof(SI_DungeonGenerator),
			typeof(SI_MatchLocalPlayerPosition),
			typeof(SI_AnimatedSun),
			typeof(SI_EntranceTeleport),
			typeof(SI_ScanNode),
			typeof(SI_DoorLock),
			typeof(SI_WaterSurface),
			typeof(SI_Ladder),
			typeof(SI_ItemDropship),
			typeof(SI_NetworkPrefabInstancier),
			typeof(SI_InteractTrigger),
			typeof(SI_DamagePlayer),
			typeof(SI_SoundYDistance),
			typeof(SI_AudioOutputInterface),
			typeof(SI_NetworkDataInterfacing),
			typeof(PlayerShip)
		};

		public static List<Type> scrapWhitelist = new List<Type>
		{
			typeof(Transform),
			typeof(MeshFilter),
			typeof(MeshRenderer),
			typeof(SkinnedMeshRenderer),
			typeof(MeshCollider),
			typeof(BoxCollider),
			typeof(SphereCollider),
			typeof(CapsuleCollider),
			typeof(SphereCollider),
			typeof(TerrainCollider),
			typeof(WheelCollider),
			typeof(ArticulationBody),
			typeof(ConstantForce),
			typeof(ConfigurableJoint),
			typeof(FixedJoint),
			typeof(HingeJoint),
			typeof(Cloth),
			typeof(Rigidbody),
			typeof(NetworkObject),
			typeof(NetworkRigidbody),
			typeof(NetworkTransform),
			typeof(NetworkAnimator),
			typeof(Animator),
			typeof(Animation),
			typeof(DecalProjector),
			typeof(LODGroup),
			typeof(Light),
			typeof(HDAdditionalLightData),
			typeof(LightProbeGroup),
			typeof(LightProbeProxyVolume),
			typeof(LocalVolumetricFog),
			typeof(OcclusionArea),
			typeof(OcclusionPortal),
			typeof(ReflectionProbe),
			typeof(PlanarReflectionProbe),
			typeof(HDAdditionalReflectionData),
			typeof(SortingGroup),
			typeof(SpriteRenderer),
			typeof(AudioSource),
			typeof(AudioReverbZone),
			typeof(AudioReverbFilter),
			typeof(AudioChorusFilter),
			typeof(AudioDistortionFilter),
			typeof(AudioEchoFilter),
			typeof(AudioHighPassFilter),
			typeof(AudioLowPassFilter),
			typeof(AudioListener),
			typeof(LensFlare),
			typeof(TrailRenderer),
			typeof(LineRenderer),
			typeof(ParticleSystem),
			typeof(ParticleSystemRenderer),
			typeof(ParticleSystemForceField),
			typeof(VideoPlayer),
			typeof(SI_DamagePlayer),
			typeof(SI_AudioOutputInterface)
		};
	}
	public class ConfigManager
	{
		private static ConfigManager _instance;

		private List<ConfigItem> items = new List<ConfigItem>();

		private List<ConfigEntryBase> entries = new List<ConfigEntryBase>();

		public static ConfigManager Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new ConfigManager();
				}
				return _instance;
			}
		}

		public void AddItem(ConfigItem item)
		{
			try
			{
				items.Add(item);
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
			}
		}

		public void ReadConfig()
		{
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Expected O, but got Unknown
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Expected O, but got Unknown
			//IL_0308: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Expected O, but got Unknown
			items = (from item in items
				orderby item.Tab, item.Key
				select item).ToList();
			try
			{
				for (int i = 0; i < items.Count; i++)
				{
					if (!items[i].Hidden)
					{
						string description = items[i].Description;
						description = description + "\nNetwork synchronization: " + (items[i].Sync ? "Yes" : "No");
						description = description + "\nMod required by clients: " + (items[i].Optional ? "No" : "Yes");
						switch (items[i].type.Name)
						{
						case "Int32":
							entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<int>(items[i].Tab, items[i].Key, (int)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<int>((int)items[i].MinValue, (int)items[i].MaxValue), Array.Empty<object>())));
							break;
						case "Single":
							entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<float>(items[i].Tab, items[i].Key, (float)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<float>((float)items[i].MinValue, (float)items[i].MaxValue), Array.Empty<object>())));
							break;
						case "Boolean":
							entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<bool>(items[i].Tab, items[i].Key, (bool)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())));
							break;
						case "String":
							entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<string>(items[i].Tab, items[i].Key, (string)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())));
							break;
						}
						if (!items[i].Sync)
						{
							items[i].Value = entries.Last().BoxedValue;
						}
					}
					else
					{
						entries.Add(null);
					}
				}
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
			}
		}

		public object FindItemValue(string key)
		{
			try
			{
				return items.First((ConfigItem item) => item.Key == key).Value;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public object FindItemValue(int index)
		{
			try
			{
				return items[index].Value;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public object FindEntryValue(string key)
		{
			try
			{
				return entries.First((ConfigEntryBase item) => item.Definition.Key == key).BoxedValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public object FindEntryValue(int index)
		{
			try
			{
				return entries[index].BoxedValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public bool RequireRestart(string key)
		{
			try
			{
				return items.First((ConfigItem item) => item.Key == key).RequireRestart;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public bool RequireRestart(int index)
		{
			try
			{
				return items[index].RequireRestart;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public string FindDescription(string key)
		{
			try
			{
				return items.First((ConfigItem item) => item.Key == key).Description;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public string FindDescription(int index)
		{
			try
			{
				return items[index].Description;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public (bool, bool) FindNetInfo(string key)
		{
			try
			{
				ConfigItem configItem = items.First((ConfigItem item) => item.Key == key);
				return (configItem.Sync, configItem.Optional);
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return (false, false);
			}
		}

		public (bool, bool) FindNetInfo(int index)
		{
			try
			{
				return (items[index].Sync, items[index].Optional);
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return (false, false);
			}
		}

		public object FindDefaultValue(string key)
		{
			try
			{
				return items.First((ConfigItem item) => item.Key == key).DefaultValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public object FindDefaultValue(int index)
		{
			try
			{
				return items[index].DefaultValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public bool MustBeSync(string key)
		{
			try
			{
				return items.First((ConfigItem item) => item.Key == key).Sync;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return true;
			}
		}

		public bool MustBeSync(int index)
		{
			try
			{
				return items[index].Sync;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return true;
			}
		}

		public bool SetItemValue(string key, object value)
		{
			ConfigItem configItem = items.First((ConfigItem item) => item.Key == key);
			if (!items.First((ConfigItem item) => item.Key == key).RequireRestart)
			{
				try
				{
					configItem.Value = value;
					return true;
				}
				catch (Exception ex)
				{
					LethalExpansion.Log.LogError((object)ex.Message);
					return false;
				}
			}
			return false;
		}

		public bool SetEntryValue(string key, object value)
		{
			try
			{
				entries.First((ConfigEntryBase item) => item.Definition.Key == key).BoxedValue = value;
				return true;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public bool SetItemValue(int index, string value, char type)
		{
			if (!items[index].RequireRestart)
			{
				try
				{
					switch (type)
					{
					case 'i':
						items[index].Value = int.Parse(value, CultureInfo.InvariantCulture);
						break;
					case 'f':
						items[index].Value = float.Parse(value, CultureInfo.InvariantCulture);
						break;
					case 'b':
						items[index].Value = bool.Parse(value);
						break;
					case 's':
						items[index].Value = value;
						break;
					}
					return true;
				}
				catch (Exception ex)
				{
					LethalExpansion.Log.LogError((object)ex.Message);
					return false;
				}
			}
			return false;
		}

		public bool SetEntryValue(int index, string value, char type)
		{
			try
			{
				switch (type)
				{
				case 'i':
					entries[index].BoxedValue = int.Parse(value);
					break;
				case 'f':
					entries[index].BoxedValue = float.Parse(value);
					break;
				case 'b':
					entries[index].BoxedValue = bool.Parse(value);
					break;
				case 's':
					entries[index].BoxedValue = value;
					break;
				}
				return true;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public (object, int) FindValueAndIndex(string key)
		{
			try
			{
				return (items.First((ConfigItem item) => item.Key == key).Value, items.FindIndex((ConfigItem item) => item.Key == key));
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return (null, -1);
			}
		}

		public int FindIndex(string key)
		{
			try
			{
				return items.FindIndex((ConfigItem item) => item.Key == key);
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return -1;
			}
		}

		public T FindItemValue<T>(string key)
		{
			try
			{
				ConfigItem configItem = items.First((ConfigItem item) => item.Key == key);
				if (configItem != null && configItem.Value is T)
				{
					return (T)configItem.Value;
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return default(T);
			}
		}

		public T FindItemValue<T>(int index)
		{
			try
			{
				ConfigItem configItem = items[index];
				if (configItem != null && configItem.Value is T)
				{
					return (T)configItem.Value;
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return default(T);
			}
		}

		public T FindEntryValue<T>(string key)
		{
			try
			{
				ConfigEntryBase val = entries.First((ConfigEntryBase item) => item.Definition.Key == key);
				if (val != null && val.BoxedValue is T)
				{
					return (T)val.BoxedValue;
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return default(T);
			}
		}

		public T FindEntryValue<T>(int index)
		{
			try
			{
				ConfigEntryBase val = entries[index];
				if (val != null && val.BoxedValue is T)
				{
					return (T)val.BoxedValue;
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return default(T);
			}
		}

		public bool SetItemValue<T>(string key, T value)
		{
			ConfigItem configItem = items.First((ConfigItem item) => item.Key == key);
			if (!configItem.RequireRestart)
			{
				try
				{
					if (configItem == null || !(configItem.Value is T))
					{
						LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
						throw new InvalidOperationException("Key not found or value is of incorrect type");
					}
					configItem.Value = value;
					return true;
				}
				catch (Exception ex)
				{
					LethalExpansion.Log.LogError((object)ex.Message);
					return false;
				}
			}
			return false;
		}

		public bool SetEntryValue<T>(string key, T value)
		{
			try
			{
				ConfigEntryBase val = entries.First((ConfigEntryBase item) => item.Definition.Key == key);
				if (val != null && val.BoxedValue is T)
				{
					val.BoxedValue = value;
					return true;
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public bool SetItemValue<T>(int index, T value)
		{
			if (!items[index].RequireRestart)
			{
				try
				{
					items[index].Value = value;
					return true;
				}
				catch (Exception ex)
				{
					LethalExpansion.Log.LogError((object)ex.Message);
					return false;
				}
			}
			return false;
		}

		public bool SetEntryValue<T>(int index, T value)
		{
			try
			{
				entries[index].BoxedValue = value;
				return true;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public (T, int) FindValueAndIndex<T>(string key)
		{
			try
			{
				ConfigItem configItem = items.First((ConfigItem item) => item.Key == key);
				if (configItem != null && configItem.Value is T)
				{
					return ((T)configItem.Value, items.FindIndex((ConfigItem item) => item.Key == key));
				}
				LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type");
				throw new InvalidOperationException("Key not found or value is of incorrect type");
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return (default(T), -1);
			}
		}

		public List<ConfigItem> GetAll()
		{
			try
			{
				return items;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public int GetCount()
		{
			try
			{
				return items.Count;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return -1;
			}
		}

		public int GetEntriesCount()
		{
			try
			{
				return entries.Count;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return -1;
			}
		}

		public object ReadConfigValue(string key)
		{
			try
			{
				return entries[FindIndex(key)].BoxedValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return null;
			}
		}

		public T ReadConfigValue<T>(string key)
		{
			try
			{
				return (T)entries[FindIndex(key)].BoxedValue;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return default(T);
			}
		}

		public bool WriteConfigValue(string key, object value)
		{
			try
			{
				int index = FindIndex(key);
				SetItemValue(index, value);
				entries[index].BoxedValue = value;
				return true;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}

		public bool WriteConfigValue<T>(string key, T value)
		{
			try
			{
				int index = FindIndex(key);
				SetItemValue(index, value);
				entries[index].BoxedValue = value;
				return true;
			}
			catch (Exception ex)
			{
				LethalExpansion.Log.LogError((object)ex.Message);
				return false;
			}
		}
	}
	public static class ModUtils
	{
		public static T[] RemoveElementFromArray<T>(T[] originalArray, int indexToRemove)
		{
			if (indexToRemove < 0 || indexToRemove >= originalArray.Length)
			{
				throw new ArgumentOutOfRangeException("indexToRemove");
			}
			T[] array = new T[originalArray.Length - 1];
			int i = 0;
			int num = 0;
			for (; i < originalArray.Length; i++)
			{
				if (i != indexToRemove)
				{
					array[num] = originalArray[i];
					num++;
				}
			}
			return array;
		}
	}
	public class NetworkPacketManager
	{
		public enum packetType
		{
			request = 0,
			data = 1,
			other = -1
		}

		private static NetworkPacketManager _instance;

		private ConcurrentDictionary<long, CancellationTokenSource> timeoutDictionary = new ConcurrentDictionary<long, CancellationTokenSource>();

		public static NetworkPacketManager Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new NetworkPacketManager();
				}
				return _instance;
			}
		}

		private NetworkPacketManager()
		{
		}

		public void sendPacket(packetType type, string header, string packet, long destination = -1L, bool waitForAnswer = true)
		{
			HUDManager.Instance.AddTextToChatOnServer($"[sync]{(int)type}|{((NetworkBehaviour)RoundManager.Instance).NetworkManager.LocalClientId}>{destination}|{header}={packet}[sync]", -1);
			if ((waitForAnswer && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && ConfigManager.Instance.FindItemValue<bool>("LoadModules")) || ConfigManager.Instance.FindItemValue<bool>("KickPlayerWithoutMod"))
			{
				StartTimeout(destination);
			}
		}

		public void sendPacket(packetType type, string header, string packet, long[] destinations, bool waitForAnswer = true)
		{
			for (int i = 0; i < destinations.Length; i++)
			{
				int num = (int)destinations[i];
				if (num != -1)
				{
					HUDManager.Instance.AddTextToChatOnServer($"[sync]{(int)type}|{((NetworkBehaviour)RoundManager.Instance).NetworkManager.LocalClientId}>{num}|{header}={packet}[sync]", -1);
					if ((waitForAnswer && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && ConfigManager.Instance.FindItemValue<bool>("LoadModules")) || ConfigManager.Instance.FindItemValue<bool>("KickPlayerWithoutMod"))
					{
						StartTimeout(num);
					}
				}
			}
		}

		public void StartTimeout(long id)
		{
			CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
			if (!timeoutDictionary.TryAdd(id, cancellationTokenSource))
			{
				return;
			}
			Task.Run(async delegate
			{
				try
				{
					await PacketTimeout(id, cancellationTokenSource.Token);
				}
				catch (OperationCanceledException)
				{
				}
				finally
				{
					timeoutDictionary.TryRemove(id, out var _);
				}
			});
		}

		public void CancelTimeout(long id)
		{
			if (timeoutDictionary.TryRemove(id, out var value))
			{
				value.Cancel();
			}
		}

		private async Task PacketTimeout(long id, CancellationToken token)
		{
			await Task.Delay(5000, token);
			if (token.IsCancellationRequested)
			{
			}
		}
	}
	public class PopupManager
	{
		private static PopupManager _instance;

		private List<PopupObject> popups = new List<PopupObject>();

		public static PopupManager Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new PopupManager();
				}
				return _instance;
			}
		}

		private PopupManager()
		{
		}

		public void InstantiatePopup(Scene sceneFocus, string title = "Popup", string content = "", string button1 = "Ok", string button2 = "Cancel", UnityAction button1Action = null, UnityAction button2Action = null, int titlesize = 24, int contentsize = 24, int button1size = 24, int button2size = 24)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Expected O, but got Unknown
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Expected O, but got Unknown
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Expected O, but got Unknown
			if (!((Scene)(ref sceneFocus)).isLoaded)
			{
				return;
			}
			GameObject[] rootGameObjects = ((Scene)(ref sceneFocus)).GetRootGameObjects();
			Canvas val = null;
			GameObject[] array = rootGameObjects;
			foreach (GameObject val2 in array)
			{
				val = val2.GetComponentInChildren<Canvas>();
				if ((Object)(object)val != (Object)null)
				{
					break;
				}
			}
			if ((Object)(object)val == (Object)null || ((Component)val).gameObject.scene != sceneFocus)
			{
				GameObject val3 = new GameObject();
				((Object)val3).name = "Canvas";
				val = val3.AddComponent<Canvas>();
				SceneManager.MoveGameObjectToScene(((Component)val).gameObject, sceneFocus);
			}
			GameObject _tmp = Object.Instantiate<GameObject>(AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Prefabs/HUD/Popup.prefab"), ((Component)val).transform);
			if ((Object)(object)_tmp != (Object)null)
			{
				((Component)_tmp.transform.Find("DragAndDropSurface")).gameObject.AddComponent<SettingMenu_DragAndDrop>().rectTransform = _tmp.GetComponent<RectTransform>();
				((UnityEvent)((Component)_tmp.transform.Find("CloseButton")).gameObject.GetComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					Object.Destroy((Object)(object)_tmp);
				});
				if (button1Action != null)
				{
					((UnityEvent)((Component)_tmp.transform.Find("Button1")).gameObject.GetComponent<Button>().onClick).AddListener(button1Action);
				}
				if (button2Action != null)
				{
					((UnityEvent)((Component)_tmp.transform.Find("Button2")).gameObject.GetComponent<Button>().onClick).AddListener(button2Action);
				}
				((UnityEvent)((Component)_tmp.transform.Find("Button1")).gameObject.GetComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					Object.Destroy((Object)(object)_tmp);
				});
				((UnityEvent)((Component)_tmp.transform.Find("Button2")).gameObject.GetComponent<Button>().onClick).AddListener((UnityAction)delegate
				{
					Object.Destroy((Object)(object)_tmp);
				});
				PopupObject popupObject = new PopupObject(_tmp, ((Component)_tmp.transform.Find("Title")).GetComponent<TMP_Text>(), ((Component)_tmp.transform.Find("Panel/MainContent")).GetComponent<TMP_Text>(), ((Component)_tmp.transform.Find("Button1/Text")).GetComponent<TMP_Text>(), ((Component)_tmp.transform.Find("Button2/Text")).GetComponent<TMP_Text>());
				popupObject.title.text = title;
				popupObject.title.fontSize = titlesize;
				popupObject.content.text = content;
				popupObject.content.fontSize = contentsize;
				popupObject.button1.text = button1;
				popupObject.button1.fontSize = button1size;
				popupObject.button2.text = button2;
				popupObject.button2.fontSize = button2size;
				popups.Add(popupObject);
			}
		}
	}
	public class PopupObject
	{
		public GameObject baseObject;

		public TMP_Text title;

		public TMP_Text content;

		public TMP_Text button1;

		public TMP_Text button2;

		public PopupObject(GameObject baseObject, TMP_Text title, TMP_Text content, TMP_Text button1, TMP_Text button2)
		{
			this.baseObject = baseObject;
			this.title = title;
			this.content = content;
			this.button1 = button1;
			this.button2 = button2;
		}
	}
	public class VersionChecker
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static UnityAction <>9__1_0;

			internal void <CompareVersions>b__1_0()
			{
				Application.OpenURL("https://thunderstore.io/c/lethal-company/p/HolographicWings/LethalExpansion/");
			}
		}

		public static async Task CheckVersion()
		{
			using HttpClient httpClient = new HttpClient();
			try
			{
				CompareVersions(await httpClient.GetStringAsync("https://raw.githubusercontent.com/HolographicWings/LethalExpansion/main/last.txt"));
			}
			catch (HttpRequestException ex2)
			{
				HttpRequestException ex = ex2;
				LethalExpansion.Log.LogError((object)ex.Message);
			}
		}

		pri

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/LethalLib/LethalLib.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using LethalLib.Extras;
using LethalLib.Modules;
using LethalLib.NetcodePatcher;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using On;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Audio;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: AssemblyCompany("Evaisa")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Content-addition API for Lethal Company")]
[assembly: AssemblyFileVersion("0.12.1.0")]
[assembly: AssemblyInformationalVersion("0.12.1+393793bdff10617b3adaa1b731ba64d982de5c23")]
[assembly: AssemblyProduct("LethalLib")]
[assembly: AssemblyTitle("LethalLib")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/EvaisaDev/LethalLib")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LethalLib
{
	[BepInPlugin("evaisa.lethallib", "LethalLib", "0.12.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "evaisa.lethallib";

		public const string ModName = "LethalLib";

		public const string ModVersion = "0.12.1";

		public static AssetBundle MainAssets;

		public static ManualLogSource logger;

		public static ConfigFile config;

		public static Plugin Instance;

		private void Awake()
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			config = ((BaseUnityPlugin)this).Config;
			logger = ((BaseUnityPlugin)this).Logger;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalLib loaded!!");
			MainAssets = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "lethallib"));
			new ILHook((MethodBase)typeof(StackTrace).GetMethod("AddFrames", BindingFlags.Instance | BindingFlags.NonPublic), new Manipulator(IlHook));
			Enemies.Init();
			Items.Init();
			Unlockables.Init();
			MapObjects.Init();
			Dungeon.Init();
			Weathers.Init();
			Player.Init();
			Utilities.Init();
			NetworkPrefabs.Init();
		}

		private void IlHook(ILContext il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			ILCursor val = new ILCursor(il);
			val.GotoNext(new Func<Instruction, bool>[1]
			{
				(Instruction x) => ILPatternMatchingExt.MatchCallvirt(x, (MethodBase)typeof(StackFrame).GetMethod("GetFileLineNumber", BindingFlags.Instance | BindingFlags.Public))
			});
			val.RemoveRange(2);
			val.EmitDelegate<Func<StackFrame, string>>((Func<StackFrame, string>)GetLineOrIL);
		}

		private static string GetLineOrIL(StackFrame instance)
		{
			int fileLineNumber = instance.GetFileLineNumber();
			if (fileLineNumber == -1 || fileLineNumber == 0)
			{
				return "IL_" + instance.GetILOffset().ToString("X4");
			}
			return fileLineNumber.ToString();
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "LethalLib";

		public const string PLUGIN_NAME = "LethalLib";

		public const string PLUGIN_VERSION = "0.12.1";
	}
}
namespace LethalLib.Modules
{
	public class ContentLoader
	{
		public class CustomContent
		{
			private string id = "";

			public string ID => id;

			public CustomContent(string id)
			{
				this.id = id;
			}
		}

		public class CustomItem : CustomContent
		{
			public Action<Item> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal Item item;

			public Item Item => item;

			public CustomItem(string id, string contentPath, Action<Item> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
			}
		}

		public class ShopItem : CustomItem
		{
			public int initPrice;

			public string buyNode1Path;

			public string buyNode2Path;

			public string itemInfoPath;

			public void RemoveFromShop()
			{
				Items.RemoveShopItem(base.Item);
			}

			public void SetPrice(int price)
			{
				Items.UpdateShopItemPrice(base.Item, price);
			}

			public ShopItem(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, Action<Item> registryCallback = null)
				: base(id, contentPath, registryCallback)
			{
				initPrice = price;
				this.buyNode1Path = buyNode1Path;
				this.buyNode2Path = buyNode2Path;
				this.itemInfoPath = itemInfoPath;
			}
		}

		public class ScrapItem : CustomItem
		{
			public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>();

			public Dictionary<string, int> customLevelRarities = new Dictionary<string, int>();

			public int Rarity => 0;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags)
			{
				Items.RemoveScrapFromLevels(base.Item, levelFlags);
			}

			public ScrapItem(string id, string contentPath, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Action<Item> registryCallback = null)
				: base(id, contentPath, registryCallback)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					levelRarities.Add(levelFlags, rarity);
				}
				else if (levelOverrides != null)
				{
					foreach (string key in levelOverrides)
					{
						customLevelRarities.Add(key, rarity);
					}
				}
			}

			public ScrapItem(string id, string contentPath, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, Action<Item> registryCallback = null)
				: base(id, contentPath, registryCallback)
			{
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
				if (customLevelRarities != null)
				{
					this.customLevelRarities = customLevelRarities;
				}
			}
		}

		public class Unlockable : CustomContent
		{
			public Action<UnlockableItem> registryCallback = delegate
			{
			};

			internal UnlockableItem unlockable;

			public string contentPath = "";

			public int initPrice;

			public string buyNode1Path;

			public string buyNode2Path;

			public string itemInfoPath;

			public StoreType storeType;

			public UnlockableItem UnlockableItem => unlockable;

			public void RemoveFromShop()
			{
				Unlockables.DisableUnlockable(UnlockableItem);
			}

			public void SetPrice(int price)
			{
				Unlockables.UpdateUnlockablePrice(UnlockableItem, price);
			}

			public Unlockable(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, StoreType storeType = StoreType.None, Action<UnlockableItem> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				initPrice = price;
				this.buyNode1Path = buyNode1Path;
				this.buyNode2Path = buyNode2Path;
				this.itemInfoPath = itemInfoPath;
				this.storeType = storeType;
			}
		}

		public class CustomEnemy : CustomContent
		{
			public Action<EnemyType> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal EnemyType enemy;

			public string infoNodePath;

			public string infoKeywordPath;

			public int rarity;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides;

			public Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1);

			public EnemyType Enemy => enemy;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags)
			{
				Enemies.RemoveEnemyFromLevels(Enemy, levelFlags);
			}

			public CustomEnemy(string id, string contentPath, int rarity = 0, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1), string[] levelOverrides = null, string infoNodePath = null, string infoKeywordPath = null, Action<EnemyType> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				this.infoNodePath = infoNodePath;
				this.infoKeywordPath = infoKeywordPath;
				this.rarity = rarity;
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnType = spawnType;
			}
		}

		public class MapHazard : CustomContent
		{
			public Action<SpawnableMapObjectDef> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal SpawnableMapObjectDef hazard;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides;

			public SpawnableMapObjectDef Hazard => hazard;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
			{
				MapObjects.RemoveMapObject(Hazard, levelFlags, levelOverrides);
			}

			public MapHazard(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableMapObjectDef> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnRateFunction = spawnRateFunction;
			}
		}

		public class OutsideObject : CustomContent
		{
			public Action<SpawnableOutsideObjectDef> registryCallback = delegate
			{
			};

			public string contentPath = "";

			internal SpawnableOutsideObjectDef mapObject;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;

			public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None;

			public string[] levelOverrides;

			public SpawnableOutsideObjectDef MapObject => mapObject;

			public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
			{
				MapObjects.RemoveOutsideObject(MapObject, levelFlags, levelOverrides);
			}

			public OutsideObject(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableOutsideObjectDef> registryCallback = null)
				: base(id)
			{
				this.contentPath = contentPath;
				if (registryCallback != null)
				{
					this.registryCallback = registryCallback;
				}
				LevelTypes = levelFlags;
				this.levelOverrides = levelOverrides;
				this.spawnRateFunction = spawnRateFunction;
			}
		}

		public PluginInfo modInfo;

		private AssetBundle modBundle;

		public Action<CustomContent, GameObject> prefabCallback = delegate
		{
		};

		public Dictionary<string, CustomContent> LoadedContent { get; } = new Dictionary<string, CustomContent>();


		public string modName => modInfo.Metadata.Name;

		public string modVersion => modInfo.Metadata.Version.ToString();

		public string modGUID => modInfo.Metadata.GUID;

		public ContentLoader(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null)
		{
			this.modInfo = modInfo;
			this.modBundle = modBundle;
			if (prefabCallback != null)
			{
				this.prefabCallback = prefabCallback;
			}
		}

		public ContentLoader Create(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null)
		{
			return new ContentLoader(modInfo, modBundle, prefabCallback);
		}

		public void Register(CustomContent content)
		{
			if (LoadedContent.ContainsKey(content.ID))
			{
				Debug.LogError((object)("[LethalLib] " + modName + " tried to register content with ID " + content.ID + " but it already exists!"));
				return;
			}
			if (content is CustomItem customItem)
			{
				Item val = (customItem.item = modBundle.LoadAsset<Item>(customItem.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab);
				Utilities.FixMixerGroups(val.spawnPrefab);
				prefabCallback(customItem, val.spawnPrefab);
				customItem.registryCallback(val);
				if (content is ShopItem shopItem)
				{
					TerminalNode buyNode = null;
					TerminalNode buyNode2 = null;
					TerminalNode itemInfo = null;
					if (shopItem.buyNode1Path != null)
					{
						buyNode = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode1Path);
					}
					if (shopItem.buyNode2Path != null)
					{
						buyNode2 = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode2Path);
					}
					if (shopItem.itemInfoPath != null)
					{
						itemInfo = modBundle.LoadAsset<TerminalNode>(shopItem.itemInfoPath);
					}
					Items.RegisterShopItem(val, buyNode, buyNode2, itemInfo, shopItem.initPrice);
				}
				else if (content is ScrapItem scrapItem)
				{
					Items.RegisterScrap(val, scrapItem.levelRarities, scrapItem.customLevelRarities);
				}
				else
				{
					Items.RegisterItem(val);
				}
			}
			else if (content is Unlockable unlockable)
			{
				UnlockableItemDef unlockableItemDef = modBundle.LoadAsset<UnlockableItemDef>(unlockable.contentPath);
				if ((Object)(object)unlockableItemDef.unlockable.prefabObject != (Object)null)
				{
					NetworkPrefabs.RegisterNetworkPrefab(unlockableItemDef.unlockable.prefabObject);
					prefabCallback(content, unlockableItemDef.unlockable.prefabObject);
					Utilities.FixMixerGroups(unlockableItemDef.unlockable.prefabObject);
				}
				unlockable.unlockable = unlockableItemDef.unlockable;
				unlockable.registryCallback(unlockableItemDef.unlockable);
				TerminalNode buyNode3 = null;
				TerminalNode buyNode4 = null;
				TerminalNode itemInfo2 = null;
				if (unlockable.buyNode1Path != null)
				{
					buyNode3 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode1Path);
				}
				if (unlockable.buyNode2Path != null)
				{
					buyNode4 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode2Path);
				}
				if (unlockable.itemInfoPath != null)
				{
					itemInfo2 = modBundle.LoadAsset<TerminalNode>(unlockable.itemInfoPath);
				}
				Unlockables.RegisterUnlockable(unlockableItemDef, unlockable.storeType, buyNode3, buyNode4, itemInfo2, unlockable.initPrice);
			}
			else if (content is CustomEnemy customEnemy)
			{
				EnemyType val2 = modBundle.LoadAsset<EnemyType>(customEnemy.contentPath);
				NetworkPrefabs.RegisterNetworkPrefab(val2.enemyPrefab);
				Utilities.FixMixerGroups(val2.enemyPrefab);
				customEnemy.enemy = val2;
				prefabCallback(content, val2.enemyPrefab);
				customEnemy.registryCallback(val2);
				TerminalNode infoNode = null;
				TerminalKeyword infoKeyword = null;
				if (customEnemy.infoNodePath != null)
				{
					infoNode = modBundle.LoadAsset<TerminalNode>(customEnemy.infoNodePath);
				}
				if (customEnemy.infoKeywordPath != null)
				{
					infoKeyword = modBundle.LoadAsset<TerminalKeyword>(customEnemy.infoKeywordPath);
				}
				if (customEnemy.spawnType == (Enemies.SpawnType)(-1))
				{
					Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.levelOverrides, infoNode, infoKeyword);
				}
				else
				{
					Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.spawnType, customEnemy.levelOverrides, infoNode, infoKeyword);
				}
			}
			else if (content is MapHazard mapHazard)
			{
				SpawnableMapObjectDef spawnableMapObjectDef = (mapHazard.hazard = modBundle.LoadAsset<SpawnableMapObjectDef>(mapHazard.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				Utilities.FixMixerGroups(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				prefabCallback(content, spawnableMapObjectDef.spawnableMapObject.prefabToSpawn);
				mapHazard.registryCallback(spawnableMapObjectDef);
				MapObjects.RegisterMapObject(spawnableMapObjectDef, mapHazard.LevelTypes, mapHazard.levelOverrides, mapHazard.spawnRateFunction);
			}
			else if (content is OutsideObject outsideObject)
			{
				SpawnableOutsideObjectDef spawnableOutsideObjectDef = (outsideObject.mapObject = modBundle.LoadAsset<SpawnableOutsideObjectDef>(outsideObject.contentPath));
				NetworkPrefabs.RegisterNetworkPrefab(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				Utilities.FixMixerGroups(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				prefabCallback(content, spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn);
				outsideObject.registryCallback(spawnableOutsideObjectDef);
				MapObjects.RegisterOutsideObject(spawnableOutsideObjectDef, outsideObject.LevelTypes, outsideObject.levelOverrides, outsideObject.spawnRateFunction);
			}
			LoadedContent.Add(content.ID, content);
		}

		public void RegisterAll(CustomContent[] content)
		{
			Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Length} content items!");
			foreach (CustomContent content2 in content)
			{
				Register(content2);
			}
		}

		public void RegisterAll(List<CustomContent> content)
		{
			Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Count} content items!");
			foreach (CustomContent item in content)
			{
				Register(item);
			}
		}
	}
	public class Dungeon
	{
		public class CustomDungeonArchetype
		{
			public DungeonArchetype archeType;

			public Levels.LevelTypes LevelTypes;

			public int lineIndex = -1;
		}

		public class CustomGraphLine
		{
			public GraphLine graphLine;

			public Levels.LevelTypes LevelTypes;
		}

		public class CustomDungeon
		{
			public int rarity;

			public DungeonFlow dungeonFlow;

			public Levels.LevelTypes LevelTypes;

			public string[] levelOverrides;

			public int dungeonIndex = -1;

			public AudioClip firstTimeDungeonAudio;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_GenerateNewFloor <0>__RoundManager_GenerateNewFloor;

			public static hook_Start <1>__RoundManager_Start;
		}

		public static List<CustomDungeonArchetype> customDungeonArchetypes = new List<CustomDungeonArchetype>();

		public static List<CustomGraphLine> customGraphLines = new List<CustomGraphLine>();

		public static Dictionary<string, TileSet> extraTileSets = new Dictionary<string, TileSet>();

		public static Dictionary<string, GameObjectChance> extraRooms = new Dictionary<string, GameObjectChance>();

		public static List<CustomDungeon> customDungeons = new List<CustomDungeon>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			object obj = <>O.<0>__RoundManager_GenerateNewFloor;
			if (obj == null)
			{
				hook_GenerateNewFloor val = RoundManager_GenerateNewFloor;
				<>O.<0>__RoundManager_GenerateNewFloor = val;
				obj = (object)val;
			}
			RoundManager.GenerateNewFloor += (hook_GenerateNewFloor)obj;
			object obj2 = <>O.<1>__RoundManager_Start;
			if (obj2 == null)
			{
				hook_Start val2 = RoundManager_Start;
				<>O.<1>__RoundManager_Start = val2;
				obj2 = (object)val2;
			}
			RoundManager.Start += (hook_Start)obj2;
		}

		private static void RoundManager_Start(orig_Start orig, RoundManager self)
		{
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			foreach (CustomDungeon customDungeon in customDungeons)
			{
				if (self.dungeonFlowTypes.Contains(customDungeon.dungeonFlow))
				{
					continue;
				}
				List<DungeonFlow> list = self.dungeonFlowTypes.ToList();
				list.Add(customDungeon.dungeonFlow);
				self.dungeonFlowTypes = list.ToArray();
				int dungeonIndex = self.dungeonFlowTypes.Length - 1;
				customDungeon.dungeonIndex = dungeonIndex;
				List<AudioClip> list2 = self.firstTimeDungeonAudios.ToList();
				if (list2.Count != self.dungeonFlowTypes.Length - 1)
				{
					while (list2.Count < self.dungeonFlowTypes.Length - 1)
					{
						list2.Add(null);
					}
				}
				list2.Add(customDungeon.firstTimeDungeonAudio);
				self.firstTimeDungeonAudios = list2.ToArray();
			}
			StartOfRound instance = StartOfRound.Instance;
			foreach (CustomDungeon dungeon in customDungeons)
			{
				SelectableLevel[] levels = instance.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = dungeon.LevelTypes.HasFlag(Levels.LevelTypes.All) || (dungeon.levelOverrides != null && dungeon.levelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)
					{
						Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
						if ((flag || dungeon.LevelTypes.HasFlag(levelTypes)) && !val.dungeonFlowTypes.Any((IntWithRarity rarityInt) => rarityInt.id == dungeon.dungeonIndex))
						{
							List<IntWithRarity> list3 = val.dungeonFlowTypes.ToList();
							list3.Add(new IntWithRarity
							{
								id = dungeon.dungeonIndex,
								rarity = dungeon.rarity
							});
							val.dungeonFlowTypes = list3.ToArray();
						}
					}
				}
			}
			orig.Invoke(self);
		}

		private static void RoundManager_GenerateNewFloor(orig_GenerateNewFloor orig, RoundManager self)
		{
			string name = ((Object)self.currentLevel).name;
			if (Enum.IsDefined(typeof(Levels.LevelTypes), name))
			{
				Levels.LevelTypes levelEnum = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name);
				int index = 0;
				self.dungeonGenerator.Generator.DungeonFlow.Lines.ForEach(delegate(GraphLine line)
				{
					foreach (CustomDungeonArchetype customDungeonArchetype in customDungeonArchetypes)
					{
						if (customDungeonArchetype.LevelTypes.HasFlag(levelEnum) && !line.DungeonArchetypes.Contains(customDungeonArchetype.archeType) && (customDungeonArchetype.lineIndex == -1 || customDungeonArchetype.lineIndex == index))
						{
							line.DungeonArchetypes.Add(customDungeonArchetype.archeType);
							Plugin.logger.LogInfo((object)("Added " + ((Object)customDungeonArchetype.archeType).name + " to " + name));
						}
					}
					foreach (DungeonArchetype dungeonArchetype in line.DungeonArchetypes)
					{
						string name2 = ((Object)dungeonArchetype).name;
						if (extraTileSets.ContainsKey(name2))
						{
							TileSet val4 = extraTileSets[name2];
							if (!dungeonArchetype.TileSets.Contains(val4))
							{
								dungeonArchetype.TileSets.Add(val4);
								Plugin.logger.LogInfo((object)("Added " + ((Object)val4).name + " to " + name));
							}
						}
						foreach (TileSet tileSet in dungeonArchetype.TileSets)
						{
							string name3 = ((Object)tileSet).name;
							if (extraRooms.ContainsKey(name3))
							{
								GameObjectChance item = extraRooms[name3];
								if (!tileSet.TileWeights.Weights.Contains(item))
								{
									tileSet.TileWeights.Weights.Add(item);
								}
							}
						}
					}
					index++;
				});
				foreach (CustomGraphLine customGraphLine in customGraphLines)
				{
					if (customGraphLine.LevelTypes.HasFlag(levelEnum) && !self.dungeonGenerator.Generator.DungeonFlow.Lines.Contains(customGraphLine.graphLine))
					{
						self.dungeonGenerator.Generator.DungeonFlow.Lines.Add(customGraphLine.graphLine);
					}
				}
			}
			orig.Invoke(self);
			NetworkManager val = Object.FindObjectOfType<NetworkManager>();
			RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>();
			foreach (RandomMapObject val2 in array)
			{
				for (int j = 0; j < val2.spawnablePrefabs.Count; j++)
				{
					string prefabName = ((Object)val2.spawnablePrefabs[j]).name;
					NetworkPrefab val3 = ((IEnumerable<NetworkPrefab>)val.NetworkConfig.Prefabs.m_Prefabs).FirstOrDefault((Func<NetworkPrefab, bool>)((NetworkPrefab x) => ((Object)x.Prefab).name == prefabName));
					if (val3 != null && (Object)(object)val3.Prefab != (Object)(object)val2.spawnablePrefabs[j])
					{
						val2.spawnablePrefabs[j] = val3.Prefab;
					}
					else if (val3 == null)
					{
						Plugin.logger.LogError((object)("DungeonGeneration - Could not find network prefab (" + prefabName + ")! Make sure your assigned prefab is registered with the network manager, or named identically to the vanilla prefab you are referencing."));
					}
				}
			}
		}

		public static void AddArchetype(DungeonArchetype archetype, Levels.LevelTypes levelFlags, int lineIndex = -1)
		{
			CustomDungeonArchetype customDungeonArchetype = new CustomDungeonArchetype();
			customDungeonArchetype.archeType = archetype;
			customDungeonArchetype.LevelTypes = levelFlags;
			customDungeonArchetype.lineIndex = lineIndex;
			customDungeonArchetypes.Add(customDungeonArchetype);
		}

		public static void AddLine(GraphLine line, Levels.LevelTypes levelFlags)
		{
			CustomGraphLine customGraphLine = new CustomGraphLine();
			customGraphLine.graphLine = line;
			customGraphLine.LevelTypes = levelFlags;
			customGraphLines.Add(customGraphLine);
		}

		public static void AddLine(DungeonGraphLineDef line, Levels.LevelTypes levelFlags)
		{
			AddLine(line.graphLine, levelFlags);
		}

		public static void AddTileSet(TileSet set, string archetypeName)
		{
			extraTileSets.Add(archetypeName, set);
		}

		public static void AddRoom(GameObjectChance room, string tileSetName)
		{
			extraRooms.Add(tileSetName, room);
		}

		public static void AddRoom(GameObjectChanceDef room, string tileSetName)
		{
			AddRoom(room.gameObjectChance, tileSetName);
		}

		public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags)
		{
			AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, dungeon.firstTimeDungeonAudio);
		}

		public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags, string[] levelOverrides)
		{
			AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, levelOverrides, dungeon.firstTimeDungeonAudio);
		}

		public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, AudioClip firstTimeDungeonAudio = null)
		{
			customDungeons.Add(new CustomDungeon
			{
				dungeonFlow = dungeon,
				rarity = rarity,
				LevelTypes = levelFlags,
				firstTimeDungeonAudio = firstTimeDungeonAudio
			});
		}

		public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, string[] levelOverrides = null, AudioClip firstTimeDungeonAudio = null)
		{
			customDungeons.Add(new CustomDungeon
			{
				dungeonFlow = dungeon,
				rarity = rarity,
				LevelTypes = levelFlags,
				firstTimeDungeonAudio = firstTimeDungeonAudio,
				levelOverrides = levelOverrides
			});
		}
	}
	public class Enemies
	{
		public struct EnemyAssetInfo
		{
			public EnemyType EnemyAsset;

			public TerminalKeyword keyword;
		}

		public enum SpawnType
		{
			Default,
			Daytime,
			Outside
		}

		public class SpawnableEnemy
		{
			public EnemyType enemy;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public SpawnType spawnType;

			public TerminalNode terminalNode;

			public TerminalKeyword infoKeyword;

			public string modName;

			public string[] spawnLevelOverrides;

			public SpawnableEnemy(EnemyType enemy, int rarity, Levels.LevelTypes spawnLevels, SpawnType spawnType, string[] spawnLevelOverrides = null)
			{
				this.enemy = enemy;
				this.rarity = rarity;
				this.spawnLevels = spawnLevels;
				this.spawnType = spawnType;
				this.spawnLevelOverrides = spawnLevelOverrides;
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__RegisterLevelEnemies;

			public static hook_Start <1>__Terminal_Start;
		}

		public static Terminal terminal;

		public static List<EnemyAssetInfo> enemyAssetInfos = new List<EnemyAssetInfo>();

		public static List<SpawnableEnemy> spawnableEnemies = new List<SpawnableEnemy>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			object obj = <>O.<0>__RegisterLevelEnemies;
			if (obj == null)
			{
				hook_Awake val = RegisterLevelEnemies;
				<>O.<0>__RegisterLevelEnemies = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__Terminal_Start;
			if (obj2 == null)
			{
				hook_Start val2 = Terminal_Start;
				<>O.<1>__Terminal_Start = val2;
				obj2 = (object)val2;
			}
			Terminal.Start += (hook_Start)obj2;
		}

		private static void Terminal_Start(orig_Start orig, Terminal self)
		{
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0264: Unknown result type (might be due to invalid IL or missing references)
			//IL_027a: Expected O, but got Unknown
			terminal = self;
			TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			List<string> list = new List<string>();
			foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
			{
				if (list.Contains(spawnableEnemy.enemy.enemyName))
				{
					Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added"));
					continue;
				}
				if ((Object)(object)spawnableEnemy.terminalNode == (Object)null)
				{
					spawnableEnemy.terminalNode = ScriptableObject.CreateInstance<TerminalNode>();
					spawnableEnemy.terminalNode.displayText = spawnableEnemy.enemy.enemyName + "\n\nDanger level: Unknown\n\n[No information about this creature was found.]\n\n";
					spawnableEnemy.terminalNode.clearPreviousText = true;
					spawnableEnemy.terminalNode.maxCharactersToType = 35;
					spawnableEnemy.terminalNode.creatureName = spawnableEnemy.enemy.enemyName;
				}
				if (self.enemyFiles.Any((TerminalNode x) => x.creatureName == spawnableEnemy.terminalNode.creatureName))
				{
					Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added"));
					continue;
				}
				TerminalKeyword keyword2 = (((Object)(object)spawnableEnemy.infoKeyword != (Object)null) ? spawnableEnemy.infoKeyword : TerminalUtils.CreateTerminalKeyword(spawnableEnemy.terminalNode.creatureName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val));
				keyword2.defaultVerb = val;
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				if (!list2.Any((TerminalKeyword x) => x.word == keyword2.word))
				{
					list2.Add(keyword2);
					self.terminalNodes.allKeywords = list2.ToArray();
				}
				List<CompatibleNoun> list3 = val.compatibleNouns.ToList();
				if (!list3.Any((CompatibleNoun x) => x.noun.word == keyword2.word))
				{
					list3.Add(new CompatibleNoun
					{
						noun = keyword2,
						result = spawnableEnemy.terminalNode
					});
				}
				val.compatibleNouns = list3.ToArray();
				spawnableEnemy.terminalNode.creatureFileID = self.enemyFiles.Count;
				self.enemyFiles.Add(spawnableEnemy.terminalNode);
				spawnableEnemy.enemy.enemyPrefab.GetComponentInChildren<ScanNodeProperties>().creatureScanID = spawnableEnemy.terminalNode.creatureFileID;
				EnemyAssetInfo enemyAssetInfo = default(EnemyAssetInfo);
				enemyAssetInfo.EnemyAsset = spawnableEnemy.enemy;
				enemyAssetInfo.keyword = keyword2;
				EnemyAssetInfo item = enemyAssetInfo;
				enemyAssetInfos.Add(item);
			}
			orig.Invoke(self);
		}

		private static void RegisterLevelEnemies(orig_Awake orig, StartOfRound self)
		{
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Expected O, but got Unknown
			orig.Invoke(self);
			foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies)
			{
				SelectableLevel[] levels = self.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = spawnableEnemy.spawnLevels.HasFlag(Levels.LevelTypes.All) || (spawnableEnemy.spawnLevelOverrides != null && spawnableEnemy.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !spawnableEnemy.spawnLevels.HasFlag(levelTypes))
					{
						continue;
					}
					SpawnableEnemyWithRarity item2 = new SpawnableEnemyWithRarity
					{
						enemyType = spawnableEnemy.enemy,
						rarity = spawnableEnemy.rarity
					};
					switch (spawnableEnemy.spawnType)
					{
					case SpawnType.Default:
						if (!val.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
						{
							val.Enemies.Add(item2);
							Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Default]"));
						}
						break;
					case SpawnType.Daytime:
						if (!val.DaytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
						{
							val.DaytimeEnemies.Add(item2);
							Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Daytime]"));
						}
						break;
					case SpawnType.Outside:
						if (!val.OutsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy))
						{
							val.OutsideEnemies.Add(item2);
							Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Outside]"));
						}
						break;
					}
				}
			}
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType);
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			string name = Assembly.GetCallingAssembly().GetName().Name;
			spawnableEnemy.modName = name;
			spawnableEnemies.Add(spawnableEnemy);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType, spawnLevelOverrides);
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			string name = Assembly.GetCallingAssembly().GetName().Name;
			spawnableEnemy.modName = name;
			spawnableEnemies.Add(spawnableEnemy);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default));
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			string name = Assembly.GetCallingAssembly().GetName().Name;
			spawnableEnemy.modName = name;
			spawnableEnemies.Add(spawnableEnemy);
		}

		public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null)
		{
			SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default), spawnLevelOverrides);
			spawnableEnemy.terminalNode = infoNode;
			spawnableEnemy.infoKeyword = infoKeyword;
			string name = Assembly.GetCallingAssembly().GetName().Name;
			spawnableEnemy.modName = name;
			spawnableEnemies.Add(spawnableEnemy);
		}

		public static void RemoveEnemyFromLevels(EnemyType enemyType, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			EnemyType enemyType2 = enemyType;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					List<SpawnableEnemyWithRarity> enemies = val.Enemies;
					List<SpawnableEnemyWithRarity> daytimeEnemies = val.DaytimeEnemies;
					List<SpawnableEnemyWithRarity> outsideEnemies = val.OutsideEnemies;
					enemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					daytimeEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
					outsideEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2);
				}
			}
		}
	}
	public class Items
	{
		public struct ItemSaveOrderData
		{
			public int itemId;

			public string itemName;

			public string assetName;
		}

		public struct BuyableItemAssetInfo
		{
			public Item itemAsset;

			public TerminalKeyword keyword;
		}

		public class ScrapItem
		{
			public Item item;

			public Item origItem;

			public int rarity;

			public Levels.LevelTypes spawnLevels;

			public string[] spawnLevelOverrides;

			public string modName = "Unknown";

			public Dictionary<string, int> customLevelRarities = new Dictionary<string, int>();

			public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>();

			public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null)
			{
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				origItem = item;
				if (!item.isScrap)
				{
					item = item.Clone<Item>();
					item.isScrap = true;
					if (item.maxValue == 0 && item.minValue == 0)
					{
						item.minValue = 40;
						item.maxValue = 100;
					}
					else if (item.maxValue == 0)
					{
						item.maxValue = item.minValue * 2;
					}
					else if (item.minValue == 0)
					{
						item.minValue = item.maxValue / 2;
					}
					GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab);
					if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null)
					{
						val.GetComponent<GrabbableObject>().itemProperties = item;
					}
					if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() == (Object)null)
					{
						GameObject obj = Object.Instantiate<GameObject>(scanNodePrefab, val.transform);
						((Object)obj).name = "ScanNode";
						obj.transform.localPosition = new Vector3(0f, 0f, 0f);
						obj.GetComponent<ScanNodeProperties>().headerText = item.itemName;
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				if (spawnLevelOverrides != null)
				{
					foreach (string key in spawnLevelOverrides)
					{
						customLevelRarities.Add(key, rarity);
					}
				}
				if (spawnLevels == Levels.LevelTypes.None)
				{
					return;
				}
				foreach (Levels.LevelTypes value in Enum.GetValues(typeof(Levels.LevelTypes)))
				{
					if (spawnLevels.HasFlag(value))
					{
						levelRarities.Add(value, rarity);
					}
				}
			}

			public ScrapItem(Item item, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
			{
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				origItem = item;
				if (!item.isScrap)
				{
					item = item.Clone<Item>();
					item.isScrap = true;
					if (item.maxValue == 0 && item.minValue == 0)
					{
						item.minValue = 40;
						item.maxValue = 100;
					}
					else if (item.maxValue == 0)
					{
						item.maxValue = item.minValue * 2;
					}
					else if (item.minValue == 0)
					{
						item.minValue = item.maxValue / 2;
					}
					GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab);
					if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null)
					{
						val.GetComponent<GrabbableObject>().itemProperties = item;
					}
					if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() == (Object)null)
					{
						GameObject obj = Object.Instantiate<GameObject>(scanNodePrefab, val.transform);
						((Object)obj).name = "ScanNode";
						obj.transform.localPosition = new Vector3(0f, 0f, 0f);
						obj.GetComponent<ScanNodeProperties>().headerText = item.itemName;
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				if (customLevelRarities != null)
				{
					this.customLevelRarities = customLevelRarities;
				}
				if (levelRarities != null)
				{
					this.levelRarities = levelRarities;
				}
			}
		}

		public class PlainItem
		{
			public Item item;

			public string modName;

			public PlainItem(Item item)
			{
				this.item = item;
			}
		}

		public class ShopItem
		{
			public Item item;

			public Item origItem;

			public TerminalNode buyNode1;

			public TerminalNode buyNode2;

			public TerminalNode itemInfo;

			public bool wasRemoved;

			public int price;

			public string modName;

			public ShopItem(Item item, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = 0)
			{
				origItem = item;
				if (item.isScrap)
				{
					item = item.Clone<Item>();
					item.isScrap = false;
					GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab);
					if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null)
					{
						val.GetComponent<GrabbableObject>().itemProperties = item;
					}
					if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() != (Object)null)
					{
						Object.Destroy((Object)(object)((Component)val.GetComponentInChildren<ScanNodeProperties>()).gameObject);
					}
					item.spawnPrefab = val;
				}
				this.item = item;
				this.price = price;
				if ((Object)(object)buyNode1 != (Object)null)
				{
					this.buyNode1 = buyNode1;
				}
				if ((Object)(object)buyNode2 != (Object)null)
				{
					this.buyNode2 = buyNode2;
				}
				if ((Object)(object)itemInfo != (Object)null)
				{
					this.itemInfo = itemInfo;
				}
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__StartOfRound_Start;

			public static hook_Awake <1>__Terminal_Awake;

			public static hook_TextPostProcess <2>__Terminal_TextPostProcess;
		}

		public static ConfigEntry<bool> useSavedataFix;

		public static GameObject scanNodePrefab;

		public static List<Item> LethalLibItemList = new List<Item>();

		public static List<BuyableItemAssetInfo> buyableItemAssetInfos = new List<BuyableItemAssetInfo>();

		public static Terminal terminal;

		public static List<ScrapItem> scrapItems = new List<ScrapItem>();

		public static List<ShopItem> shopItems = new List<ShopItem>();

		public static List<PlainItem> plainItems = new List<PlainItem>();

		public static void Init()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			useSavedataFix = Plugin.config.Bind<bool>("Items", "EnableItemSaveFix", false, "Allow for LethalLib to store/reorder the item list, which should fix issues where items get reshuffled when loading an old save. This is experimental and may cause save corruptions occasionally.");
			scanNodePrefab = Plugin.MainAssets.LoadAsset<GameObject>("Assets/Custom/ItemScanNode.prefab");
			object obj = <>O.<0>__StartOfRound_Start;
			if (obj == null)
			{
				hook_Start val = StartOfRound_Start;
				<>O.<0>__StartOfRound_Start = val;
				obj = (object)val;
			}
			StartOfRound.Start += (hook_Start)obj;
			object obj2 = <>O.<1>__Terminal_Awake;
			if (obj2 == null)
			{
				hook_Awake val2 = Terminal_Awake;
				<>O.<1>__Terminal_Awake = val2;
				obj2 = (object)val2;
			}
			Terminal.Awake += (hook_Awake)obj2;
			object obj3 = <>O.<2>__Terminal_TextPostProcess;
			if (obj3 == null)
			{
				hook_TextPostProcess val3 = Terminal_TextPostProcess;
				<>O.<2>__Terminal_TextPostProcess = val3;
				obj3 = (object)val3;
			}
			Terminal.TextPostProcess += (hook_TextPostProcess)obj3;
		}

		private static string Terminal_TextPostProcess(orig_TextPostProcess orig, Terminal self, string modifiedDisplayText, TerminalNode node)
		{
			List<Item> list = self.buyableItemsList.ToList();
			List<Item> list2 = self.buyableItemsList.ToList();
			list2.RemoveAll((Item x) => shopItems.FirstOrDefault((ShopItem item) => (Object)(object)item.origItem == (Object)(object)x || (Object)(object)item.item == (Object)(object)x)?.wasRemoved ?? false);
			self.buyableItemsList = list2.ToArray();
			string result = orig.Invoke(self, modifiedDisplayText, node);
			self.buyableItemsList = list.ToArray();
			return result;
		}

		private static void StartOfRound_Start(orig_Start orig, StartOfRound self)
		{
			if (useSavedataFix.Value && ((NetworkBehaviour)self).IsHost)
			{
				Plugin.logger.LogInfo((object)"Fixing Item savedata!!");
				List<ItemSaveOrderData> itemList = new List<ItemSaveOrderData>();
				StartOfRound.Instance.allItemsList.itemsList.ForEach(delegate(Item item)
				{
					itemList.Add(new ItemSaveOrderData
					{
						itemId = item.itemId,
						itemName = item.itemName,
						assetName = ((Object)item).name
					});
				});
				if (ES3.KeyExists("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName))
				{
					itemList = ES3.Load<List<ItemSaveOrderData>>("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName);
				}
				List<Item> itemsList = StartOfRound.Instance.allItemsList.itemsList;
				List<Item> list = new List<Item>();
				foreach (ItemSaveOrderData item2 in itemList)
				{
					Item val = ((IEnumerable<Item>)itemsList).FirstOrDefault((Func<Item, bool>)((Item x) => x.itemId == item2.itemId && x.itemName == item2.itemName && item2.assetName == ((Object)x).name));
					if ((Object)(object)val != (Object)null)
					{
						list.Add(val);
					}
					else
					{
						list.Add(ScriptableObject.CreateInstance<Item>());
					}
				}
				foreach (Item item3 in itemsList)
				{
					if (!list.Contains(item3))
					{
						list.Add(item3);
					}
				}
				StartOfRound.Instance.allItemsList.itemsList = list;
				ES3.Save<List<ItemSaveOrderData>>("LethalLibAllItemsList", itemList, GameNetworkManager.Instance.currentSaveFileName);
			}
			orig.Invoke(self);
		}

		private static void Terminal_Awake(orig_Awake orig, Terminal self)
		{
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a5: Expected O, but got Unknown
			//IL_0882: Unknown result type (might be due to invalid IL or missing references)
			//IL_0887: Unknown result type (might be due to invalid IL or missing references)
			//IL_08bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_08c5: Expected O, but got Unknown
			//IL_08c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_08cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0901: Unknown result type (might be due to invalid IL or missing references)
			//IL_0909: Expected O, but got Unknown
			//IL_0987: Unknown result type (might be due to invalid IL or missing references)
			//IL_098c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0994: Unknown result type (might be due to invalid IL or missing references)
			//IL_09a1: Expected O, but got Unknown
			//IL_0a3d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a42: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a4a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a57: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			foreach (ScrapItem scrapItem in scrapItems)
			{
				SelectableLevel[] levels = instance.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = scrapItem.levelRarities.ContainsKey(Levels.LevelTypes.All) || (scrapItem.customLevelRarities != null && scrapItem.customLevelRarities.ContainsKey(name));
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelEnum = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !scrapItem.levelRarities.Keys.Any((Levels.LevelTypes key) => key.HasFlag(levelEnum)))
					{
						continue;
					}
					int rarity = 0;
					if (scrapItem.levelRarities.Keys.Any((Levels.LevelTypes key) => key.HasFlag(levelEnum)))
					{
						rarity = scrapItem.levelRarities.First((KeyValuePair<Levels.LevelTypes, int> x) => x.Key.HasFlag(levelEnum)).Value;
					}
					else if (scrapItem.customLevelRarities != null && scrapItem.customLevelRarities.ContainsKey(name))
					{
						rarity = scrapItem.customLevelRarities[name];
					}
					SpawnableItemWithRarity item2 = new SpawnableItemWithRarity
					{
						spawnableItem = scrapItem.item,
						rarity = rarity
					};
					if (!val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem.item))
					{
						val.spawnableScrap.Add(item2);
						Plugin.logger.LogInfo((object)("Added " + ((Object)scrapItem.item).name + " to " + name));
					}
				}
			}
			foreach (ScrapItem scrapItem2 in scrapItems)
			{
				if (!instance.allItemsList.itemsList.Contains(scrapItem2.item))
				{
					if (scrapItem2.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(scrapItem2.modName + " registered scrap item: " + scrapItem2.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered scrap item: " + scrapItem2.item.itemName));
					}
					LethalLibItemList.Add(scrapItem2.item);
					instance.allItemsList.itemsList.Add(scrapItem2.item);
				}
			}
			foreach (ShopItem shopItem in shopItems)
			{
				if (!instance.allItemsList.itemsList.Contains(shopItem.item))
				{
					if (shopItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(shopItem.modName + " registered shop item: " + shopItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered shop item: " + shopItem.item.itemName));
					}
					LethalLibItemList.Add(shopItem.item);
					instance.allItemsList.itemsList.Add(shopItem.item);
				}
			}
			foreach (PlainItem plainItem in plainItems)
			{
				if (!instance.allItemsList.itemsList.Contains(plainItem.item))
				{
					if (plainItem.modName != "LethalLib")
					{
						Plugin.logger.LogInfo((object)(plainItem.modName + " registered item: " + plainItem.item.itemName));
					}
					else
					{
						Plugin.logger.LogInfo((object)("Registered item: " + plainItem.item.itemName));
					}
					LethalLibItemList.Add(plainItem.item);
					instance.allItemsList.itemsList.Add(plainItem.item);
				}
			}
			terminal = self;
			List<Item> list = self.buyableItemsList.ToList();
			TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			TerminalNode result = val2.compatibleNouns[0].result.terminalOptions[1].result;
			TerminalKeyword val3 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			Plugin.logger.LogInfo((object)$"Adding {shopItems.Count} items to terminal");
			foreach (ShopItem item in shopItems)
			{
				if (list.Any((Item x) => x.itemName == item.item.itemName) && !item.wasRemoved)
				{
					Plugin.logger.LogInfo((object)("Item " + item.item.itemName + " already exists in terminal, skipping"));
					continue;
				}
				item.wasRemoved = false;
				if (item.price == -1)
				{
					item.price = item.item.creditsWorth;
				}
				else
				{
					item.item.creditsWorth = item.price;
				}
				int num = -1;
				if (!list.Any((Item x) => (Object)(object)x == (Object)(object)item.item))
				{
					list.Add(item.item);
				}
				else
				{
					num = list.IndexOf(item.item);
				}
				int buyItemIndex = ((num == -1) ? (list.Count - 1) : num);
				string itemName = item.item.itemName;
				_ = itemName[itemName.Length - 1];
				string text = itemName;
				Plugin.logger.LogInfo((object)("Adding " + itemName + " to terminal"));
				TerminalNode val4 = item.buyNode2;
				if ((Object)(object)val4 == (Object)null)
				{
					val4 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val4).name = itemName.Replace(" ", "-") + "BuyNode2";
					val4.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n";
					val4.clearPreviousText = true;
					val4.maxCharactersToType = 15;
					Plugin.logger.LogInfo((object)"Generating buynode2");
				}
				val4.buyItemIndex = buyItemIndex;
				val4.isConfirmationNode = false;
				val4.itemCost = item.price;
				val4.playSyncedClip = 0;
				Plugin.logger.LogInfo((object)$"Item price: {val4.itemCost}, Item index: {val4.buyItemIndex}");
				TerminalNode val5 = item.buyNode1;
				if ((Object)(object)val5 == (Object)null)
				{
					val5 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val5).name = itemName.Replace(" ", "-") + "BuyNode1";
					val5.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n";
					val5.clearPreviousText = true;
					val5.maxCharactersToType = 35;
					Plugin.logger.LogInfo((object)"Generating buynode1");
				}
				val5.buyItemIndex = buyItemIndex;
				val5.isConfirmationNode = true;
				val5.overrideOptions = true;
				val5.itemCost = item.price;
				Plugin.logger.LogInfo((object)$"Item price: {val5.itemCost}, Item index: {val5.buyItemIndex}");
				val5.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2]
				{
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"),
						result = val4
					},
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"),
						result = result
					}
				};
				TerminalKeyword val6 = TerminalUtils.CreateTerminalKeyword(itemName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val2);
				Plugin.logger.LogInfo((object)("Generated keyword: " + val6.word));
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				list2.Add(val6);
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list3 = val2.compatibleNouns.ToList();
				list3.Add(new CompatibleNoun
				{
					noun = val6,
					result = val5
				});
				val2.compatibleNouns = list3.ToArray();
				TerminalNode val7 = item.itemInfo;
				if ((Object)(object)val7 == (Object)null)
				{
					val7 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val7).name = itemName.Replace(" ", "-") + "InfoNode";
					val7.displayText = "[No information about this object was found.]\n\n";
					val7.clearPreviousText = true;
					val7.maxCharactersToType = 25;
					Plugin.logger.LogInfo((object)"Generated item info!!");
				}
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list4 = val3.compatibleNouns.ToList();
				list4.Add(new CompatibleNoun
				{
					noun = val6,
					result = val7
				});
				val3.compatibleNouns = list4.ToArray();
				BuyableItemAssetInfo buyableItemAssetInfo = default(BuyableItemAssetInfo);
				buyableItemAssetInfo.itemAsset = item.item;
				buyableItemAssetInfo.keyword = val6;
				BuyableItemAssetInfo item3 = buyableItemAssetInfo;
				buyableItemAssetInfos.Add(item3);
			}
			self.buyableItemsList = list.ToArray();
			orig.Invoke(self);
		}

		public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					scrapItem.levelRarities.Add(levelFlags, rarity);
				}
			}
			else
			{
				scrapItem = new ScrapItem(spawnableItem2, rarity, levelFlags);
				string name = Assembly.GetCallingAssembly().GetName().Name;
				scrapItem.modName = name;
				scrapItems.Add(scrapItem);
			}
		}

		public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelFlags != Levels.LevelTypes.None)
				{
					scrapItem.levelRarities.Add(levelFlags, rarity);
				}
				if (levelOverrides != null)
				{
					foreach (string key in levelOverrides)
					{
						scrapItem.customLevelRarities.Add(key, rarity);
					}
				}
			}
			else
			{
				scrapItem = new ScrapItem(spawnableItem2, rarity, levelFlags, levelOverrides);
				string name = Assembly.GetCallingAssembly().GetName().Name;
				scrapItem.modName = name;
				scrapItems.Add(scrapItem);
			}
		}

		public static void RegisterScrap(Item spawnableItem, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null)
		{
			Item spawnableItem2 = spawnableItem;
			ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2);
			if (scrapItem != null)
			{
				if (levelRarities != null)
				{
					foreach (KeyValuePair<Levels.LevelTypes, int> levelRarity in levelRarities)
					{
						scrapItem.levelRarities.Add(levelRarity.Key, levelRarity.Value);
					}
				}
				if (customLevelRarities == null)
				{
					return;
				}
				{
					foreach (KeyValuePair<string, int> customLevelRarity in customLevelRarities)
					{
						scrapItem.customLevelRarities.Add(customLevelRarity.Key, customLevelRarity.Value);
					}
					return;
				}
			}
			scrapItem = new ScrapItem(spawnableItem2, levelRarities, customLevelRarities);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			scrapItem.modName = name;
			scrapItems.Add(scrapItem);
		}

		public static void RegisterShopItem(Item shopItem, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
		{
			ShopItem shopItem2 = new ShopItem(shopItem, buyNode1, buyNode2, itemInfo, price);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			shopItem2.modName = name;
			shopItems.Add(shopItem2);
		}

		public static void RegisterShopItem(Item shopItem, int price = -1)
		{
			ShopItem shopItem2 = new ShopItem(shopItem, null, null, null, price);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			shopItem2.modName = name;
			shopItems.Add(shopItem2);
		}

		public static void RegisterItem(Item plainItem)
		{
			PlainItem plainItem2 = new PlainItem(plainItem);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			plainItem2.modName = name;
			plainItems.Add(plainItem2);
		}

		public static void RemoveScrapFromLevels(Item scrapItem, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null)
		{
			Item scrapItem2 = scrapItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					ScrapItem actualItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)scrapItem2 || (Object)(object)x.item == (Object)(object)scrapItem2);
					SpawnableItemWithRarity val2 = ((IEnumerable<SpawnableItemWithRarity>)val.spawnableScrap).FirstOrDefault((Func<SpawnableItemWithRarity, bool>)((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)actualItem.item));
					if (val2 != null)
					{
						val.spawnableScrap.Remove(val2);
					}
				}
			}
		}

		public static void RemoveShopItem(Item shopItem)
		{
			Item shopItem2 = shopItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem2 || (Object)(object)x.item == (Object)(object)shopItem2);
			actualItem.wasRemoved = true;
			List<TerminalKeyword> list = terminal.terminalNodes.allKeywords.ToList();
			TerminalKeyword obj = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			TerminalKeyword val = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			List<CompatibleNoun> list2 = val.compatibleNouns.ToList();
			List<CompatibleNoun> list3 = obj.compatibleNouns.ToList();
			if (buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item))
			{
				BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item);
				list.Remove(asset.keyword);
				list2.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
				list3.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword);
			}
			terminal.terminalNodes.allKeywords = list.ToArray();
			val.compatibleNouns = list2.ToArray();
			obj.compatibleNouns = list3.ToArray();
		}

		public static void UpdateShopItemPrice(Item shopItem, int price)
		{
			Item shopItem2 = shopItem;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem2 || (Object)(object)x.item == (Object)(object)shopItem2);
			actualItem.item.creditsWorth = price;
			TerminalKeyword obj = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			_ = obj.compatibleNouns[0].result.terminalOptions[1].result;
			List<CompatibleNoun> source = obj.compatibleNouns.ToList();
			if (!buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item))
			{
				return;
			}
			BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item);
			if (!source.Any((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword))
			{
				return;
			}
			TerminalNode result = source.First((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword).result;
			result.itemCost = price;
			if (result.terminalOptions.Length == 0)
			{
				return;
			}
			CompatibleNoun[] terminalOptions = result.terminalOptions;
			foreach (CompatibleNoun val in terminalOptions)
			{
				if ((Object)(object)val.result != (Object)null && val.result.buyItemIndex != -1)
				{
					val.result.itemCost = price;
				}
			}
		}
	}
	public class Levels
	{
		[Flags]
		public enum LevelTypes
		{
			None = 1,
			ExperimentationLevel = 4,
			AssuranceLevel = 8,
			VowLevel = 0x10,
			OffenseLevel = 0x20,
			MarchLevel = 0x40,
			RendLevel = 0x80,
			DineLevel = 0x100,
			TitanLevel = 0x200,
			Vanilla = 0x3FC,
			All = -1
		}
	}
	public class MapObjects
	{
		public class RegisteredMapObject
		{
			public SpawnableMapObject mapObject;

			public SpawnableOutsideObjectWithRarity outsideObject;

			public Levels.LevelTypes levels;

			public string[] spawnLevelOverrides;

			public Func<SelectableLevel, AnimationCurve> spawnRateFunction;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__StartOfRound_Awake;

			public static hook_SpawnMapObjects <1>__RoundManager_SpawnMapObjects;
		}

		public static List<RegisteredMapObject> mapObjects = new List<RegisteredMapObject>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__RoundManager_SpawnMapObjects;
			if (obj2 == null)
			{
				hook_SpawnMapObjects val2 = RoundManager_SpawnMapObjects;
				<>O.<1>__RoundManager_SpawnMapObjects = val2;
				obj2 = (object)val2;
			}
			RoundManager.SpawnMapObjects += (hook_SpawnMapObjects)obj2;
		}

		private static void RoundManager_SpawnMapObjects(orig_SpawnMapObjects orig, RoundManager self)
		{
			RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>();
			foreach (RandomMapObject val in array)
			{
				foreach (RegisteredMapObject mapObject in mapObjects)
				{
					if (mapObject.mapObject != null && !val.spawnablePrefabs.Any((GameObject prefab) => (Object)(object)prefab == (Object)(object)mapObject.mapObject.prefabToSpawn))
					{
						val.spawnablePrefabs.Add(mapObject.mapObject.prefabToSpawn);
					}
				}
			}
			orig.Invoke(self);
		}

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			orig.Invoke(self);
			foreach (RegisteredMapObject mapObject in mapObjects)
			{
				SelectableLevel[] levels = self.levels;
				foreach (SelectableLevel val in levels)
				{
					string name = ((Object)val).name;
					bool flag = mapObject.levels.HasFlag(Levels.LevelTypes.All) || (mapObject.spawnLevelOverrides != null && mapObject.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()));
					if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
					{
						continue;
					}
					Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
					if (!flag && !mapObject.levels.HasFlag(levelTypes))
					{
						continue;
					}
					if (mapObject.mapObject != null)
					{
						if (!val.spawnableMapObjects.Any((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn))
						{
							List<SpawnableMapObject> list = val.spawnableMapObjects.ToList();
							list.RemoveAll((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn);
							val.spawnableMapObjects = list.ToArray();
						}
						SpawnableMapObject mapObject2 = mapObject.mapObject;
						if (mapObject.spawnRateFunction != null)
						{
							mapObject2.numberToSpawn = mapObject.spawnRateFunction(val);
						}
						List<SpawnableMapObject> list2 = val.spawnableMapObjects.ToList();
						list2.Add(mapObject2);
						val.spawnableMapObjects = list2.ToArray();
						Plugin.logger.LogInfo((object)("Added " + ((Object)mapObject2.prefabToSpawn).name + " to " + name));
					}
					else
					{
						if (mapObject.outsideObject == null)
						{
							continue;
						}
						if (!val.spawnableOutsideObjects.Any((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn))
						{
							List<SpawnableOutsideObjectWithRarity> list3 = val.spawnableOutsideObjects.ToList();
							list3.RemoveAll((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn);
							val.spawnableOutsideObjects = list3.ToArray();
						}
						SpawnableOutsideObjectWithRarity outsideObject = mapObject.outsideObject;
						if (mapObject.spawnRateFunction != null)
						{
							outsideObject.randomAmount = mapObject.spawnRateFunction(val);
						}
						List<SpawnableOutsideObjectWithRarity> list4 = val.spawnableOutsideObjects.ToList();
						list4.Add(outsideObject);
						val.spawnableOutsideObjects = list4.ToArray();
						Plugin.logger.LogInfo((object)("Added " + ((Object)outsideObject.spawnableObject.prefabToSpawn).name + " to " + name));
					}
				}
			}
		}

		public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterMapObject(mapObject.spawnableMapObject, levels, spawnRateFunction);
		}

		public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterMapObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction);
		}

		public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				mapObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction
			});
		}

		public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				mapObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction,
				spawnLevelOverrides = levelOverrides
			});
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterOutsideObject(mapObject.spawnableMapObject, levels, spawnRateFunction);
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			RegisterOutsideObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction);
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				outsideObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction
			});
		}

		public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null)
		{
			mapObjects.Add(new RegisteredMapObject
			{
				outsideObject = mapObject,
				levels = levels,
				spawnRateFunction = spawnRateFunction,
				spawnLevelOverrides = levelOverrides
			});
		}

		public static void RemoveMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			RemoveMapObject(mapObject.spawnableMapObject, levelFlags, levelOverrides);
		}

		public static void RemoveMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			SpawnableMapObject mapObject2 = mapObject;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					val.spawnableMapObjects = val.spawnableMapObjects.Where((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn != (Object)(object)mapObject2.prefabToSpawn).ToArray();
				}
			}
		}

		public static void RemoveOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			RemoveOutsideObject(mapObject.spawnableMapObject, levelFlags, levelOverrides);
		}

		public static void RemoveOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null)
		{
			SpawnableOutsideObjectWithRarity mapObject2 = mapObject;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				string name = ((Object)val).name;
				bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false);
				if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag))
				{
					continue;
				}
				Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name)));
				if (flag || levelFlags.HasFlag(levelTypes))
				{
					val.spawnableOutsideObjects = val.spawnableOutsideObjects.Where((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn != (Object)(object)mapObject2.spawnableObject.prefabToSpawn).ToArray();
				}
			}
		}
	}
	public class NetworkPrefabs
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Start <0>__GameNetworkManager_Start;
		}

		private static List<GameObject> _networkPrefabs = new List<GameObject>();

		internal static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			object obj = <>O.<0>__GameNetworkManager_Start;
			if (obj == null)
			{
				hook_Start val = GameNetworkManager_Start;
				<>O.<0>__GameNetworkManager_Start = val;
				obj = (object)val;
			}
			GameNetworkManager.Start += (hook_Start)obj;
		}

		public static void RegisterNetworkPrefab(GameObject prefab)
		{
			if (!_networkPrefabs.Contains(prefab))
			{
				_networkPrefabs.Add(prefab);
			}
		}

		public static GameObject CreateNetworkPrefab(string name)
		{
			GameObject obj = PrefabUtils.CreatePrefab(name);
			obj.AddComponent<NetworkObject>();
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + name));
			obj.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			RegisterNetworkPrefab(obj);
			return obj;
		}

		public static GameObject CloneNetworkPrefab(GameObject prefabToClone, string newName = null)
		{
			GameObject val = PrefabUtils.ClonePrefab(prefabToClone, newName);
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + ((Object)val).name));
			val.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			RegisterNetworkPrefab(val);
			return val;
		}

		private static void GameNetworkManager_Start(orig_Start orig, GameNetworkManager self)
		{
			orig.Invoke(self);
			foreach (GameObject networkPrefab in _networkPrefabs)
			{
				if (!NetworkManager.Singleton.NetworkConfig.Prefabs.Contains(networkPrefab))
				{
					NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
				}
			}
		}
	}
	public class Player
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__StartOfRound_Awake;
		}

		public static Dictionary<string, GameObject> ragdollRefs = new Dictionary<string, GameObject>();

		public static Dictionary<string, int> ragdollIndexes = new Dictionary<string, int>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			object obj = <>O.<0>__StartOfRound_Awake;
			if (obj == null)
			{
				hook_Awake val = StartOfRound_Awake;
				<>O.<0>__StartOfRound_Awake = val;
				obj = (object)val;
			}
			StartOfRound.Awake += (hook_Awake)obj;
		}

		private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self)
		{
			orig.Invoke(self);
			foreach (KeyValuePair<string, GameObject> ragdollRef in ragdollRefs)
			{
				if (!self.playerRagdolls.Contains(ragdollRef.Value))
				{
					self.playerRagdolls.Add(ragdollRef.Value);
					int value = self.playerRagdolls.Count - 1;
					if (ragdollIndexes.ContainsKey(ragdollRef.Key))
					{
						ragdollIndexes[ragdollRef.Key] = value;
					}
					else
					{
						ragdollIndexes.Add(ragdollRef.Key, value);
					}
				}
			}
		}

		public static int GetRagdollIndex(string id)
		{
			return ragdollIndexes[id];
		}

		public static GameObject GetRagdoll(string id)
		{
			return ragdollRefs[id];
		}

		public static void RegisterPlayerRagdoll(string id, GameObject ragdoll)
		{
			Plugin.logger.LogInfo((object)("Registering player ragdoll " + id));
			ragdollRefs.Add(id, ragdoll);
		}
	}
	public class PrefabUtils
	{
		internal static Lazy<GameObject> _prefabParent;

		internal static GameObject prefabParent => _prefabParent.Value;

		static PrefabUtils()
		{
			_prefabParent = new Lazy<GameObject>((Func<GameObject>)delegate
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: 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)
				//IL_001a: Expected O, but got Unknown
				GameObject val = new GameObject("LethalLibGeneratedPrefabs")
				{
					hideFlags = (HideFlags)61
				};
				val.SetActive(false);
				return val;
			});
		}

		public static GameObject ClonePrefab(GameObject prefabToClone, string newName = null)
		{
			GameObject val = Object.Instantiate<GameObject>(prefabToClone, prefabParent.transform);
			((Object)val).hideFlags = (HideFlags)61;
			if (newName != null)
			{
				((Object)val).name = newName;
			}
			else
			{
				((Object)val).name = ((Object)prefabToClone).name;
			}
			return val;
		}

		public static GameObject CreatePrefab(string name)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_0024: Expected O, but got Unknown
			GameObject val = new GameObject(name)
			{
				hideFlags = (HideFlags)61
			};
			val.transform.SetParent(prefabParent.transform);
			return val;
		}
	}
	public class Shaders
	{
		public static void FixShaders(GameObject gameObject)
		{
			Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Material[] materials = componentsInChildren[i].materials;
				foreach (Material val in materials)
				{
					if (((Object)val.shader).name.Contains("Standard"))
					{
						val.shader = Shader.Find("HDRP/Lit");
					}
				}
			}
		}
	}
	public class TerminalUtils
	{
		public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, CompatibleNoun[] compatibleNouns = null, TerminalNode specialKeywordResult = null, TerminalKeyword defaultVerb = null, bool accessTerminalObjects = false)
		{
			TerminalKeyword obj = ScriptableObject.CreateInstance<TerminalKeyword>();
			((Object)obj).name = word;
			obj.word = word;
			obj.isVerb = isVerb;
			obj.compatibleNouns = compatibleNouns;
			obj.specialKeywordResult = specialKeywordResult;
			obj.defaultVerb = defaultVerb;
			obj.accessTerminalObjects = accessTerminalObjects;
			return obj;
		}
	}
	public enum StoreType
	{
		None,
		ShipUpgrade,
		Decor
	}
	public class Unlockables
	{
		public class RegisteredUnlockable
		{
			public UnlockableItem unlockable;

			public StoreType StoreType;

			public TerminalNode buyNode1;

			public TerminalNode buyNode2;

			public TerminalNode itemInfo;

			public int price;

			public string modName;

			public bool disabled;

			public RegisteredUnlockable(UnlockableItem unlockable, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
			{
				this.unlockable = unlockable;
				this.buyNode1 = buyNode1;
				this.buyNode2 = buyNode2;
				this.itemInfo = itemInfo;
				this.price = price;
			}
		}

		public struct BuyableUnlockableAssetInfo
		{
			public UnlockableItem itemAsset;

			public TerminalKeyword keyword;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_Awake <0>__Terminal_Awake;

			public static hook_TextPostProcess <1>__Terminal_TextPostProcess;
		}

		public static List<RegisteredUnlockable> registeredUnlockables = new List<RegisteredUnlockable>();

		public static List<BuyableUnlockableAssetInfo> buyableUnlockableAssetInfos = new List<BuyableUnlockableAssetInfo>();

		public static void Init()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			object obj = <>O.<0>__Terminal_Awake;
			if (obj == null)
			{
				hook_Awake val = Terminal_Awake;
				<>O.<0>__Terminal_Awake = val;
				obj = (object)val;
			}
			Terminal.Awake += (hook_Awake)obj;
			object obj2 = <>O.<1>__Terminal_TextPostProcess;
			if (obj2 == null)
			{
				hook_TextPostProcess val2 = Terminal_TextPostProcess;
				<>O.<1>__Terminal_TextPostProcess = val2;
				obj2 = (object)val2;
			}
			Terminal.TextPostProcess += (hook_TextPostProcess)obj2;
		}

		private static string Terminal_TextPostProcess(orig_TextPostProcess orig, Terminal self, string modifiedDisplayText, TerminalNode node)
		{
			if (modifiedDisplayText.Contains("[buyableItemsList]") && modifiedDisplayText.Contains("[unlockablesSelectionList]"))
			{
				int num = modifiedDisplayText.IndexOf(":");
				foreach (RegisteredUnlockable registeredUnlockable in registeredUnlockables)
				{
					if (registeredUnlockable.StoreType == StoreType.ShipUpgrade && !registeredUnlockable.disabled)
					{
						string unlockableName = registeredUnlockable.unlockable.unlockableName;
						int price = registeredUnlockable.price;
						string value = $"\n* {unlockableName}    //    Price: ${price}";
						modifiedDisplayText = modifiedDisplayText.Insert(num + 1, value);
					}
				}
			}
			return orig.Invoke(self, modifiedDisplayText, node);
		}

		private static void Terminal_Awake(orig_Awake orig, Terminal self)
		{
			//IL_0497: Unknown result type (might be due to invalid IL or missing references)
			//IL_049c: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04da: Expected O, but got Unknown
			//IL_04dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0516: Unknown result type (might be due to invalid IL or missing references)
			//IL_051e: Expected O, but got Unknown
			//IL_059a: Unknown result type (might be due to invalid IL or missing references)
			//IL_059f: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b9: Expected O, but got Unknown
			//IL_0645: Unknown result type (might be due to invalid IL or missing references)
			//IL_064a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0657: Unknown result type (might be due to invalid IL or missing references)
			//IL_0664: Expected O, but got Unknown
			StartOfRound instance = StartOfRound.Instance;
			Plugin.logger.LogInfo((object)$"Adding {registeredUnlockables.Count} unlockables to unlockables list");
			foreach (RegisteredUnlockable unlockable2 in registeredUnlockables)
			{
				if (instance.unlockablesList.unlockables.Any((UnlockableItem x) => x.unlockableName == unlockable2.unlockable.unlockableName))
				{
					Plugin.logger.LogInfo((object)("Unlockable " + unlockable2.unlockable.unlockableName + " already exists in unlockables list, skipping"));
					continue;
				}
				if ((Object)(object)unlockable2.unlockable.prefabObject != (Object)null)
				{
					PlaceableShipObject componentInChildren = unlockable2.unlockable.prefabObject.GetComponentInChildren<PlaceableShipObject>();
					if ((Object)(object)componentInChildren != (Object)null)
					{
						componentInChildren.unlockableID = instance.unlockablesList.unlockables.Count;
					}
				}
				instance.unlockablesList.unlockables.Add(unlockable2.unlockable);
			}
			TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result;
			TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			List<RegisteredUnlockable> list = registeredUnlockables.FindAll((RegisteredUnlockable unlockable) => unlockable.price != -1).ToList();
			Plugin.logger.LogInfo((object)$"Adding {list.Count} items to terminal");
			foreach (RegisteredUnlockable item in list)
			{
				string unlockableName = item.unlockable.unlockableName;
				TerminalKeyword keyword3 = TerminalUtils.CreateTerminalKeyword(unlockableName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val);
				if (self.terminalNodes.allKeywords.Any((TerminalKeyword kw) => kw.word == keyword3.word))
				{
					Plugin.logger.LogInfo((object)("Keyword " + keyword3.word + " already registed, skipping."));
					continue;
				}
				int shipUnlockableID = StartOfRound.Instance.unlockablesList.unlockables.FindIndex((UnlockableItem unlockable) => unlockable.unlockableName == item.unlockable.unlockableName);
				if ((Object)(object)StartOfRound.Instance == (Object)null)
				{
					Debug.Log((object)"STARTOFROUND INSTANCE NOT FOUND");
				}
				item.disabled = false;
				if (item.price == -1 && (Object)(object)item.buyNode1 != (Object)null)
				{
					item.price = item.buyNode1.itemCost;
				}
				_ = unlockableName[unlockableName.Length - 1];
				string text = unlockableName;
				TerminalNode val3 = item.buyNode2;
				if ((Object)(object)val3 == (Object)null)
				{
					val3 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val3).name = unlockableName.Replace(" ", "-") + "BuyNode2";
					val3.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n";
					val3.clearPreviousText = true;
					val3.maxCharactersToType = 15;
				}
				val3.buyItemIndex = -1;
				val3.shipUnlockableID = shipUnlockableID;
				val3.buyUnlockable = true;
				val3.creatureName = unlockableName;
				val3.isConfirmationNode = false;
				val3.itemCost = item.price;
				val3.playSyncedClip = 0;
				TerminalNode val4 = item.buyNode1;
				if ((Object)(object)val4 == (Object)null)
				{
					val4 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val4).name = unlockableName.Replace(" ", "-") + "BuyNode1";
					val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n";
					val4.clearPreviousText = true;
					val4.maxCharactersToType = 35;
				}
				val4.buyItemIndex = -1;
				val4.shipUnlockableID = shipUnlockableID;
				val4.creatureName = unlockableName;
				val4.isConfirmationNode = true;
				val4.overrideOptions = true;
				val4.itemCost = item.price;
				val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2]
				{
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"),
						result = val3
					},
					new CompatibleNoun
					{
						noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"),
						result = result
					}
				};
				if (item.StoreType == StoreType.Decor)
				{
					item.unlockable.shopSelectionNode = val4;
				}
				else
				{
					item.unlockable.shopSelectionNode = null;
				}
				List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList();
				list2.Add(keyword3);
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list3 = val.compatibleNouns.ToList();
				list3.Add(new CompatibleNoun
				{
					noun = keyword3,
					result = val4
				});
				val.compatibleNouns = list3.ToArray();
				TerminalNode val5 = item.itemInfo;
				if ((Object)(object)val5 == (Object)null)
				{
					val5 = ScriptableObject.CreateInstance<TerminalNode>();
					((Object)val5).name = unlockableName.Replace(" ", "-") + "InfoNode";
					val5.displayText = "[No information about this object was found.]\n\n";
					val5.clearPreviousText = true;
					val5.maxCharactersToType = 25;
				}
				self.terminalNodes.allKeywords = list2.ToArray();
				List<CompatibleNoun> list4 = val2.compatibleNouns.ToList();
				list4.Add(new CompatibleNoun
				{
					noun = keyword3,
					result = val5
				});
				val2.compatibleNouns = list4.ToArray();
				BuyableUnlockableAssetInfo buyableUnlockableAssetInfo = default(BuyableUnlockableAssetInfo);
				buyableUnlockableAssetInfo.itemAsset = item.unlockable;
				buyableUnlockableAssetInfo.keyword = keyword3;
				BuyableUnlockableAssetInfo item2 = buyableUnlockableAssetInfo;
				buyableUnlockableAssetInfos.Add(item2);
				Plugin.logger.LogInfo((object)(item.modName + " registered item: " + item.unlockable.unlockableName));
			}
			orig.Invoke(self);
		}

		public static void RegisterUnlockable(UnlockableItemDef unlockable, int price = -1, StoreType storeType = StoreType.None)
		{
			RegisterUnlockable(unlockable.unlockable, storeType, null, null, null, price);
		}

		public static void RegisterUnlockable(UnlockableItem unlockable, int price = -1, StoreType storeType = StoreType.None)
		{
			RegisterUnlockable(unlockable, storeType, null, null, null, price);
		}

		public static void RegisterUnlockable(UnlockableItemDef unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
		{
			RegisterUnlockable(unlockable.unlockable, storeType, buyNode1, buyNode2, itemInfo, price);
		}

		public static void RegisterUnlockable(UnlockableItem unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1)
		{
			RegisteredUnlockable registeredUnlockable = new RegisteredUnlockable(unlockable, buyNode1, buyNode2, itemInfo, price);
			string name = Assembly.GetCallingAssembly().GetName().Name;
			registeredUnlockable.modName = name;
			registeredUnlockable.StoreType = storeType;
			registeredUnlockables.Add(registeredUnlockable);
		}

		public static void DisableUnlockable(UnlockableItemDef unlockable)
		{
			DisableUnlockable(unlockable.unlockable);
		}

		public static void DisableUnlockable(UnlockableItem unlockable)
		{
			UnlockableItem unlockable2 = unlockable;
			if (!((Object)(object)StartOfRound.Instance != (Object)null))
			{
				return;
			}
			List<TerminalKeyword> list = Items.terminal.terminalNodes.allKeywords.ToList();
			TerminalKeyword obj = Items.terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info");
			TerminalKeyword val = Items.terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy");
			_ = val.compatibleNouns[0].result.terminalOptions[1].result;
			List<CompatibleNoun> list2 = val.compatibleNouns.ToList();
			List<CompatibleNoun> list3 = 

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/LethalSDK.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using DunGen;
using DunGen.Adapters;
using GameNetcodeStuff;
using LethalSDK.Component;
using LethalSDK.ScriptableObjects;
using LethalSDK.Utils;
using Unity.Netcode;
using UnityEditor;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("LethalSDK")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LethalSDK")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4d234a4d-c807-438a-b717-4c6d77706054")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
public class AssetModificationProcessor : AssetPostprocessor
{
	private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
	{
		foreach (string assetPath in importedAssets)
		{
			ProcessAsset(assetPath);
		}
		foreach (string assetPath2 in movedAssets)
		{
			ProcessAsset(assetPath2);
		}
	}

	private static void ProcessAsset(string assetPath)
	{
		if (assetPath.Contains("NavMesh-Environment"))
		{
			AssetDatabase.RenameAsset(assetPath, (SelectionLogger.name != string.Empty) ? (SelectionLogger.name + "NavMesh") : "New NavMesh");
		}
		if (assetPath.Contains("New Terrain"))
		{
			AssetDatabase.RenameAsset(assetPath, (SelectionLogger.name != string.Empty) ? SelectionLogger.name : "New Terrain");
		}
		if (assetPath.ToLower().StartsWith("assets/mods/") && assetPath.Split(new char[1] { '/' }).Length > 3 && !assetPath.ToLower().EndsWith(".unity") && !assetPath.ToLower().Contains("/scenes"))
		{
			AssetImporter atPath = AssetImporter.GetAtPath(assetPath);
			if ((Object)(object)atPath != (Object)null)
			{
				string text2 = (atPath.assetBundleName = ExtractBundleNameFromPath(assetPath));
				atPath.assetBundleVariant = "lem";
				Debug.Log((object)(assetPath + " asset moved to " + text2 + " asset bundle."));
			}
			if (assetPath != "Assets/Mods/" + assetPath.ToLower().Replace("assets/mods/", string.Empty).RemoveNonAlphanumeric(4))
			{
				AssetDatabase.MoveAsset(assetPath, "Assets/Mods/" + assetPath.ToLower().Replace("assets/mods/", string.Empty).RemoveNonAlphanumeric(4));
			}
		}
		else
		{
			AssetImporter atPath2 = AssetImporter.GetAtPath(assetPath);
			if ((Object)(object)atPath2 != (Object)null)
			{
				atPath2.assetBundleName = null;
				Debug.Log((object)(assetPath + " asset removed from asset bundle."));
			}
		}
	}

	public static string ExtractBundleNameFromPath(string path)
	{
		string[] array = path.Split(new char[1] { '/' });
		if (array.Length > 3)
		{
			return array[2].ToLower();
		}
		return "";
	}
}
[InitializeOnLoad]
public class SelectionLogger
{
	public static string name;

	static SelectionLogger()
	{
		Selection.selectionChanged = (Action)Delegate.Combine(Selection.selectionChanged, new Action(OnSelectionChanged));
	}

	private static void OnSelectionChanged()
	{
		if ((Object)(object)Selection.activeGameObject != (Object)null)
		{
			name = ((Object)GetRootParent(Selection.activeGameObject)).name;
		}
		else
		{
			name = string.Empty;
		}
	}

	public static GameObject GetRootParent(GameObject obj)
	{
		if ((Object)(object)obj != (Object)null && (Object)(object)obj.transform.parent != (Object)null)
		{
			return GetRootParent(((Component)obj.transform.parent).gameObject);
		}
		return obj;
	}
}
[InitializeOnLoad]
public class AssetBundleVariantAssigner
{
	static AssetBundleVariantAssigner()
	{
		AssignVariantToAssetBundles();
	}

	[InitializeOnLoadMethod]
	private static void AssignVariantToAssetBundles()
	{
		string[] allAssetBundleNames = AssetDatabase.GetAllAssetBundleNames();
		string[] array = allAssetBundleNames;
		foreach (string text in array)
		{
			if (!text.Contains("."))
			{
				string[] assetPathsFromAssetBundle = AssetDatabase.GetAssetPathsFromAssetBundle(text);
				string[] array2 = assetPathsFromAssetBundle;
				foreach (string text2 in array2)
				{
					AssetImporter.GetAtPath(text2).SetAssetBundleNameAndVariant(text, "lem");
				}
				Debug.Log((object)("File extention added to AssetBundle: " + text));
			}
		}
		AssetDatabase.SaveAssets();
		string text3 = "Assets/AssetBundles";
		if (!Directory.Exists(text3))
		{
			Debug.LogError((object)("Le dossier n'existe pas : " + text3));
			return;
		}
		string[] files = Directory.GetFiles(text3);
		string[] array3 = files;
		foreach (string text4 in array3)
		{
			if (Path.GetExtension(text4) == "" && Path.GetFileName(text4) != "AssetBundles")
			{
				string path = text4 + ".meta";
				string text5 = text4 + ".manifest";
				string path2 = text5 + ".meta";
				File.Delete(text4);
				if (File.Exists(path))
				{
					File.Delete(path);
				}
				if (File.Exists(text5))
				{
					File.Delete(text5);
				}
				if (File.Exists(path2))
				{
					File.Delete(path2);
				}
				Debug.Log((object)("Fichier supprimé : " + text4));
			}
		}
		AssetDatabase.Refresh();
	}
}
public class CubemapTextureBuilder : EditorWindow
{
	private Texture2D[] textures = (Texture2D[])(object)new Texture2D[6];

	private string[] labels = new string[6] { "Right", "Left", "Top", "Bottom", "Front", "Back" };

	private TextureFormat[] HDRFormats;

	private Vector2Int[] placementRects;

	[MenuItem("LethalSDK/Cubemap Builder", false, 100)]
	public static void OpenWindow()
	{
		EditorWindow.GetWindow<CubemapTextureBuilder>();
	}

	private Texture2D UpscaleTexture(Texture2D original, int targetWidth, int targetHeight)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Expected O, but got Unknown
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		RenderTexture val = (RenderTexture.active = RenderTexture.GetTemporary(targetWidth, targetHeight));
		Graphics.Blit((Texture)(object)original, val);
		Texture2D val2 = new Texture2D(targetWidth, targetHeight);
		val2.ReadPixels(new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), 0, 0);
		val2.Apply();
		RenderTexture.ReleaseTemporary(val);
		return val2;
	}

	private void OnGUI()
	{
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0256: Expected O, but got Unknown
		for (int i = 0; i < 6; i++)
		{
			ref Texture2D reference = ref textures[i];
			Object obj = EditorGUILayout.ObjectField(labels[i], (Object)(object)textures[i], typeof(Texture2D), false, Array.Empty<GUILayoutOption>());
			reference = (Texture2D)(object)((obj is Texture2D) ? obj : null);
		}
		if (!GUILayout.Button("Build Cubemap", Array.Empty<GUILayoutOption>()))
		{
			return;
		}
		if (textures.Any((Texture2D t) => (Object)(object)t == (Object)null))
		{
			EditorUtility.DisplayDialog("Cubemap Builder Error", "One or more texture is missing.", "Ok");
			return;
		}
		int size = ((Texture)textures[0]).width;
		if (textures.Any((Texture2D t) => ((Texture)t).width != size || ((Texture)t).height != size))
		{
			EditorUtility.DisplayDialog("Cubemap Builder Error", "All the textures need to be the same size and square.", "Ok");
			return;
		}
		bool flag = HDRFormats.Any((TextureFormat f) => f == textures[0].format);
		string[] array = textures.Select((Texture2D t) => AssetDatabase.GetAssetPath((Object)(object)t)).ToArray();
		string text = EditorUtility.SaveFilePanel("Save Cubemap", Path.GetDirectoryName(array[0]), "Cubemap", flag ? "exr" : "png");
		if (!string.IsNullOrEmpty(text))
		{
			bool[] array2 = textures.Select((Texture2D t) => ((Texture)t).isReadable).ToArray();
			TextureImporter[] array3 = array.Select(delegate(string p)
			{
				AssetImporter atPath2 = AssetImporter.GetAtPath(p);
				return (TextureImporter)(object)((atPath2 is TextureImporter) ? atPath2 : null);
			}).ToArray();
			TextureImporter[] array4 = array3;
			foreach (TextureImporter val in array4)
			{
				val.isReadable = true;
			}
			AssetDatabase.Refresh();
			string[] array5 = array;
			foreach (string text2 in array5)
			{
				AssetDatabase.ImportAsset(text2);
			}
			Texture2D val2 = new Texture2D(size * 4, size * 3, (TextureFormat)(flag ? 20 : 4), false);
			for (int l = 0; l < 6; l++)
			{
				val2.SetPixels(((Vector2Int)(ref placementRects[l])).x * size, ((Vector2Int)(ref placementRects[l])).y * size, size, size, textures[l].GetPixels(0));
			}
			val2.Apply(false);
			byte[] bytes = (flag ? ImageConversion.EncodeToEXR(val2) : ImageConversion.EncodeToPNG(val2));
			File.WriteAllBytes(text, bytes);
			Object.Destroy((Object)(object)val2);
			for (int m = 0; m < 6; m++)
			{
				array3[m].isReadable = array2[m];
			}
			text = text.Remove(0, Application.dataPath.Length - 6);
			AssetDatabase.ImportAsset(text);
			AssetImporter atPath = AssetImporter.GetAtPath(text);
			TextureImporter val3 = (TextureImporter)(object)((atPath is TextureImporter) ? atPath : null);
			val3.textureShape = (TextureImporterShape)2;
			val3.sRGBTexture = false;
			val3.generateCubemap = (TextureImporterGenerateCubemap)5;
			string[] array6 = array;
			foreach (string text3 in array6)
			{
				AssetDatabase.ImportAsset(text3);
			}
			AssetDatabase.ImportAsset(text);
			AssetDatabase.Refresh();
		}
	}

	public CubemapTextureBuilder()
	{
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: 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)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		TextureFormat[] array = new TextureFormat[9];
		RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
		HDRFormats = (TextureFormat[])(object)array;
		placementRects = (Vector2Int[])(object)new Vector2Int[6]
		{
			new Vector2Int(2, 1),
			new Vector2Int(0, 1),
			new Vector2Int(1, 2),
			new Vector2Int(1, 0),
			new Vector2Int(1, 1),
			new Vector2Int(3, 1)
		};
		((EditorWindow)this)..ctor();
	}
}
public class PlayerShip : MonoBehaviour
{
	public readonly Vector3 shipPosition = new Vector3(-17.5f, 5.75f, -16.55f);

	private void Start()
	{
		Object.Destroy((Object)(object)this);
	}
}
[CustomEditor(typeof(PlayerShip))]
public class PlayerShipEditor : Editor
{
	public override void OnInspectorGUI()
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		((Editor)this).OnInspectorGUI();
		PlayerShip playerShip = (PlayerShip)(object)((Editor)this).target;
		if (((Component)playerShip).transform.position != playerShip.shipPosition)
		{
			((Component)playerShip).transform.position = playerShip.shipPosition;
		}
	}
}
namespace LethalSDK.ScriptableObjects
{
	[CreateAssetMenu(fileName = "AssetBank", menuName = "LethalSDK/Asset Bank")]
	public class AssetBank : ScriptableObject
	{
		[Header("Audio Clips")]
		[SerializeField]
		private AudioClipInfoPair[] _audioClips = new AudioClipInfoPair[0];

		[SerializeField]
		private PlanetPrefabInfoPair[] _planetPrefabs = new PlanetPrefabInfoPair[0];

		[SerializeField]
		private PrefabInfoPair[] _networkPrefabs = new PrefabInfoPair[0];

		[HideInInspector]
		public string serializedAudioClips;

		[HideInInspector]
		public string serializedPlanetPrefabs;

		[HideInInspector]
		public string serializedNetworkPrefabs;

		private void OnValidate()
		{
			for (int i = 0; i < _audioClips.Length; i++)
			{
				_audioClips[i].AudioClipName = _audioClips[i].AudioClipName.RemoveNonAlphanumeric(1);
				_audioClips[i].AudioClipPath = _audioClips[i].AudioClipPath.RemoveNonAlphanumeric(4);
			}
			for (int j = 0; j < _planetPrefabs.Length; j++)
			{
				_planetPrefabs[j].PlanetPrefabName = _planetPrefabs[j].PlanetPrefabName.RemoveNonAlphanumeric(1);
				_planetPrefabs[j].PlanetPrefabPath = _planetPrefabs[j].PlanetPrefabPath.RemoveNonAlphanumeric(4);
			}
			for (int k = 0; k < _networkPrefabs.Length; k++)
			{
				_networkPrefabs[k].PrefabName = _networkPrefabs[k].PrefabName.RemoveNonAlphanumeric(1);
				_networkPrefabs[k].PrefabPath = _networkPrefabs[k].PrefabPath.RemoveNonAlphanumeric(4);
			}
			serializedAudioClips = string.Join(";", _audioClips.Select((AudioClipInfoPair p) => ((p.AudioClipName.Length != 0) ? p.AudioClipName : (((Object)(object)p.AudioClip != (Object)null) ? ((Object)p.AudioClip).name : "")) + "," + AssetDatabase.GetAssetPath((Object)(object)p.AudioClip)));
			serializedPlanetPrefabs = string.Join(";", _planetPrefabs.Select((PlanetPrefabInfoPair p) => ((p.PlanetPrefabName.Length != 0) ? p.PlanetPrefabName : (((Object)(object)p.PlanetPrefab != (Object)null) ? ((Object)p.PlanetPrefab).name : "")) + "," + AssetDatabase.GetAssetPath((Object)(object)p.PlanetPrefab)));
			serializedNetworkPrefabs = string.Join(";", _networkPrefabs.Select((PrefabInfoPair p) => ((p.PrefabName.Length != 0) ? p.PrefabName : (((Object)(object)p.Prefab != (Object)null) ? ((Object)p.Prefab).name : "")) + "," + AssetDatabase.GetAssetPath((Object)(object)p.Prefab)));
		}

		public AudioClipInfoPair[] AudioClips()
		{
			if (serializedAudioClips != null)
			{
				return (from s in serializedAudioClips.Split(new char[1] { ';' })
					select s.Split(new char[1] { ',' }) into split
					where split.Length == 2
					select new AudioClipInfoPair(split[0], split[1])).ToArray();
			}
			return new AudioClipInfoPair[0];
		}

		public bool HaveAudioClip(string audioClipName)
		{
			if (serializedAudioClips != null)
			{
				return AudioClips().Any((AudioClipInfoPair a) => a.AudioClipName == audioClipName);
			}
			return false;
		}

		public string AudioClipPath(string audioClipName)
		{
			if (serializedAudioClips != null)
			{
				return AudioClips().First((AudioClipInfoPair c) => c.AudioClipName == audioClipName).AudioClipPath;
			}
			return string.Empty;
		}

		public Dictionary<string, string> AudioClipsDictionary()
		{
			if (serializedAudioClips != null)
			{
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				AudioClipInfoPair[] audioClips = _audioClips;
				for (int i = 0; i < audioClips.Length; i++)
				{
					AudioClipInfoPair audioClipInfoPair = audioClips[i];
					dictionary.Add(audioClipInfoPair.AudioClipName, audioClipInfoPair.AudioClipPath);
				}
				return dictionary;
			}
			return new Dictionary<string, string>();
		}

		public PlanetPrefabInfoPair[] PlanetPrefabs()
		{
			if (serializedPlanetPrefabs != null)
			{
				return (from s in serializedPlanetPrefabs.Split(new char[1] { ';' })
					select s.Split(new char[1] { ',' }) into split
					where split.Length == 2
					select new PlanetPrefabInfoPair(split[0], split[1])).ToArray();
			}
			return new PlanetPrefabInfoPair[0];
		}

		public bool HavePlanetPrefabs(string planetPrefabName)
		{
			if (serializedPlanetPrefabs != null)
			{
				return PlanetPrefabs().Any((PlanetPrefabInfoPair a) => a.PlanetPrefabName == planetPrefabName);
			}
			return false;
		}

		public string PlanetPrefabsPath(string planetPrefabName)
		{
			if (serializedPlanetPrefabs != null)
			{
				return PlanetPrefabs().First((PlanetPrefabInfoPair c) => c.PlanetPrefabName == planetPrefabName).PlanetPrefabPath;
			}
			return string.Empty;
		}

		public Dictionary<string, string> PlanetPrefabsDictionary()
		{
			if (serializedPlanetPrefabs != null)
			{
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				PlanetPrefabInfoPair[] planetPrefabs = _planetPrefabs;
				for (int i = 0; i < planetPrefabs.Length; i++)
				{
					PlanetPrefabInfoPair planetPrefabInfoPair = planetPrefabs[i];
					dictionary.Add(planetPrefabInfoPair.PlanetPrefabName, planetPrefabInfoPair.PlanetPrefabPath);
				}
				return dictionary;
			}
			return new Dictionary<string, string>();
		}

		public PrefabInfoPair[] NetworkPrefabs()
		{
			if (serializedNetworkPrefabs != null)
			{
				return (from s in serializedNetworkPrefabs.Split(new char[1] { ';' })
					select s.Split(new char[1] { ',' }) into split
					where split.Length == 2
					select new PrefabInfoPair(split[0], split[1])).ToArray();
			}
			return new PrefabInfoPair[0];
		}

		public bool HaveNetworkPrefabs(string networkPrefabName)
		{
			if (serializedNetworkPrefabs != null)
			{
				return NetworkPrefabs().Any((PrefabInfoPair a) => a.PrefabName == networkPrefabName);
			}
			return false;
		}

		public string NetworkPrefabsPath(string networkPrefabName)
		{
			if (serializedNetworkPrefabs != null)
			{
				return NetworkPrefabs().First((PrefabInfoPair c) => c.PrefabName == networkPrefabName).PrefabPath;
			}
			return string.Empty;
		}

		public Dictionary<string, string> NetworkPrefabsDictionary()
		{
			if (serializedNetworkPrefabs != null)
			{
				Dictionary<string, string> dictionary = new Dictionary<string, string>();
				PrefabInfoPair[] networkPrefabs = _networkPrefabs;
				for (int i = 0; i < networkPrefabs.Length; i++)
				{
					PrefabInfoPair prefabInfoPair = networkPrefabs[i];
					dictionary.Add(prefabInfoPair.PrefabName, prefabInfoPair.PrefabPath);
				}
				return dictionary;
			}
			return new Dictionary<string, string>();
		}
	}
	[CreateAssetMenu(fileName = "ModManifest", menuName = "LethalSDK/Mod Manifest")]
	public class ModManifest : ScriptableObject
	{
		public string modName = "New Mod";

		[Space]
		[SerializeField]
		private SerializableVersion version = new SerializableVersion(0, 0, 0, 0);

		[HideInInspector]
		public string serializedVersion;

		[Space]
		public string author = "Author";

		[Space]
		[TextArea(5, 15)]
		public string description = "Mod Description";

		[Space]
		[Header("Content")]
		public Scrap[] scraps = new Scrap[0];

		public Moon[] moons = new Moon[0];

		[Space]
		public AssetBank assetBank;

		private void OnValidate()
		{
			serializedVersion = version.ToString();
		}

		public SerializableVersion GetVersion()
		{
			int[] array = ((serializedVersion != null) ? serializedVersion.Split(new char[1] { '.' }).Select(int.Parse).ToArray() : new int[4]);
			return new SerializableVersion(array[0], array[1], array[2], array[3]);
		}
	}
	[CreateAssetMenu(fileName = "New Moon", menuName = "LethalSDK/Moon")]
	public class Moon : ScriptableObject
	{
		public string MoonName = "NewMoon";

		public string[] RequiredBundles;

		public string[] IncompatibleBundles;

		public bool IsEnabled = true;

		public bool IsHidden = false;

		public bool IsLocked = false;

		[Header("Info")]
		public string OrbitPrefabName = "Moon1";

		public bool SpawnEnemiesAndScrap = true;

		public string PlanetName = "New Moon";

		public GameObject MainPrefab;

		[TextArea(5, 15)]
		public string PlanetDescription;

		public VideoClip PlanetVideo;

		public string RiskLevel = "X";

		[Range(0f, 16f)]
		public float TimeToArrive = 1f;

		[Header("Time")]
		[Range(0.1f, 5f)]
		public float DaySpeedMultiplier = 1f;

		public bool PlanetHasTime = true;

		[SerializeField]
		private RandomWeatherPair[] _RandomWeatherTypes = new RandomWeatherPair[6]
		{
			new RandomWeatherPair(LevelWeatherType.None, 0, 0),
			new RandomWeatherPair(LevelWeatherType.Rainy, 0, 0),
			new RandomWeatherPair(LevelWeatherType.Stormy, 1, 0),
			new RandomWeatherPair(LevelWeatherType.Foggy, 1, 0),
			new RandomWeatherPair(LevelWeatherType.Flooded, -4, 5),
			new RandomWeatherPair(LevelWeatherType.Eclipsed, 1, 0)
		};

		public bool OverwriteWeather = false;

		public LevelWeatherType OverwriteWeatherType = LevelWeatherType.None;

		[Header("Route")]
		public string RouteWord = "newmoon";

		public int RoutePrice;

		public string BoughtComment = "Please enjoy your flight.";

		[Header("Dungeon")]
		[Range(1f, 5f)]
		public float FactorySizeMultiplier = 1f;

		public int FireExitsAmountOverwrite = 1;

		[SerializeField]
		private DungeonFlowPair[] _DungeonFlowTypes = new DungeonFlowPair[2]
		{
			new DungeonFlowPair(0, 300),
			new DungeonFlowPair(1, 1)
		};

		[SerializeField]
		private SpawnableScrapPair[] _SpawnableScrap = new SpawnableScrapPair[19]
		{
			new SpawnableScrapPair("Cog1", 80),
			new SpawnableScrapPair("EnginePart1", 90),
			new SpawnableScrapPair("FishTestProp", 12),
			new SpawnableScrapPair("MetalSheet", 88),
			new SpawnableScrapPair("FlashLaserPointer", 4),
			new SpawnableScrapPair("BigBolt", 80),
			new SpawnableScrapPair("BottleBin", 19),
			new SpawnableScrapPair("Ring", 3),
			new SpawnableScrapPair("SteeringWheel", 32),
			new SpawnableScrapPair("MoldPan", 5),
			new SpawnableScrapPair("EggBeater", 10),
			new SpawnableScrapPair("PickleJar", 10),
			new SpawnableScrapPair("DustPan", 32),
			new SpawnableScrapPair("Airhorn", 3),
			new SpawnableScrapPair("ClownHorn", 3),
			new SpawnableScrapPair("CashRegister", 3),
			new SpawnableScrapPair("Candy", 2),
			new SpawnableScrapPair("GoldBar", 1),
			new SpawnableScrapPair("YieldSign", 6)
		};

		public string[] spawnableScrapBlacklist = new string[0];

		[Range(0f, 100f)]
		public int MinScrap = 8;

		[Range(0f, 100f)]
		public int MaxScrap = 12;

		public string LevelAmbienceClips = "Level1TypeAmbience";

		[Range(0f, 30f)]
		public int MaxEnemyPowerCount = 4;

		[SerializeField]
		private SpawnableEnemiesPair[] _Enemies = new SpawnableEnemiesPair[8]
		{
			new SpawnableEnemiesPair("Centipede", 51),
			new SpawnableEnemiesPair("SandSpider", 58),
			new SpawnableEnemiesPair("HoarderBug", 28),
			new SpawnableEnemiesPair("Flowerman", 13),
			new SpawnableEnemiesPair("Crawler", 16),
			new SpawnableEnemiesPair("Blob", 31),
			new SpawnableEnemiesPair("DressGirl", 1),
			new SpawnableEnemiesPair("Puffer", 28)
		};

		public AnimationCurve EnemySpawnChanceThroughoutDay = CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0015411376953125,\"value\":-3.0,\"inSlope\":19.556997299194337,\"outSlope\":19.556997299194337,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0,\"outWeight\":0.12297855317592621},{\"serializedVersion\":\"3\",\"time\":0.4575331211090088,\"value\":4.796203136444092,\"inSlope\":24.479534149169923,\"outSlope\":24.479534149169923,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.396077424287796,\"outWeight\":0.35472238063812258},{\"serializedVersion\":\"3\",\"time\":0.7593884468078613,\"value\":4.973001480102539,\"inSlope\":2.6163148880004885,\"outSlope\":2.6163148880004885,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.2901076376438141,\"outWeight\":0.5360636115074158},{\"serializedVersion\":\"3\",\"time\":1.0,\"value\":15.0,\"inSlope\":35.604026794433597,\"outSlope\":35.604026794433597,\"tangentMode\":0,\"weightedMode\":1,\"inWeight\":0.04912583902478218,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}");

		[Range(0f, 30f)]
		public float SpawnProbabilityRange = 4f;

		[Header("Outside")]
		[SerializeField]
		private SpawnableMapObjectPair[] _SpawnableMapObjects = new SpawnableMapObjectPair[2]
		{
			new SpawnableMapObjectPair("Landmine", spawnFacingAwayFromWall: false, CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":-0.003082275390625,\"value\":0.0,\"inSlope\":0.23179344832897187,\"outSlope\":0.23179344832897187,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27936428785324099},{\"serializedVersion\":\"3\",\"time\":0.8171924352645874,\"value\":1.7483322620391846,\"inSlope\":7.064207077026367,\"outSlope\":7.064207077026367,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.2631833553314209,\"outWeight\":0.6898177862167358},{\"serializedVersion\":\"3\",\"time\":1.0002186298370362,\"value\":11.760997772216797,\"inSlope\":968.80810546875,\"outSlope\":968.80810546875,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.029036391526460649,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableMapObjectPair("TurretContainer", spawnFacingAwayFromWall: true, CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.354617178440094,\"outSlope\":0.354617178440094,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.9190289974212647,\"value\":1.0005745887756348,\"inSlope\":Infinity,\"outSlope\":1.7338485717773438,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0,\"outWeight\":0.6534967422485352},{\"serializedVersion\":\"3\",\"time\":1.0038425922393799,\"value\":7.198680877685547,\"inSlope\":529.4945068359375,\"outSlope\":529.4945068359375,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.14589552581310273,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}"))
		};

		[SerializeField]
		private SpawnableOutsideObjectPair[] _SpawnableOutsideObjects = new SpawnableOutsideObjectPair[7]
		{
			new SpawnableOutsideObjectPair("LargeRock1", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.7571572661399841,\"value\":0.6448163986206055,\"inSlope\":2.974250078201294,\"outSlope\":2.974250078201294,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.3333333432674408,\"outWeight\":0.3333333432674408},{\"serializedVersion\":\"3\",\"time\":0.9995536804199219,\"value\":5.883961200714111,\"inSlope\":65.30631256103516,\"outSlope\":65.30631256103516,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.12097536772489548,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("LargeRock2", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.7562879920005798,\"value\":1.2308543920516968,\"inSlope\":5.111926555633545,\"outSlope\":5.111926555633545,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.3333333432674408,\"outWeight\":0.21955738961696626},{\"serializedVersion\":\"3\",\"time\":1.0010795593261719,\"value\":7.59307336807251,\"inSlope\":92.0470199584961,\"outSlope\":92.0470199584961,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.05033162236213684,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("LargeRock3", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.9964686632156372,\"value\":2.0009398460388185,\"inSlope\":6.82940673828125,\"outSlope\":6.82940673828125,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.06891261041164398,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("LargeRock4", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.9635604619979858,\"value\":2.153383493423462,\"inSlope\":6.251225471496582,\"outSlope\":6.251225471496582,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.07428120821714401,\"outWeight\":0.3333333432674408},{\"serializedVersion\":\"3\",\"time\":0.9995394349098206,\"value\":5.0,\"inSlope\":15.746581077575684,\"outSlope\":15.746581077575684,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.06317413598299027,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("TreeLeafless1", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":1.6912956237792969,\"outSlope\":1.6912956237792969,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27726083993911745},{\"serializedVersion\":\"3\",\"time\":0.776531994342804,\"value\":6.162014007568359,\"inSlope\":30.075166702270509,\"outSlope\":30.075166702270509,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.15920747816562653,\"outWeight\":0.5323987007141113},{\"serializedVersion\":\"3\",\"time\":1.0002281665802003,\"value\":38.093849182128909,\"inSlope\":1448.839111328125,\"outSlope\":1448.839111328125,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0620061457157135,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("SmallGreyRocks1", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":1.6912956237792969,\"outSlope\":1.6912956237792969,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27726083993911745},{\"serializedVersion\":\"3\",\"time\":0.802714467048645,\"value\":1.5478605031967164,\"inSlope\":9.096116065979004,\"outSlope\":9.096116065979004,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.15920747816562653,\"outWeight\":0.58766108751297},{\"serializedVersion\":\"3\",\"time\":1.0002281665802003,\"value\":14.584033966064454,\"inSlope\":1244.9173583984375,\"outSlope\":1244.9173583984375,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.054620321840047839,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")),
			new SpawnableOutsideObjectPair("GiantPumpkin", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":1.6912956237792969,\"outSlope\":1.6912956237792969,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27726083993911745},{\"serializedVersion\":\"3\",\"time\":0.8832725882530212,\"value\":0.5284063816070557,\"inSlope\":3.2962090969085695,\"outSlope\":29.38977813720703,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.19772815704345704,\"outWeight\":0.8989489078521729},{\"serializedVersion\":\"3\",\"time\":0.972209095954895,\"value\":6.7684478759765629,\"inSlope\":140.27394104003907,\"outSlope\":140.27394104003907,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.39466607570648196,\"outWeight\":0.47049039602279665},{\"serializedVersion\":\"3\",\"time\":1.0002281665802003,\"value\":23.0,\"inSlope\":579.3037109375,\"outSlope\":14.8782377243042,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.648808479309082,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}"))
		};

		[Range(0f, 30f)]
		public int MaxOutsideEnemyPowerCount = 8;

		[Range(0f, 30f)]
		public int MaxDaytimeEnemyPowerCount = 5;

		[SerializeField]
		private SpawnableEnemiesPair[] _OutsideEnemies = new SpawnableEnemiesPair[3]
		{
			new SpawnableEnemiesPair("MouthDog", 75),
			new SpawnableEnemiesPair("ForestGiant", 0),
			new SpawnableEnemiesPair("SandWorm", 56)
		};

		[SerializeField]
		private SpawnableEnemiesPair[] _DaytimeEnemies = new SpawnableEnemiesPair[3]
		{
			new SpawnableEnemiesPair("RedLocustBees", 22),
			new SpawnableEnemiesPair("Doublewing", 74),
			new SpawnableEnemiesPair("DocileLocustBees", 52)
		};

		public AnimationCurve OutsideEnemySpawnChanceThroughDay = CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":-7.736962288618088e-7,\"value\":-2.996999979019165,\"inSlope\":Infinity,\"outSlope\":0.5040292143821716,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0,\"outWeight\":0.08937685936689377},{\"serializedVersion\":\"3\",\"time\":0.7105481624603272,\"value\":-0.6555822491645813,\"inSlope\":9.172262191772461,\"outSlope\":9.172262191772461,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.3333333432674408,\"outWeight\":0.7196550369262695},{\"serializedVersion\":\"3\",\"time\":1.0052626132965088,\"value\":5.359400749206543,\"inSlope\":216.42247009277345,\"outSlope\":11.374387741088868,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.044637180864810947,\"outWeight\":0.48315444588661196}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}");

		public AnimationCurve DaytimeEnemySpawnChanceThroughDay = CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":2.2706568241119386,\"inSlope\":-7.500085353851318,\"outSlope\":-7.500085353851318,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.3333333432674408,\"outWeight\":0.20650266110897065},{\"serializedVersion\":\"3\",\"time\":0.38507816195487978,\"value\":-0.0064108967781066898,\"inSlope\":-2.7670974731445314,\"outSlope\":-2.7670974731445314,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.28388944268226626,\"outWeight\":0.30659767985343935},{\"serializedVersion\":\"3\",\"time\":0.6767024993896484,\"value\":-7.021658420562744,\"inSlope\":-27.286888122558595,\"outSlope\":-27.286888122558595,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.10391546785831452,\"outWeight\":0.12503522634506226},{\"serializedVersion\":\"3\",\"time\":0.9998173117637634,\"value\":-14.818100929260254,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}");

		[Range(0f, 30f)]
		public float DaytimeEnemiesProbabilityRange = 5f;

		public bool LevelIncludesSnowFootprints = false;

		[HideInInspector]
		public string serializedRandomWeatherTypes;

		[HideInInspector]
		public string serializedDungeonFlowTypes;

		[HideInInspector]
		public string serializedSpawnableScrap;

		[HideInInspector]
		public string serializedEnemies;

		[HideInInspector]
		public string serializedOutsideEnemies;

		[HideInInspector]
		public string serializedDaytimeEnemies;

		[HideInInspector]
		public string serializedSpawnableMapObjects;

		[HideInInspector]
		public string serializedSpawnableOutsideObjects;

		private void OnValidate()
		{
			RequiredBundles = RequiredBundles.RemoveNonAlphanumeric(1);
			IncompatibleBundles = IncompatibleBundles.RemoveNonAlphanumeric(1);
			MoonName = MoonName.RemoveNonAlphanumeric(1);
			OrbitPrefabName = OrbitPrefabName.RemoveNonAlphanumeric(1);
			RiskLevel = RiskLevel.RemoveNonAlphanumeric();
			RouteWord = RouteWord.RemoveNonAlphanumeric(2);
			BoughtComment = BoughtComment.RemoveNonAlphanumeric();
			LevelAmbienceClips = LevelAmbienceClips.RemoveNonAlphanumeric(1);
			TimeToArrive = Mathf.Clamp(TimeToArrive, 0f, 16f);
			DaySpeedMultiplier = Mathf.Clamp(DaySpeedMultiplier, 0.1f, 5f);
			RoutePrice = Mathf.Clamp(RoutePrice, 0, int.MaxValue);
			FactorySizeMultiplier = Mathf.Clamp(FactorySizeMultiplier, 1f, 5f);
			FireExitsAmountOverwrite = Mathf.Clamp(FireExitsAmountOverwrite, 0, 20);
			MinScrap = Mathf.Clamp(MinScrap, 0, MaxScrap);
			MaxScrap = Mathf.Clamp(MaxScrap, MinScrap, 100);
			MaxEnemyPowerCount = Mathf.Clamp(MaxEnemyPowerCount, 0, 30);
			MaxOutsideEnemyPowerCount = Mathf.Clamp(MaxOutsideEnemyPowerCount, 0, 30);
			MaxDaytimeEnemyPowerCount = Mathf.Clamp(MaxDaytimeEnemyPowerCount, 0, 30);
			SpawnProbabilityRange = Mathf.Clamp(SpawnProbabilityRange, 0f, 30f);
			DaytimeEnemiesProbabilityRange = Mathf.Clamp(DaytimeEnemiesProbabilityRange, 0f, 30f);
			for (int i = 0; i < _SpawnableScrap.Length; i++)
			{
				_SpawnableScrap[i].ObjectName = _SpawnableScrap[i].ObjectName.RemoveNonAlphanumeric(1);
			}
			for (int j = 0; j < _Enemies.Length; j++)
			{
				_Enemies[j].EnemyName = _Enemies[j].EnemyName.RemoveNonAlphanumeric(1);
			}
			for (int k = 0; k < _SpawnableMapObjects.Length; k++)
			{
				_SpawnableMapObjects[k].ObjectName = _SpawnableMapObjects[k].ObjectName.RemoveNonAlphanumeric(1);
			}
			for (int l = 0; l < _SpawnableOutsideObjects.Length; l++)
			{
				_SpawnableOutsideObjects[l].ObjectName = _SpawnableOutsideObjects[l].ObjectName.RemoveNonAlphanumeric(1);
			}
			for (int m = 0; m < _OutsideEnemies.Length; m++)
			{
				_OutsideEnemies[m].EnemyName = _OutsideEnemies[m].EnemyName.RemoveNonAlphanumeric(1);
			}
			for (int n = 0; n < _DaytimeEnemies.Length; n++)
			{
				_DaytimeEnemies[n].EnemyName = _DaytimeEnemies[n].EnemyName.RemoveNonAlphanumeric(1);
			}
			serializedRandomWeatherTypes = string.Join(";", _RandomWeatherTypes.Select((RandomWeatherPair p) => $"{(int)p.Weather},{p.WeatherVariable1},{p.WeatherVariable2}"));
			serializedDungeonFlowTypes = string.Join(";", _DungeonFlowTypes.Select((DungeonFlowPair p) => $"{p.ID},{p.Rarity}"));
			serializedSpawnableScrap = string.Join(";", _SpawnableScrap.Select((SpawnableScrapPair p) => $"{p.ObjectName},{p.SpawnWeight}"));
			serializedEnemies = string.Join(";", _Enemies.Select((SpawnableEnemiesPair p) => $"{p.EnemyName},{p.SpawnWeight}"));
			serializedOutsideEnemies = string.Join(";", _OutsideEnemies.Select((SpawnableEnemiesPair p) => $"{p.EnemyName},{p.SpawnWeight}"));
			serializedDaytimeEnemies = string.Join(";", _DaytimeEnemies.Select((SpawnableEnemiesPair p) => $"{p.EnemyName},{p.SpawnWeight}"));
			serializedSpawnableMapObjects = string.Join(";", _SpawnableMapObjects.Select((SpawnableMapObjectPair p) => $"{p.ObjectName}|{p.SpawnFacingAwayFromWall}|{CurveContainer.SerializeCurve(p.SpawnRate)}"));
			serializedSpawnableOutsideObjects = string.Join(";", _SpawnableOutsideObjects.Select((SpawnableOutsideObjectPair p) => p.ObjectName + "|" + CurveContainer.SerializeCurve(p.SpawnRate)));
		}

		public RandomWeatherPair[] RandomWeatherTypes()
		{
			return (from s in serializedRandomWeatherTypes.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 3
				select new RandomWeatherPair((LevelWeatherType)int.Parse(split[0]), int.Parse(split[1]), int.Parse(split[2]))).ToArray();
		}

		public DungeonFlowPair[] DungeonFlowTypes()
		{
			return (from s in serializedDungeonFlowTypes.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new DungeonFlowPair(int.Parse(split[0]), int.Parse(split[1]))).ToArray();
		}

		public SpawnableScrapPair[] SpawnableScrap()
		{
			return (from s in serializedSpawnableScrap.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new SpawnableScrapPair(split[0], int.Parse(split[1]))).ToArray();
		}

		public SpawnableEnemiesPair[] Enemies()
		{
			return (from s in serializedEnemies.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new SpawnableEnemiesPair(split[0], int.Parse(split[1]))).ToArray();
		}

		public SpawnableEnemiesPair[] OutsideEnemies()
		{
			return (from s in serializedOutsideEnemies.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new SpawnableEnemiesPair(split[0], int.Parse(split[1]))).ToArray();
		}

		public SpawnableEnemiesPair[] DaytimeEnemies()
		{
			return (from s in serializedDaytimeEnemies.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new SpawnableEnemiesPair(split[0], int.Parse(split[1]))).ToArray();
		}

		public SpawnableMapObjectPair[] SpawnableMapObjects()
		{
			return (from s in serializedSpawnableMapObjects.Split(new char[1] { ';' })
				select s.Split(new char[1] { '|' }) into split
				where split.Length == 3
				select new SpawnableMapObjectPair(split[0], bool.Parse(split[1]), CurveContainer.DeserializeCurve(split[2]))).ToArray();
		}

		public SpawnableOutsideObjectPair[] SpawnableOutsideObjects()
		{
			return (from s in serializedSpawnableOutsideObjects.Split(new char[1] { ';' })
				select s.Split(new char[1] { '|' }) into split
				where split.Length == 2
				select new SpawnableOutsideObjectPair(split[0], CurveContainer.DeserializeCurve(split[1]))).ToArray();
		}
	}
	[CreateAssetMenu(fileName = "New Scrap", menuName = "LethalSDK/Scrap")]
	public class Scrap : ScriptableObject
	{
		public string[] RequiredBundles;

		public string[] IncompatibleBundles;

		[Header("Base")]
		public ScrapType scrapType = ScrapType.Normal;

		public string itemName = string.Empty;

		public int minValue = 0;

		public int maxValue = 0;

		public bool twoHanded = false;

		public GrabAnim HandedAnimation = GrabAnim.OneHanded;

		public bool requiresBattery = false;

		public bool isConductiveMetal = false;

		public int weight = 0;

		public GameObject prefab;

		[Header("Sounds")]
		public string grabSFX = string.Empty;

		public string dropSFX = string.Empty;

		[Header("Offsets")]
		public float verticalOffset = 0f;

		public Vector3 restingRotation = Vector3.zero;

		public Vector3 positionOffset = Vector3.zero;

		public Vector3 rotationOffset = Vector3.zero;

		[Header("Variants")]
		public Mesh[] meshVariants = (Mesh[])(object)new Mesh[0];

		public Material[] materialVariants = (Material[])(object)new Material[0];

		[Header("Spawn rate")]
		public bool useGlobalSpawnWeight = true;

		[Range(0f, 100f)]
		public int globalSpawnWeight = 10;

		[SerializeField]
		private ScrapSpawnChancePerScene[] _perPlanetSpawnWeight = new ScrapSpawnChancePerScene[9]
		{
			new ScrapSpawnChancePerScene("41 Experimentation", 10),
			new ScrapSpawnChancePerScene("220 Assurance", 10),
			new ScrapSpawnChancePerScene("56 Vow", 10),
			new ScrapSpawnChancePerScene("21 Offense", 10),
			new ScrapSpawnChancePerScene("61 March", 10),
			new ScrapSpawnChancePerScene("85 Rend", 10),
			new ScrapSpawnChancePerScene("7 Dine", 10),
			new ScrapSpawnChancePerScene("8 Titan", 10),
			new ScrapSpawnChancePerScene("Others", 10)
		};

		public string[] playetSpawnBlacklist = new string[0];

		[Header("Shovel")]
		public int shovelHitForce = 1;

		public AudioSource shovelAudio;

		public string reelUp = "ShovelReelUp";

		public string swing = "ShovelSwing";

		public string[] hitSFX = new string[2] { "ShovelHitDefault", "ShovelHitDefault2" };

		[Header("Flashlight")]
		public bool usingPlayerHelmetLight = false;

		public int flashlightInterferenceLevel = 0;

		public Light flashlightBulb;

		public Light flashlightBulbGlow;

		public AudioSource flashlightAudio;

		public string[] flashlightClips = new string[1] { "FlashlightClick" };

		public string outOfBatteriesClip = "FlashlightOutOfBatteries";

		public string flashlightFlicker = "FlashlightFlicker";

		public Material bulbLight;

		public Material bulbDark;

		public MeshRenderer flashlightMesh;

		public int flashlightTypeID = 0;

		public bool changeMaterial = true;

		[Header("Noisemaker")]
		public AudioSource noiseAudio;

		public AudioSource noiseAudioFar;

		public string[] noiseSFX = new string[1] { "ClownHorn1" };

		public string[] noiseSFXFar = new string[1] { "ClownHornFar" };

		public float noiseRange = 60f;

		public float maxLoudness = 1f;

		public float minLoudness = 0.6f;

		public float minPitch = 0.93f;

		public float maxPitch = 1f;

		public Animator triggerAnimator;

		[Header("WhoopieCushion")]
		public AudioSource whoopieCushionAudio;

		public string[] fartAudios = new string[4] { "Fart1", "Fart2", "Fart3", "Fart5" };

		[HideInInspector]
		public string serializedData;

		private void OnValidate()
		{
			RequiredBundles = RequiredBundles.RemoveNonAlphanumeric(1);
			IncompatibleBundles = IncompatibleBundles.RemoveNonAlphanumeric(1);
			itemName = itemName.RemoveNonAlphanumeric(1);
			grabSFX = grabSFX.RemoveNonAlphanumeric(1);
			dropSFX = dropSFX.RemoveNonAlphanumeric(1);
			for (int i = 0; i < _perPlanetSpawnWeight.Length; i++)
			{
				_perPlanetSpawnWeight[i].SceneName = _perPlanetSpawnWeight[i].SceneName.RemoveNonAlphanumeric(1);
			}
			serializedData = string.Join(";", _perPlanetSpawnWeight.Select((ScrapSpawnChancePerScene p) => $"{p.SceneName},{p.SpawnWeight}"));
		}

		public ScrapSpawnChancePerScene[] perPlanetSpawnWeight()
		{
			return (from s in serializedData.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new ScrapSpawnChancePerScene(split[0], int.Parse(split[1]))).ToArray();
		}
	}
	public enum ScrapType
	{
		Normal,
		Shovel,
		Flashlight,
		Noisemaker,
		WhoopieCushion
	}
	public enum GrabAnim
	{
		OneHanded,
		TwoHanded,
		Shotgun,
		Jetpack,
		Clipboard
	}
}
namespace LethalSDK.Utils
{
	public static class AssetGatherDialog
	{
		public static Dictionary<string, AudioClip> audioClips = new Dictionary<string, AudioClip>();

		public static Dictionary<string, (AudioMixer, AudioMixerGroup[])> audioMixers = new Dictionary<string, (AudioMixer, AudioMixerGroup[])>();

		public static Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();
	}
	[Serializable]
	public class SerializableVersion
	{
		public int Major = 1;

		public int Minor = 0;

		public int Build = 0;

		public int Revision = 0;

		public SerializableVersion(int major, int minor, int build, int revision)
		{
			Major = major;
			Minor = minor;
			Build = build;
			Revision = revision;
		}

		public Version ToVersion()
		{
			return new Version(Major, Minor, Build, Revision);
		}

		public override string ToString()
		{
			return $"{Major}.{Minor}.{Build}.{Revision}";
		}
	}
	[Serializable]
	public class CurveContainer
	{
		public AnimationCurve curve;

		public static string SerializeCurve(AnimationCurve curve)
		{
			CurveContainer curveContainer = new CurveContainer
			{
				curve = curve
			};
			return JsonUtility.ToJson((object)curveContainer);
		}

		public static AnimationCurve DeserializeCurve(string json)
		{
			CurveContainer curveContainer = JsonUtility.FromJson<CurveContainer>(json);
			return curveContainer.curve;
		}
	}
	[Serializable]
	public struct StringIntPair
	{
		public string _string;

		public int _int;

		public StringIntPair(string _string, int _int)
		{
			this._string = _string.RemoveNonAlphanumeric(1);
			this._int = Mathf.Clamp(_int, 0, 100);
		}
	}
	[Serializable]
	public struct StringStringPair
	{
		public string _string1;

		public string _string2;

		public StringStringPair(string _string1, string _string2)
		{
			this._string1 = _string1.RemoveNonAlphanumeric(1);
			this._string2 = _string2.RemoveNonAlphanumeric(1);
		}
	}
	[Serializable]
	public struct IntIntPair
	{
		public int _int1;

		public int _int2;

		public IntIntPair(int _int1, int _int2)
		{
			this._int1 = _int1;
			this._int2 = _int2;
		}
	}
	[Serializable]
	public struct DungeonFlowPair
	{
		public int ID;

		[Range(0f, 300f)]
		public int Rarity;

		public DungeonFlowPair(int id, int rarity)
		{
			ID = id;
			Rarity = Mathf.Clamp(rarity, 0, 300);
		}
	}
	[Serializable]
	public struct SpawnableScrapPair
	{
		public string ObjectName;

		[Range(0f, 100f)]
		public int SpawnWeight;

		public SpawnableScrapPair(string objectName, int spawnWeight)
		{
			ObjectName = objectName.RemoveNonAlphanumeric(1);
			SpawnWeight = Mathf.Clamp(spawnWeight, 0, 100);
		}
	}
	[Serializable]
	public struct SpawnableMapObjectPair
	{
		public string ObjectName;

		public bool SpawnFacingAwayFromWall;

		public AnimationCurve SpawnRate;

		public SpawnableMapObjectPair(string objectName, bool spawnFacingAwayFromWall, AnimationCurve spawnRate)
		{
			ObjectName = objectName.RemoveNonAlphanumeric(1);
			SpawnFacingAwayFromWall = spawnFacingAwayFromWall;
			SpawnRate = spawnRate;
		}
	}
	[Serializable]
	public struct SpawnableOutsideObjectPair
	{
		public string ObjectName;

		public AnimationCurve SpawnRate;

		public SpawnableOutsideObjectPair(string objectName, AnimationCurve spawnRate)
		{
			ObjectName = objectName.RemoveNonAlphanumeric(1);
			SpawnRate = spawnRate;
		}
	}
	[Serializable]
	public struct SpawnableEnemiesPair
	{
		public string EnemyName;

		[Range(0f, 100f)]
		public int SpawnWeight;

		public SpawnableEnemiesPair(string enemyName, int spawnWeight)
		{
			EnemyName = enemyName.RemoveNonAlphanumeric(1);
			SpawnWeight = Mathf.Clamp(spawnWeight, 0, 100);
		}
	}
	[Serializable]
	public struct ScrapSpawnChancePerScene
	{
		public string SceneName;

		[Range(0f, 100f)]
		public int SpawnWeight;

		public ScrapSpawnChancePerScene(string sceneName, int spawnWeight)
		{
			SceneName = sceneName.RemoveNonAlphanumeric(1);
			SpawnWeight = Mathf.Clamp(spawnWeight, 0, 100);
		}
	}
	[Serializable]
	public struct ScrapInfoPair
	{
		public string ScrapPath;

		public Scrap Scrap;

		public ScrapInfoPair(string scrapPath, Scrap scrap)
		{
			ScrapPath = scrapPath.RemoveNonAlphanumeric(4);
			Scrap = scrap;
		}
	}
	[Serializable]
	public struct AudioClipInfoPair
	{
		public string AudioClipName;

		[HideInInspector]
		public string AudioClipPath;

		[SerializeField]
		public AudioClip AudioClip;

		public AudioClipInfoPair(string audioClipName, string audioClipPath)
		{
			AudioClipName = audioClipName.RemoveNonAlphanumeric(1);
			AudioClipPath = audioClipPath.RemoveNonAlphanumeric(4);
			AudioClip = null;
		}
	}
	[Serializable]
	public struct PlanetPrefabInfoPair
	{
		public string PlanetPrefabName;

		[HideInInspector]
		public string PlanetPrefabPath;

		[SerializeField]
		public GameObject PlanetPrefab;

		public PlanetPrefabInfoPair(string planetPrefabName, string planetPrefabPath)
		{
			PlanetPrefabName = planetPrefabName.RemoveNonAlphanumeric(1);
			PlanetPrefabPath = planetPrefabPath.RemoveNonAlphanumeric(4);
			PlanetPrefab = null;
		}
	}
	[Serializable]
	public struct PrefabInfoPair
	{
		public string PrefabName;

		[HideInInspector]
		public string PrefabPath;

		[SerializeField]
		public GameObject Prefab;

		public PrefabInfoPair(string prefabName, string prefabPath)
		{
			PrefabName = prefabName.RemoveNonAlphanumeric(1);
			PrefabPath = prefabPath.RemoveNonAlphanumeric(4);
			Prefab = null;
		}
	}
	[Serializable]
	public struct RandomWeatherPair
	{
		public LevelWeatherType Weather;

		[Tooltip("Thunder Frequency, Flooding speed or minimum initial enemies in eclipses")]
		public int WeatherVariable1;

		[Tooltip("Flooding offset when Weather is Flooded")]
		public int WeatherVariable2;

		public RandomWeatherPair(LevelWeatherType weather, int weatherVariable1, int weatherVariable2)
		{
			Weather = weather;
			WeatherVariable1 = weatherVariable1;
			WeatherVariable2 = weatherVariable2;
		}
	}
	public enum LevelWeatherType
	{
		None = -1,
		DustClouds,
		Rainy,
		Stormy,
		Foggy,
		Flooded,
		Eclipsed
	}
	public class SpawnPrefab
	{
		private static SpawnPrefab _instance;

		public GameObject waterSurface;

		public static SpawnPrefab Instance
		{
			get
			{
				if (_instance == null)
				{
					_instance = new SpawnPrefab();
				}
				return _instance;
			}
		}
	}
	public static class TypeExtensions
	{
		public enum removeType
		{
			Normal,
			Serializable,
			Keyword,
			Path,
			SerializablePath
		}

		public static readonly Dictionary<removeType, string> regexes = new Dictionary<removeType, string>
		{
			{
				removeType.Normal,
				"[^a-zA-Z0-9 ,.!?_-]"
			},
			{
				removeType.Serializable,
				"[^a-zA-Z0-9 .!_-]"
			},
			{
				removeType.Keyword,
				"[^a-zA-Z0-9._-]"
			},
			{
				removeType.Path,
				"[^a-zA-Z0-9 ,.!_/-]"
			},
			{
				removeType.SerializablePath,
				"[^a-zA-Z0-9 .!_/-]"
			}
		};

		public static string RemoveNonAlphanumeric(this string input)
		{
			if (input != null)
			{
				return Regex.Replace(input, regexes[removeType.Normal], string.Empty);
			}
			return string.Empty;
		}

		public static string[] RemoveNonAlphanumeric(this string[] input)
		{
			if (input != null)
			{
				for (int i = 0; i < input.Length; i++)
				{
					input[i] = Regex.Replace(input[i], regexes[removeType.Normal], string.Empty);
				}
				return input;
			}
			return new string[0];
		}

		public static string RemoveNonAlphanumeric(this string input, removeType removeType = removeType.Normal)
		{
			if (input != null)
			{
				return Regex.Replace(input, regexes[removeType], string.Empty);
			}
			return string.Empty;
		}

		public static string[] RemoveNonAlphanumeric(this string[] input, removeType removeType = removeType.Normal)
		{
			if (input != null)
			{
				for (int i = 0; i < input.Length; i++)
				{
					input[i] = Regex.Replace(input[i], regexes[removeType], string.Empty);
				}
				return input;
			}
			return new string[0];
		}

		public static string RemoveNonAlphanumeric(this string input, int removeType = 0)
		{
			if (input != null)
			{
				return Regex.Replace(input, regexes[(removeType)removeType], string.Empty);
			}
			return string.Empty;
		}

		public static string[] RemoveNonAlphanumeric(this string[] input, int removeType = 0)
		{
			if (input != null)
			{
				for (int i = 0; i < input.Length; i++)
				{
					input[i] = Regex.Replace(input[i], regexes[(removeType)removeType], string.Empty);
				}
				return input;
			}
			return new string[0];
		}
	}
}
namespace LethalSDK.Editor
{
	internal class CopyrightsWindow : EditorWindow
	{
		private Vector2 scrollPosition;

		private readonly Dictionary<string, string> assetAuthorList = new Dictionary<string, string>
		{
			{ "Drop Ship assets, Sun cycle animations, ScrapItem sprite, ScavengerSuit Textures/Arms Mesh and MonitorWall mesh", "Zeekerss" },
			{ "SDK Scripts, Sun Texture, CrossButton Sprite (Inspired of vanilla), OldSeaPort planet prefab texture", "HolographicWings" },
			{ "Old Sea Port asset package", "VIVID Arts" },
			{ "Survival Game Tools asset package", "cookiepopworks.com" }
		};

		[MenuItem("LethalSDK/Copyrights", false, 999)]
		public static void ShowWindow()
		{
			EditorWindow.GetWindow<CopyrightsWindow>("Copyrights");
		}

		private void OnGUI()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.Label("List of Copyrights", EditorStyles.boldLabel, Array.Empty<GUILayoutOption>());
			scrollPosition = GUILayout.BeginScrollView(scrollPosition, Array.Empty<GUILayoutOption>());
			EditorGUILayout.Space(5f);
			foreach (KeyValuePair<string, string> assetAuthor in assetAuthorList)
			{
				GUILayout.Label("Asset: " + assetAuthor.Key + " - By: " + assetAuthor.Value, EditorStyles.wordWrappedLabel, Array.Empty<GUILayoutOption>());
				EditorGUILayout.Space(2f);
			}
			EditorGUILayout.Space(5f);
			GUILayout.Label("This SDK do not embed any Vanilla script.", Array.Empty<GUILayoutOption>());
			GUILayout.EndScrollView();
		}
	}
	public class EditorChecker : Editor
	{
		public override void OnInspectorGUI()
		{
			((Editor)this).DrawDefaultInspector();
		}
	}
	[CustomEditor(typeof(ModManifest))]
	public class ModManifestEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			ModManifest modManifest = (ModManifest)(object)((Editor)this).target;
			if (modManifest.serializedVersion == "0.0.0.0")
			{
				EditorGUILayout.HelpBox("Please define a version to your mod and don't forget to increment it at each update.", (MessageType)2);
			}
			if (modManifest.modName == null || modManifest.modName.Length == 0)
			{
				EditorGUILayout.HelpBox("Your mod need a name.", (MessageType)3);
			}
			IEnumerable<string> enumerable = from e in modManifest.scraps.Where((Scrap e) => (Object)(object)e != (Object)null).ToList()
				group e by e.itemName into g
				where g.Count() > 1
				select g.Key;
			if (enumerable.Any())
			{
				string text = string.Empty;
				foreach (string item in enumerable)
				{
					text = text + item + ",";
				}
				text = text.Remove(text.Length - 1);
				EditorGUILayout.HelpBox("You are trying to register two times or more the same Scraps. Duplicated Scraps are: " + text, (MessageType)2);
			}
			IEnumerable<string> enumerable2 = from e in modManifest.moons.Where((Moon e) => (Object)(object)e != (Object)null).ToList()
				group e by e.MoonName into g
				where g.Count() > 1
				select g.Key;
			if (enumerable2.Any())
			{
				string text2 = string.Empty;
				foreach (string item2 in enumerable2)
				{
					text2 = text2 + item2 + ",";
				}
				text2 = text2.Remove(text2.Length - 1);
				EditorGUILayout.HelpBox("You are trying to register two times or more the same Moons. Duplicated Moons are: " + text2, (MessageType)2);
			}
			string text3 = string.Empty;
			Scrap[] scraps = modManifest.scraps;
			foreach (Scrap scrap in scraps)
			{
				if ((Object)(object)scrap != (Object)null && AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)scrap)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest)))
				{
					text3 = text3 + ((Object)scrap).name + ",";
				}
			}
			Moon[] moons = modManifest.moons;
			foreach (Moon moon in moons)
			{
				if ((Object)(object)moon != (Object)null && AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)moon)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest)))
				{
					text3 = text3 + ((Object)moon).name + ",";
				}
			}
			if (text3 != null && text3.Length > 0)
			{
				text3 = text3.Remove(text3.Length - 1);
				EditorGUILayout.HelpBox("You try to register a Scrap or a Moon from another mod folder. " + text3, (MessageType)2);
			}
			if ((Object)(object)modManifest.assetBank != (Object)null && AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest.assetBank)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest)))
			{
				EditorGUILayout.HelpBox("You try to register an AssetBank from another mod folder.", (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(AssetBank))]
	public class AssetBankEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			AssetBank assetBank = (AssetBank)(object)((Editor)this).target;
			IEnumerable<string> enumerable = from e in (from e in assetBank.AudioClips()
					where e.AudioClipName != null && e.AudioClipName.Length > 0
					select e).ToList()
				group e by e.AudioClipName into g
				where g.Count() > 1
				select g.Key;
			if (enumerable.Any())
			{
				string text = string.Empty;
				foreach (string item in enumerable)
				{
					text = text + item + ",";
				}
				text = text.Remove(text.Length - 1);
				EditorGUILayout.HelpBox("You are trying to register two times or more the same Audio Clip. Duplicated Clips are: " + text, (MessageType)2);
			}
			IEnumerable<string> enumerable2 = from e in (from e in assetBank.PlanetPrefabs()
					where e.PlanetPrefabName != null && e.PlanetPrefabName.Length > 0
					select e).ToList()
				group e by e.PlanetPrefabName into g
				where g.Count() > 1
				select g.Key;
			if (enumerable2.Any())
			{
				string text2 = string.Empty;
				foreach (string item2 in enumerable2)
				{
					text2 = text2 + item2 + ",";
				}
				text2 = text2.Remove(text2.Length - 1);
				EditorGUILayout.HelpBox("You are trying to register two times or more the same Planet Prefabs. Duplicated Planet Prefabs are: " + text2, (MessageType)2);
			}
			string text3 = string.Empty;
			AudioClipInfoPair[] array = assetBank.AudioClips();
			for (int i = 0; i < array.Length; i++)
			{
				AudioClipInfoPair audioClipInfoPair = array[i];
				if (audioClipInfoPair.AudioClipName != null && audioClipInfoPair.AudioClipName.Length > 0 && AssetModificationProcessor.ExtractBundleNameFromPath(audioClipInfoPair.AudioClipPath) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)assetBank)))
				{
					text3 = text3 + audioClipInfoPair.AudioClipName + ",";
				}
			}
			PlanetPrefabInfoPair[] array2 = assetBank.PlanetPrefabs();
			for (int j = 0; j < array2.Length; j++)
			{
				PlanetPrefabInfoPair planetPrefabInfoPair = array2[j];
				if (planetPrefabInfoPair.PlanetPrefabName != null && planetPrefabInfoPair.PlanetPrefabName.Length > 0 && AssetModificationProcessor.ExtractBundleNameFromPath(planetPrefabInfoPair.PlanetPrefabPath) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)assetBank)))
				{
					text3 = text3 + planetPrefabInfoPair.PlanetPrefabName + ",";
				}
			}
			if (text3 != null && text3.Length > 0)
			{
				text3 = text3.Remove(text3.Length - 1);
				EditorGUILayout.HelpBox("You try to register an Audio Clip or a Planet Prefab from another mod folder. " + text3, (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_DungeonGenerator))]
	public class SI_DungeonGeneratorEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_DungeonGenerator sI_DungeonGenerator = (SI_DungeonGenerator)(object)((Editor)this).target;
			string assetPath = AssetDatabase.GetAssetPath((Object)(object)sI_DungeonGenerator.DungeonRoot);
			if (assetPath != null && assetPath.Length > 0)
			{
				EditorGUILayout.HelpBox("Dungeon Root must be in the scene.", (MessageType)3);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_ScanNode))]
	public class SI_ScanNodeEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_ScanNode sI_ScanNode = (SI_ScanNode)(object)((Editor)this).target;
			if (sI_ScanNode.MinRange > sI_ScanNode.MaxRange)
			{
				EditorGUILayout.HelpBox("Min Range must be smaller than Max Ranger.", (MessageType)3);
			}
			if (sI_ScanNode.CreatureScanID < -1)
			{
				EditorGUILayout.HelpBox("Creature Scan ID can't be less than -1.", (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_AnimatedSun))]
	public class SI_AnimatedSunEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_AnimatedSun sI_AnimatedSun = (SI_AnimatedSun)(object)((Editor)this).target;
			if ((Object)(object)sI_AnimatedSun.directLight == (Object)null || (Object)(object)sI_AnimatedSun.indirectLight == (Object)null)
			{
				EditorGUILayout.HelpBox("A direct and an indirect light must be defined.", (MessageType)2);
			}
			if ((Object)(object)((Component)sI_AnimatedSun.directLight).transform.parent != (Object)(object)((Component)sI_AnimatedSun).transform || (Object)(object)((Component)sI_AnimatedSun.indirectLight).transform.parent != (Object)(object)((Component)sI_AnimatedSun).transform)
			{
				EditorGUILayout.HelpBox("Direct and an indirect light must be a child of the AnimatedSun in the hierarchy.", (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_EntranceTeleport))]
	public class SI_EntranceTeleportEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_EntranceTeleport sI_EntranceTeleport = (SI_EntranceTeleport)(object)((Editor)this).target;
			IEnumerable<int> enumerable = from e in Object.FindObjectsOfType<SI_EntranceTeleport>().ToList()
				group e by e.EntranceID into g
				where g.Count() > 1
				select g.Key;
			if (enumerable.Any())
			{
				string text = string.Empty;
				foreach (int item in enumerable)
				{
					text += $"{item},";
				}
				text = text.Remove(text.Length - 1);
				EditorGUILayout.HelpBox("Two entrances or more have same Entrance ID. Duplicated entrances are: " + text, (MessageType)2);
			}
			if ((Object)(object)sI_EntranceTeleport.EntrancePoint == (Object)null)
			{
				EditorGUILayout.HelpBox("An entrance point must be defined.", (MessageType)3);
			}
			if (sI_EntranceTeleport.AudioReverbPreset < 0)
			{
				EditorGUILayout.HelpBox("Audio Reverb Preset can't be negative.", (MessageType)3);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(Scrap))]
	public class ScrapEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			Scrap scrap = (Scrap)(object)((Editor)this).target;
			if ((Object)(object)scrap.prefab == (Object)null)
			{
				EditorGUILayout.HelpBox("You must add a Prefab to your Scrap.", (MessageType)1);
			}
			else
			{
				if ((Object)(object)scrap.prefab.GetComponent<NetworkObject>() == (Object)null)
				{
					EditorGUILayout.HelpBox("The Prefab must have a NetworkObject.", (MessageType)3);
				}
				else
				{
					NetworkObject component = scrap.prefab.GetComponent<NetworkObject>();
					string text = string.Empty;
					if (component.AlwaysReplicateAsRoot)
					{
						text += "\n- AlwaysReplicateAsRoot should be false.";
					}
					if (!component.SynchronizeTransform)
					{
						text += "\n- SynchronizeTransform should be true.";
					}
					if (component.ActiveSceneSynchronization)
					{
						text += "\n- ActiveSceneSynchronization should be false.";
					}
					if (!component.SceneMigrationSynchronization)
					{
						text += "\n- SceneMigrationSynchronization should be true.";
					}
					if (!component.SpawnWithObservers)
					{
						text += "\n- SpawnWithObservers should be true.";
					}
					if (!component.DontDestroyWithOwner)
					{
						text += "\n- DontDestroyWithOwner should be true.";
					}
					if (component.AutoObjectParentSync)
					{
						text += "\n- AutoObjectParentSync should be false.";
					}
					if (text.Length > 0)
					{
						EditorGUILayout.HelpBox("The NetworkObject of the Prefab have incorrect settings: " + text, (MessageType)2);
					}
				}
				if ((Object)(object)scrap.prefab.transform.Find("ScanNode") == (Object)null)
				{
					EditorGUILayout.HelpBox("The Prefab don't have a ScanNode.", (MessageType)2);
				}
				if (AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)scrap.prefab)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)scrap)))
				{
					EditorGUILayout.HelpBox("The Prefab must come from the same mod folder as your Scrap.", (MessageType)2);
				}
			}
			if (scrap.itemName == null || scrap.itemName.Length == 0)
			{
				EditorGUILayout.HelpBox("Your scrap must have a Name.", (MessageType)3);
			}
			if (!scrap.useGlobalSpawnWeight && !scrap.perPlanetSpawnWeight().Any((ScrapSpawnChancePerScene w) => w.SceneName != null && w.SceneName.Length > 0))
			{
				EditorGUILayout.HelpBox("Your scrap use Per Planet Spawn Weight but no planet are defined.", (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(Moon))]
	public class MoonEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			Moon moon = (Moon)(object)((Editor)this).target;
			if (moon.MoonName == null || moon.MoonName.Length == 0)
			{
				EditorGUILayout.HelpBox("Your moon must have a Name.", (MessageType)3);
			}
			if (moon.PlanetName == null || moon.PlanetName.Length == 0)
			{
				EditorGUILayout.HelpBox("Your moon must have a Planet Name.", (MessageType)3);
			}
			if (moon.RouteWord == null || moon.RouteWord.Length < 3)
			{
				EditorGUILayout.HelpBox("Your moon route word must be at least 3 characters long.", (MessageType)3);
			}
			if ((Object)(object)moon.MainPrefab == (Object)null)
			{
				EditorGUILayout.HelpBox("You must add a Main Prefab to your Scrap.", (MessageType)1);
			}
			else if (AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)moon.MainPrefab)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)moon)))
			{
				EditorGUILayout.HelpBox("The Main Prefab must come from the same mod folder as your Moon.", (MessageType)2);
			}
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_DoorLock))]
	public class SI_DoorLockEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_DoorLock sI_DoorLock = (SI_DoorLock)(object)((Editor)this).target;
			EditorGUILayout.HelpBox("DoorLock is not implemented yet.", (MessageType)1);
			base.OnInspectorGUI();
		}
	}
	[CustomEditor(typeof(SI_Ladder))]
	public class SI_LadderEditor : EditorChecker
	{
		public override void OnInspectorGUI()
		{
			SI_Ladder sI_Ladder = (SI_Ladder)(object)((Editor)this).target;
			EditorGUILayout.HelpBox("Ladder is experimental.", (MessageType)1);
			base.OnInspectorGUI();
		}
	}
	internal class OldAssetsRemover
	{
		private static readonly List<string> assetPaths = new List<string>
		{
			"Assets/LethalCompanyAssets", "Assets/Mods/LethalExpansion/Audio", "Assets/Mods/LethalExpansion/AudioMixerController", "Assets/Mods/LethalExpansion/Materials/Default.mat", "Assets/Mods/LethalExpansion/Prefabs/Settings", "Assets/Mods/LethalExpansion/Prefabs/EntranceTeleportA.prefab", "Assets/Mods/LethalExpansion/Prefabs/Prefabs.zip", "Assets/Mods/LethalExpansion/Scenes/ItemPlaceTest", "Assets/Mods/LethalExpansion/Sprites/HandIcon.png", "Assets/Mods/LethalExpansion/Sprites/HandIconPoint.png",
			"Assets/Mods/LethalExpansion/Sprites/HandLadderIcon.png", "Assets/Mods/TemplateMod/Moons/NavMesh-Environment.asset", "Assets/Mods/TemplateMod/Moons/OldSeaPort.asset", "Assets/Mods/TemplateMod/Moons/Sky and Fog Global Volume Profile.asset", "Assets/Mods/TemplateMod/Moons/Sky and Fog Global Volume Profile 1.asset", "Assets/Mods/TemplateMod/AssetBank.asset", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunCompanyLevel.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeB.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeBEclipse.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeBStormy.anim",
			"Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeC.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeCEclipse.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeCStormy.anim", "Assets/Mods/LethalExpansion/Skybox", "Assets/Mods/LethalExpansion/Sprites/XButton.png", "Assets/Mods/LethalExpansion/Textures/sunTexture1.png", "Assets/Mods/OldSeaPort/Materials/Maple_bark_1.mat", "Assets/Mods/OldSeaPort/Materials/maple_leaves.mat", "Assets/Mods/TemplateMod/AssetBank.asset", "Assets/Mods/OldSeaPort/EffectExamples/Shared/Scripts",
			"Assets/Mods/OldSeaPort/scenes", "Assets/Mods/OldSeaPort/prefabs/Plane (12).prefab", "Assets/Mods/LethalExpansion/Meshes/labyrinth.fbx", "Assets/Mods/ChristmasVillage/christmas-assets-free/fbx/Materials"
		};

		[InitializeOnLoadMethod]
		public static void CheckOldAssets()
		{
			foreach (string assetPath in assetPaths)
			{
				if (AssetDatabase.IsValidFolder(assetPath))
				{
					DeleteFolder(assetPath);
				}
				else if ((Object)(object)AssetDatabase.LoadAssetAtPath<GameObject>(assetPath) != (Object)null)
				{
					DeleteAsset(assetPath);
				}
			}
		}

		private static void DeleteFolder(string path)
		{
			if (AssetDatabase.DeleteAsset(path))
			{
				Debug.Log((object)("Deleted folder at: " + path));
			}
			else
			{
				Debug.LogError((object)("Failed to delete folder at: " + path));
			}
		}

		private static void DeleteAsset(string path)
		{
			if (AssetDatabase.DeleteAsset(path))
			{
				Debug.Log((object)("Deleted asset at: " + path));
			}
			else
			{
				Debug.LogError((object)("Failed to delete asset at: " + path));
			}
		}
	}
	public class VersionChecker : Editor
	{
		[InitializeOnLoadMethod]
		public static void CheckVersion()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			UnityWebRequest www = UnityWebRequest.Get("https://raw.githubusercontent.com/HolographicWings/LethalSDK-Unity-Project/main/last.txt");
			UnityWebRequestAsyncOperation operation = www.SendWebRequest();
			CallbackFunction callback = null;
			callback = (CallbackFunction)delegate
			{
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Expected O, but got Unknown
				if (((AsyncOperation)operation).isDone)
				{
					EditorApplication.update = (CallbackFunction)Delegate.Remove((Delegate?)(object)EditorApplication.update, (Delegate?)(object)callback);
					OnRequestComplete(www);
				}
			};
			EditorApplication.update = (CallbackFunction)Delegate.Combine((Delegate?)(object)EditorApplication.update, (Delegate?)(object)callback);
		}

		private static void OnRequestComplete(UnityWebRequest www)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			if ((int)www.result == 2 || (int)www.result == 3)
			{
				Debug.LogError((object)("Error when getting last version number: " + www.error));
			}
			else
			{
				CompareVersions(www.downloadHandler.text);
			}
		}

		private static void CompareVersions(string onlineVersion)
		{
			if (Version.Parse(PlayerSettings.bundleVersion) < Version.Parse(onlineVersion) && EditorUtility.DisplayDialogComplex("Warning", "The SDK is not up to date: " + onlineVersion, "Update", "Ignore", "") == 0)
			{
				Application.OpenURL("https://thunderstore.io/c/lethal-company/p/HolographicWings/LethalSDK/");
			}
		}
	}
	internal class LethalSDKCategory : EditorWindow
	{
		[MenuItem("LethalSDK/Lethal SDK v1.3.0", false, 0)]
		public static void ShowWindow()
		{
		}
	}
	public class Lethal_AssetBundleBuilderWindow : EditorWindow
	{
		private enum compressionOption
		{
			NormalCompression,
			FastCompression,
			Uncompressed
		}

		private static string assetBundleDirectoryKey = "LethalSDK_AssetBundleBuilderWindow_assetBundleDirectory";

		private static string compressionModeKey = "LethalSDK_AssetBundleBuilderWindow_compressionMode";

		private static string _64BitsModeKey = "LethalSDK_AssetBundleBuilderWindow_64BitsMode";

		private string assetBundleDirectory = string.Empty;

		private compressionOption compressionMode = compressionOption.NormalCompression;

		private bool _64BitsMode;

		[MenuItem("LethalSDK/AssetBundle Builder", false, 100)]
		public static void ShowWindow()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			Lethal_AssetBundleBuilderWindow window = EditorWindow.GetWindow<Lethal_AssetBundleBuilderWindow>("AssetBundle Builder");
			((EditorWindow)window).minSize = new Vector2(295f, 133f);
			((EditorWindow)window).maxSize = new Vector2(295f, 133f);
			window.LoadPreferences();
		}

		private void OnGUI()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			GUILayout.Label("Base Settings", EditorStyles.boldLabel, Array.Empty<GUILayoutOption>());
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			EditorGUILayout.LabelField(new GUIContent("Output Path", "The directory where the asset bundles will be saved."), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(84f) });
			assetBundleDirectory = EditorGUILayout.TextField(assetBundleDirectory, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) });
			GUILayout.EndHorizontal();
			EditorGUILayout.Space(5f);
			GUILayout.Label("Options", EditorStyles.boldLabel, Array.Empty<GUILayoutOption>());
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			EditorGUILayout.LabelField(new GUIContent("Compression Mode", "Select the compression option for the asset bundle. Faster the compression is, faster the assets will load and less CPU it will use, but the Bundle will be bigger."), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(145f) });
			compressionMode = (compressionOption)(object)EditorGUILayout.EnumPopup((Enum)compressionMode, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) });
			GUILayout.EndHorizontal();
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			EditorGUILayout.LabelField(new GUIContent("64 Bits Asset Bundle (Not recommended)", "Better performances but incompatible with 32 bits computers."), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(270f) });
			_64BitsMode = EditorGUILayout.Toggle(_64BitsMode, Array.Empty<GUILayoutOption>());
			GUILayout.EndHorizontal();
			EditorGUILayout.Space(5f);
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("Build AssetBundles", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) }))
			{
				BuildAssetBundles();
			}
			if (GUILayout.Button("Reset", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(45f) }))
			{
				ClearPreferences();
			}
			GUILayout.EndHorizontal();
		}

		private void ClearPreferences()
		{
			EditorPrefs.DeleteKey(assetBundleDirectoryKey);
			EditorPrefs.DeleteKey(compressionModeKey);
			EditorPrefs.DeleteKey(_64BitsModeKey);
			LoadPreferences();
		}

		private void BuildAssetBundles()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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)
			//IL_004f: 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)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if (!Directory.Exists(assetBundleDirectory))
			{
				Directory.CreateDirectory(assetBundleDirectory);
			}
			BuildAssetBundleOptions val = (BuildAssetBundleOptions)0;
			val = (BuildAssetBundleOptions)(compressionMode switch
			{
				compressionOption.NormalCompression => 0, 
				compressionOption.FastCompression => 256, 
				compressionOption.Uncompressed => 1, 
				_ => 0, 
			});
			BuildTarget val2 = (BuildTarget)(_64BitsMode ? 19 : 5);
			if (assetBundleDirectory != null || assetBundleDirectory.Length != 0 || assetBundleDirectory != string.Empty)
			{
				AssetBundleManifest val3 = null;
				try
				{
					val3 = BuildPipeline.BuildAssetBundles(assetBundleDirectory, val, val2);
				}
				catch (Exception ex)
				{
					Debug.LogError((object)ex.Message);
				}
				if ((Object)(object)val3 != (Object)null)
				{
					Debug.Log((object)"AssetBundles built successfully.");
				}
				else
				{
					Debug.LogError((object)"Cannot build AssetBundles.");
				}
			}
			else
			{
				Debug.LogError((object)"AssetBundles path cannot be blank.");
			}
		}

		private void OnLostFocus()
		{
			SavePreferences();
		}

		private void OnDisable()
		{
			SavePreferences();
		}

		private void LoadPreferences()
		{
			assetBundleDirectory = EditorPrefs.GetString(assetBundleDirectoryKey, "Assets/AssetBundles");
			compressionMode = (compressionOption)EditorPrefs.GetInt(compressionModeKey, 0);
			_64BitsMode = EditorPrefs.GetBool(_64BitsModeKey, false);
		}

		private void SavePreferences()
		{
			EditorPrefs.SetString(assetBundleDirectoryKey, assetBundleDirectory);
			EditorPrefs.SetInt(compressionModeKey, (int)compressionMode);
			EditorPrefs.SetBool(_64BitsModeKey, _64BitsMode);
		}
	}
}
namespace LethalSDK.Component
{
	[AddComponentMenu("LethalSDK/DamagePlayer")]
	public class SI_DamagePlayer : MonoBehaviour
	{
		public bool kill = false;

		public bool dontSpawnBody = false;

		public SI_CauseOfDeath causeOfDeath = SI_CauseOfDeath.Gravity;

		public int damages = 25;

		public int numberIterations = 1;

		public int iterationCooldown = 1000;

		public int warmupCooldown = 0;

		public UnityEvent postEvent = new UnityEvent();

		public void Trigger(object player)
		{
			if (kill)
			{
				((MonoBehaviour)this).StartCoroutine(Kill(player));
			}
			else
			{
				((MonoBehaviour)this).StartCoroutine(Damage(player));
			}
		}

		public IEnumerator Kill(object player)
		{
			yield return (object)new WaitForSeconds((float)warmupCooldown / 1000f);
			((PlayerControllerB)((player is PlayerControllerB) ? player : null)).KillPlayer(Vector3.zero, !dontSpawnBody, (CauseOfDeath)causeOfDeath, 0);
			postEvent.Invoke();
		}

		public IEnumerator Damage(object player)
		{
			yield return (object)new WaitForSeconds((float)warmupCooldown / 1000f);
			int iteration = 0;
			while (iteration < numberIterations || numberIterations == -1)
			{
				((PlayerControllerB)((player is PlayerControllerB) ? player : null)).DamagePlayer(damages, true, true, (CauseOfDeath)causeOfDeath, 0, false, Vector3.zero);
				postEvent.Invoke();
				iteration++;
				yield return (object)new WaitForSeconds((float)iterationCooldown / 1000f);
			}
		}

		public void StopCounter(object player)
		{
			((MonoBehaviour)this).StopAllCoroutines();
		}
	}
	[AddComponentMenu("LethalSDK/SoundYDistance")]
	public class SI_SoundYDistance : MonoBehaviour
	{
		public AudioSource audioSource;

		public int maxDistance = 50;

		public void Awake()
		{
			if ((Object)(object)audioSource == (Object)null)
			{
				audioSource = ((Component)this).gameObject.GetComponent<AudioSource>();
				if ((Object)(object)audioSource == (Object)null)
				{
					audioSource = ((Component)this).gameObject.AddComponent<AudioSource>();
				}
			}
		}

		public void Update()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)RoundManager.Instance != (Object)null && (Object)(object)StartOfRound.Instance != (Object)null)
			{
				audioSource.volume = 1f - Mathf.Abs(((Component)this).transform.position.y - ((Component)RoundManager.Instance.playersManager.allPlayerScripts[StartOfRound.Instance.ClientPlayerList[((NetworkBehaviour)StartOfRound.Instance).NetworkManager.LocalClientId]].gameplayCamera).transform.position.y) / (float)maxDistance;
			}
		}
	}
	[AddComponentMenu("LethalSDK/AudioOutputInterface")]
	public class SI_AudioOutputInterface : MonoBehaviour
	{
		public AudioSource audioSource;

		public string mixerName = "Diagetic";

		public string mixerGroupName = "Master";

		public void Awake()
		{
			if ((Object)(object)audioSource == (Object)null)
			{
				audioSource = ((Component)this).gameObject.GetComponent<AudioSource>();
				if ((Object)(object)audioSource == (Object)null)
				{
					audioSource = ((Component)this).gameObject.AddComponent<AudioSource>();
				}
			}
			if (mixerName != null && mixerName.Length > 0 && mixerGroupName != null && mixerGroupName.Length > 0)
			{
				audioSource.outputAudioMixerGroup = AssetGatherDialog.audioMixers[mixerName].Item2.First((AudioMixerGroup g) => ((Object)g).name == mixerGroupName);
			}
			Object.Destroy((Object)(object)this);
		}
	}
	[AddComponentMenu("LethalSDK/NetworkPrefabInstancier")]
	public class SI_NetworkPrefabInstancier : MonoBehaviour
	{
		public GameObject prefab;

		[HideInInspector]
		public GameObject instance;

		public InterfaceType interfaceType = InterfaceType.None;

		public void Awake()
		{
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)prefab != (Object)null)
			{
				NetworkObject component = prefab.GetComponent<NetworkObject>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.NetworkManager != (Object)null && component.NetworkManager.IsHost)
				{
					SI_NetworkDataInterfacing component2 = ((Component)this).GetComponent<SI_NetworkDataInterfacing>();
					if ((Object)(object)component2 != (Object)null)
					{
						StringStringPair[] data = component2.getData();
						InterfaceType interfaceType = this.interfaceType;
						InterfaceType interfaceType2 = interfaceType;
						if (interfaceType2 != InterfaceType.Base && interfaceType2 == InterfaceType.Entrance)
						{
							SI_EntranceTeleport componentInChildren = prefab.GetComponentInChildren<SI_EntranceTeleport>();
							if ((Object)(object)componentInChildren != (Object)null)
							{
								if (data.Any((StringStringPair e) => e._string1.ToLower() == "entranceid"))
								{
									int.TryParse(data.First((StringStringPair e) => e._string1.ToLower() == "entranceid")._string2, out componentInChildren.EntranceID);
								}
								if (data.Any((StringStringPair e) => e._string1.ToLower() == "audioreverbpreset"))
								{
									int.TryParse(data.First((StringStringPair e) => e._string1.ToLower() == "audioreverbpreset")._string2, out componentInChildren.AudioReverbPreset);
								}
							}
						}
					}
					instance = Object.Instantiate<GameObject>(prefab, ((Component)this).transform.position, ((Component)this).transform.rotation, ((Component)this).transform.parent);
					instance.GetComponent<NetworkObject>().Spawn(false);
				}
			}
			((Component)this).gameObject.SetActive(false);
		}

		public void OnDestroy()
		{
			if ((Object)(object)instance != (Object)null)
			{
				NetworkObject component = prefab.GetComponent<NetworkObject>();
				if ((Object)(object)component != (Object)null && (Object)(object)component.NetworkManager != (Object)null && component.NetworkManager.IsHost)
				{
					instance.GetComponent<NetworkObject>().Despawn(true);
					Object.Destroy((Object)(object)instance);
				}
			}
		}
	}
	public enum InterfaceType
	{
		None,
		Base,
		Entrance
	}
	[AddComponentMenu("LethalSDK/NetworkDataInterfacing")]
	public class SI_NetworkDataInterfacing : MonoBehaviour
	{
		public StringStringPair[] data;

		[HideInInspector]
		public string serializedData;

		private void OnValidate()
		{
			serializedData = string.Join(";", data.Select((StringStringPair p) => p._string1 + "," + p._string2));
		}

		public virtual StringStringPair[] getData()
		{
			return (from s in serializedData.Split(new char[1] { ';' })
				select s.Split(new char[1] { ',' }) into split
				where split.Length == 2
				select new StringStringPair(split[0], split[1])).ToArray();
		}
	}
	public class ScriptImporter : MonoBehaviour
	{
		public virtual void Awake()
		{
			Object.Destroy((Object)(object)this);
		}
	}
	[AddComponentMenu("LethalSDK/MatchLocalPlayerPosition")]
	public class SI_MatchLocalPlayerPosition : ScriptImporter
	{
		public override void Awake()
		{
			((Component)this).gameObject.AddComponent<MatchLocalPlayerPosition>();
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/AnimatedSun")]
	public class SI_AnimatedSun : ScriptImporter
	{
		public Light indirectLight;

		public Light directLight;

		public override void Awake()
		{
			animatedSun val = ((Component)this).gameObject.AddComponent<animatedSun>();
			val.indirectLight = indirectLight;
			val.directLight = directLight;
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/ScanNode")]
	public class SI_ScanNode : ScriptImporter
	{
		public int MaxRange;

		public int MinRange;

		public bool RequiresLineOfSight;

		public string HeaderText;

		public string SubText;

		public int ScrapValue;

		public int CreatureScanID;

		public NodeType NodeType;

		public override void Awake()
		{
			ScanNodeProperties val = ((Component)this).gameObject.AddComponent<ScanNodeProperties>();
			val.minRange = MinRange;
			val.maxRange = MaxRange;
			val.requiresLineOfSight = RequiresLineOfSight;
			val.headerText = HeaderText;
			val.subText = SubText;
			val.scrapValue = ScrapValue;
			val.creatureScanID = CreatureScanID;
			val.nodeType = (int)NodeType;
			base.Awake();
		}
	}
	public enum NodeType
	{
		Information = 0,
		Danger = 0,
		Ressource = 0
	}
	[AddComponentMenu("LethalSDK/AudioReverbPresets")]
	public class SI_AudioReverbPresets : ScriptImporter
	{
		public GameObject[] presets;

		public override void Awake()
		{
		}

		public void Update()
		{
			int num = 0;
			GameObject[] array = presets;
			foreach (GameObject val in array)
			{
				if ((Object)(object)val.GetComponent<SI_AudioReverbTrigger>() != (Object)null)
				{
					num++;
				}
			}
			if (num != 0)
			{
				return;
			}
			List<AudioReverbTrigger> list = new List<AudioReverbTrigger>();
			GameObject[] array2 = presets;
			foreach (GameObject val2 in array2)
			{
				if ((Object)(object)val2.GetComponent<AudioReverbTrigger>() != (Object)null)
				{
					list.Add(val2.GetComponent<AudioReverbTrigger>());
				}
			}
			AudioReverbPresets val3 = ((Component)this).gameObject.AddComponent<AudioReverbPresets>();
			val3.audioPresets = list.ToArray();
			Object.Destroy((Object)(object)this);
		}
	}
	[AddComponentMenu("LethalSDK/AudioReverbTrigger")]
	public class SI_AudioReverbTrigger : ScriptImporter
	{
		[Header("Reverb Preset")]
		public bool ChangeDryLevel = false;

		[Range(-10000f, 0f)]
		public float DryLevel = 0f;

		public bool ChangeHighFreq = false;

		[Range(-10000f, 0f)]
		public float HighFreq = -270f;

		public bool ChangeLowFreq = false;

		[Range(-10000f, 0f)]
		public float LowFreq = -244f;

		public bool ChangeDecayTime = false;

		[Range(0f, 35f)]
		public float DecayTime = 1.4f;

		public bool ChangeRoom = false;

		[Range(-10000f, 0f)]
		public float Room = -600f;

		[Header("MISC")]
		public bool ElevatorTriggerForProps = false;

		public bool SetInElevatorTrigger = false;

		public bool IsShipRoom = false;

		public bool ToggleLocalFog = false;

		public float FogEnabledAmount = 10f;

		[Header("Weather and effects")]
		public bool SetInsideAtmosphere = false;

		public bool InsideLighting = false;

		public int WeatherEffect = -1;

		public bool EffectEnabled = true;

		public bool DisableAllWeather = false;

		public bool EnableCurrentLevelWeather = true;

		public override void Awake()
		{
			AudioReverbTrigger val = ((Component)this).gameObject.AddComponent<AudioReverbTrigger>();
			ReverbPreset val2 = ScriptableObject.CreateInstance<ReverbPreset>();
			val2.changeDryLevel = ChangeDryLevel;
			val2.dryLevel = DryLevel;
			val2.changeHighFreq = ChangeHighFreq;
			val2.highFreq = HighFreq;
			val2.changeLowFreq = ChangeLowFreq;
			val2.lowFreq = LowFreq;
			val2.changeDecayTime = ChangeDecayTime;
			val2.decayTime = DecayTime;
			val2.changeRoom = ChangeRoom;
			val2.room = Room;
			val.reverbPreset = val2;
			val.usePreset = -1;
			val.audioChanges = (switchToAudio[])(object)new switchToAudio[0];
			val.elevatorTriggerForProps = ElevatorTriggerForProps;
			val.setInElevatorTrigger = SetInElevatorTrigger;
			val.isShipRoom = IsShipRoom;
			val.toggleLocalFog = ToggleLocalFog;
			val.fogEnabledAmount = FogEnabledAmount;
			val.setInsideAtmosphere = SetInsideAtmosphere;
			val.insideLighting = InsideLighting;
			val.weatherEffect = WeatherEffect;
			val.effectEnabled = EffectEnabled;
			val.disableAllWeather = DisableAllWeather;
			val.enableCurrentLevelWeather = EnableCurrentLevelWeather;
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/DungeonGenerator")]
	public class SI_DungeonGenerator : ScriptImporter
	{
		public GameObject DungeonRoot;

		public override void Awake()
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			if (((Component)this).tag != "DungeonGenerator")
			{
				((Component)this).tag = "DungeonGenerator";
			}
			RuntimeDungeon val = ((Component)this).gameObject.AddComponent<RuntimeDungeon>();
			val.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0];
			val.Generator.LengthMultiplier = 0.8f;
			val.Generator.PauseBetweenRooms = 0.2f;
			val.GenerateOnStart = false;
			if ((Object)(object)DungeonRoot != (Object)null)
			{
				_ = DungeonRoot.scene;
				if (false)
				{
					DungeonRoot = new GameObject();
					((Object)DungeonRoot).name = "DungeonRoot";
					DungeonRoot.transform.position = new Vector3(0f, -200f, 0f);
				}
			}
			val.Root = DungeonRoot;
			val.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0];
			UnityNavMeshAdapter val2 = ((Component)this).gameObject.AddComponent<UnityNavMeshAdapter>();
			val2.BakeMode = (RuntimeNavMeshBakeMode)3;
			val2.LayerMask = LayerMask.op_Implicit(35072);
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/EntranceTeleport")]
	public class SI_EntranceTeleport : ScriptImporter
	{
		public int EntranceID = 0;

		public Transform EntrancePoint;

		public int AudioReverbPreset = 2;

		public AudioClip[] DoorAudios = (AudioClip[])(object)new AudioClip[0];

		public override void Awake()
		{
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Expected O, but got Unknown
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Expected O, but got Unknown
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Expected O, but got Unknown
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Expected O, but got Unknown
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Expected O, but got Unknown
			AudioSource val = ((Component)this).gameObject.AddComponent<AudioSource>();
			val.outputAudioMixerGroup = AssetGatherDialog.audioMixers["Diagetic"].Item2.First((AudioMixerGroup g) => ((Object)g).name == "Master");
			val.playOnAwake = false;
			val.spatialBlend = 1f;
			EntranceTeleport entranceTeleport = ((Component)this).gameObject.AddComponent<EntranceTeleport>();
			entranceTeleport.isEntranceToBuilding = true;
			entranceTeleport.entrancePoint = EntrancePoint;
			entranceTeleport.entranceId = EntranceID;
			entranceTeleport.audioReverbPreset = AudioReverbPreset;
			entranceTeleport.entrancePointAudio = val;
			entranceTeleport.doorAudios = DoorAudios;
			InteractTrigger val2 = ((Component)this).gameObject.AddComponent<InteractTrigger>();
			val2.hoverIcon = (AssetGatherDialog.sprites.ContainsKey("HandIcon") ? AssetGatherDialog.sprites["HandIcon"] : AssetGatherDialog.sprites.First().Value);
			val2.hoverTip = "Enter : [LMB]";
			val2.disabledHoverTip = string.Empty;
			val2.holdTip = string.Empty;
			val2.animationString = string.Empty;
			val2.interactable = true;
			val2.oneHandedItemAllowed = true;
			val2.twoHandedItemAllowed = true;
			val2.holdInteraction = true;
			val2.timeToHold = 1.5f;
			val2.timeToHoldSpeedMultiplier = 1f;
			val2.holdingInteractEvent = new InteractEventFloat();
			val2.onInteract = new InteractEvent();
			val2.onInteractEarly = new InteractEvent();
			val2.onStopInteract = new InteractEvent();
			val2.onCancelAnimation = new InteractEvent();
			((UnityEvent<PlayerControllerB>)(object)val2.onInteract).AddListener((UnityAction<PlayerControllerB>)delegate
			{
				entranceTeleport.TeleportPlayer();
			});
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/DoorLock")]
	public class SI_DoorLock : ScriptImporter
	{
		public override void Awake()
		{
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/WaterSurface")]
	public class SI_WaterSurface : ScriptImporter
	{
		private GameObject obj;

		public int soundMaxDistance = 50;

		public override void Awake()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			obj = Object.Instantiate<GameObject>(SpawnPrefab.Instance.waterSurface);
			SceneManager.MoveGameObjectToScene(obj, ((Component)this).gameObject.scene);
			obj.transform.parent = ((Component)this).transform;
			obj.transform.localPosition = Vector3.zero;
			Transform val = obj.transform.Find("Water");
			((Component)val).GetComponent<MeshFilter>().sharedMesh = ((Component)this).GetComponent<MeshFilter>().sharedMesh;
			val.position = ((Component)this).transform.position;
			val.rotation = ((Component)this).transform.rotation;
			val.localScale = ((Component)this).transform.localScale;
			SI_SoundYDistance sI_SoundYDistance = ((Component)val).gameObject.AddComponent<SI_SoundYDistance>();
			sI_SoundYDistance.audioSource = ((Component)obj.transform.Find("WaterAudio")).GetComponent<AudioSource>();
			sI_SoundYDistance.maxDistance = soundMaxDistance;
			obj.SetActive(true);
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/Ladder")]
	public class SI_Ladder : ScriptImporter
	{
		public Transform BottomPosition;

		public Transform TopPosition;

		public Transform HorizontalPosition;

		public Transform PlayerNodePosition;

		public bool UseRaycastToGetTopPosition = false;

		public override void Awake()
		{
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Expected O, but got Unknown
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Expected O, but got Unknown
			InteractTrigger val = ((Component)this).gameObject.AddComponent<InteractTrigger>();
			val.hoverIcon = (AssetGatherDialog.sprites.ContainsKey("HandLadderIcon") ? AssetGatherDialog.sprites["HandLadderIcon"] : AssetGatherDialog.sprites.First().Value);
			val.hoverTip = "Climb : [LMB]";
			val.disabledHoverTip = string.Empty;
			val.holdTip = string.Empty;
			val.animationString = string.Empty;
			val.specialCharacterAnimation = true;
			val.animationWaitTime = 0.5f;
			val.animationString = "SA_PullLever";
			val.isLadder = true;
			val.lockPlayerPosition = true;
			val.playerPositionNode = BottomPosition;
			val.bottomOfLadderPosition = BottomPosition;
			val.bottomOfLadderPosition = BottomPosition;
			val.topOfLadderPosition = TopPosition;
			val.ladderHorizontalPosition = HorizontalPosition;
			val.ladderPlayerPositionNode = PlayerNodePosition;
			val.useRaycastToGetTopPosition = UseRaycastToGetTopPosition;
			val.holdingInteractEvent = new InteractEventFloat();
			val.onCancelAnimation = new InteractEvent();
			val.onInteract = new InteractEvent();
			val.onInteractEarly = new InteractEvent();
			val.onStopInteract = new InteractEvent();
			base.Awake();
		}
	}
	[AddComponentMenu("LethalSDK/ItemDropship")]
	public class SI_ItemDropship : ScriptImporter
	{
		public Animator ShipAnimator;

		public Transform[] ItemSpawnPositions;

		public GameObject OpenTriggerObject;

		public GameObject KillTriggerObject;

		public AudioClip ShipThrusterCloseSound;

		public AudioClip ShipLandSound;

		public AudioClip ShipOpenDoorsSound;

		public override void Awake()
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Expected O, but got Unknown
			ItemDropship ItemDropship = ((Component)this).gameObject.AddComponent<ItemDropship>();
			ItemDropship.shipAnimator = ShipAnimator;
			ItemDropship.itemSpawnPositions = ItemSpawnPositions;
			PlayAudioAnimationEvent val = ((Component)this).gameObject.AddComponent<PlayAudioAnimationEvent>();
			val.audioToPlay = ((Component)this).GetComponent<AudioSource>();
			val.audioClip = ShipLandSound;
			val.audioClip2 = ShipOpenDoorsSound;
			InteractTrigger val2 = OpenTriggerObject.AddComponent<InteractTrigger>();
			val2.hoverIcon = (AssetGatherDialog.sprites.ContainsKey("HandIcon") ? AssetGatherDialog.sprites["HandIcon"] 

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/Lightsaber/ItemTest.dll

Decompiled 7 months ago
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using LethalLib.Modules;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ItemTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ItemTest")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("a6c49ce7-8c47-472e-9a14-0488ecb20293")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")]
[assembly: AssemblyVersion("1.0.0.0")]
public class LightCheck : MonoBehaviour
{
	private MeshRenderer mainRend;

	private Light thisLight;

	private void Start()
	{
		thisLight = ((Component)this).GetComponentInChildren<Light>();
		mainRend = ((Component)this).GetComponentInChildren<MeshRenderer>();
	}

	private void Update()
	{
		((Behaviour)thisLight).enabled = ((Renderer)mainRend).enabled;
	}
}
namespace ModTest;

[BepInPlugin("Mills.ItemTest", "Mod Test", "1.0.0.0")]
public class Plugin : BaseUnityPlugin
{
	private const string modGUID = "Mills.ItemTest";

	private const string modName = "Mod Test";

	private const string modVersion = "1.0.0.0";

	internal ManualLogSource nls;

	private static Plugin instance;

	private void Awake()
	{
		if ((Object)(object)instance == (Object)null)
		{
			instance = this;
			nls = Logger.CreateLogSource("Mills.ItemTest");
			nls.LogInfo((object)"Lightsabers awakened!.");
			string[] array = new string[4] { "greenlightsaber", "redlightsaber", "bluelightsaber", "purplelightsaber" };
			string[] array2 = new string[4] { "GreenLightsaber", "RedLightsaber", "BlueLightsaber", "PurpleLightsaber" };
			for (int i = 0; i < 4; i++)
			{
				string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), array[i]);
				AssetBundle val = AssetBundle.LoadFromFile(text);
				string text2 = "Assets/Items/" + array2[i] + ".asset";
				Item val2 = val.LoadAsset<Item>(text2);
				NetworkPrefabs.RegisterNetworkPrefab(val2.spawnPrefab);
				Utilities.FixMixerGroups(val2.spawnPrefab);
				Items.RegisterScrap(val2, 0, (LevelTypes)1);
				TerminalNode val3 = ScriptableObject.CreateInstance<TerminalNode>();
				val3.clearPreviousText = true;
				val3.displayText = "A f*ckin lightsaber. Unfortunately you haven't been trained to use one so it's no more effective than a mere shovel. It does however glow indefinitely.\n\n";
				Items.RegisterShopItem(val2, (TerminalNode)null, (TerminalNode)null, val3, 40);
				Shovel component = val2.spawnPrefab.GetComponent<Shovel>();
				LightCheck lightCheck = val2.spawnPrefab.AddComponent<LightCheck>();
				nls.LogInfo((object)("Loaded : " + array2[i]));
			}
			nls.LogInfo((object)"Lightsabers loaded!.");
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/MoreEmotes1.3.3.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using MoreEmotes.Patch;
using MoreEmotes.Scripts;
using RuntimeNetcodeRPCValidator;
using TMPro;
using Tools;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Animations.Rigging;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("FuckYouMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FuckYouMod")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5ecc2bf2-af12-4e83-a6f1-cf2eacbf3060")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Tools
{
	public class Ref
	{
		public static object GetInstanceField(Type type, object instance, string fieldName)
		{
			BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
			FieldInfo field = type.GetField(fieldName, bindingAttr);
			return field.GetValue(instance);
		}

		public static object Method(object instance, string methodName, params object[] args)
		{
			MethodInfo method = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
			if (method != null)
			{
				return method.Invoke(instance, args);
			}
			return null;
		}
	}
	public class D : MonoBehaviour
	{
		public static bool Debug;

		public static void L(string msg)
		{
			if (Debug)
			{
				Debug.Log((object)msg);
			}
		}

		public static void W(string msg)
		{
			if (Debug)
			{
				Debug.LogWarning((object)msg);
			}
		}
	}
}
namespace MoreEmotes
{
	[BepInPlugin("MoreEmotes", "MoreEmotes-Sligili", "1.3.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class MoreEmotesInitialization : BaseUnityPlugin
	{
		private Harmony _harmony;

		private NetcodeValidator netcodeValidator;

		private ConfigEntry<string> config_KeyWheel;

		private ConfigEntry<string> config_KeyWheel_c;

		private ConfigEntry<bool> config_InventoryCheck;

		private ConfigEntry<bool> config_UseConfigFile;

		private ConfigEntry<string> config_KeyEmote3;

		private ConfigEntry<string> config_KeyEmote4;

		private ConfigEntry<string> config_KeyEmote5;

		private ConfigEntry<string> config_KeyEmote6;

		private ConfigEntry<string> config_KeyEmote7;

		private ConfigEntry<string> config_KeyEmote8;

		private ConfigEntry<string> config_KeyEmote9;

		private ConfigEntry<string> config_KeyEmote10;

		private void Awake()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"MoreEmotes loaded");
			LoadAssetBundles();
			LoadAssets();
			ConfigFile();
			SearchForIncompatibleMods();
			_harmony = new Harmony("MoreEmotes");
			_harmony.PatchAll(typeof(EmotePatch));
			netcodeValidator = new NetcodeValidator("MoreEmotes");
			netcodeValidator.PatchAll();
			netcodeValidator.BindToPreExistingObjectByBehaviour<SignEmoteText, PlayerControllerB>();
			netcodeValidator.BindToPreExistingObjectByBehaviour<SyncAnimatorToOthers, PlayerControllerB>();
		}

		private void LoadAssetBundles()
		{
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animationsbundle");
			string text2 = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animatorbundle");
			try
			{
				EmotePatch.AnimationsBundle = AssetBundle.LoadFromFile(text);
				EmotePatch.AnimatorBundle = AssetBundle.LoadFromFile(text2);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Failed to load AssetBundles. Make sure \"animatorsbundle\" and \"animationsbundle\" are inside the MoreEmotes folder.\nError: " + ex.Message));
			}
		}

		private void LoadAssets()
		{
			string path = "Assets/MoreEmotes";
			EmotePatch.local = EmotePatch.AnimatorBundle.LoadAsset<RuntimeAnimatorController>(Path.Combine(path, "NEWmetarig.controller"));
			EmotePatch.others = EmotePatch.AnimatorBundle.LoadAsset<RuntimeAnimatorController>(Path.Combine(path, "NEWmetarigOtherPlayers.controller"));
			MoreEmotesEvents.ClapSounds[0] = EmotePatch.AnimationsBundle.LoadAsset<AudioClip>(Path.Combine(path, "SingleClapEmote1.wav"));
			MoreEmotesEvents.ClapSounds[1] = EmotePatch.AnimationsBundle.LoadAsset<AudioClip>(Path.Combine(path, "SingleClapEmote2.wav"));
			EmotePatch.SettingsPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/MoreEmotesPanel.prefab"));
			EmotePatch.ButtonPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/MoreEmotesButton.prefab"));
			EmotePatch.LegsPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/plegs.prefab"));
			EmotePatch.SignPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/Sign.prefab"));
			EmotePatch.SignUIPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/SignTextUI.prefab"));
			EmotePatch.WheelPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesMenu.prefab");
		}

		private void ConfigFile()
		{
			EmotePatch.ConfigFile_Keybinds = new string[32];
			config_KeyWheel = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL", "Key", "v", (ConfigDescription)null);
			EmotePatch.ConfigFile_WheelKeybind = config_KeyWheel.Value;
			config_KeyWheel_c = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL (Controller)", "Key", "leftshoulder", (ConfigDescription)null);
			EmotePatch.ConfigFile_WheelKeybind_controller = config_KeyWheel_c.Value;
			config_InventoryCheck = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "InventoryCheck", true, "Prevents some emotes from performing while holding any item/scrap");
			EmotePatch.ConfigFile_InventoryCheck = config_InventoryCheck.Value;
			config_UseConfigFile = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "ConfigFile", false, "Ignores all in-game saved settings and instead uses the config file");
			EmotePatch.UseConfigFile = config_UseConfigFile.Value;
			config_KeyEmote3 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Middle Finger", "3", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[2] = config_KeyEmote3.Value.Replace(" ", "");
			config_KeyEmote4 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "The Griddy", "6", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[5] = config_KeyEmote4.Value.Replace(" ", "");
			config_KeyEmote5 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Shy", "5", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[4] = config_KeyEmote5.Value.Replace(" ", "");
			config_KeyEmote6 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Clap", "4", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[3] = config_KeyEmote6.Value.Replace(" ", "");
			config_KeyEmote7 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Twerk", "7", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[6] = config_KeyEmote7.Value.Replace(" ", "");
			config_KeyEmote8 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Salute", "8", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[7] = config_KeyEmote8.Value.Replace(" ", "");
			config_KeyEmote9 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Prisyadka", "9", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[8] = config_KeyEmote9.Value.Replace(" ", "");
			config_KeyEmote10 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Sign", "0", (ConfigDescription)null);
			EmotePatch.ConfigFile_Keybinds[9] = config_KeyEmote10.Value.Replace(" ", "");
		}

		private void SearchForIncompatibleMods()
		{
			foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
			{
				BepInPlugin metadata = pluginInfo.Value.Metadata;
				if (metadata.GUID.Equals("com.malco.lethalcompany.moreshipupgrades", StringComparison.OrdinalIgnoreCase) || metadata.GUID.Equals("Stoneman.LethalProgression", StringComparison.OrdinalIgnoreCase))
				{
					EmotePatch.IncompatibleStuff = true;
					break;
				}
			}
		}
	}
	public static class PluginInfo
	{
		public const string GUID = "MoreEmotes";

		public const string NAME = "MoreEmotes-Sligili";

		public const string VER = "1.3.3";
	}
}
namespace MoreEmotes.Patch
{
	public enum Emotes
	{
		D_Sign = 1010,
		D_Clap = 1004,
		D_Middle_Finger = 1003,
		Dance = 1,
		Point = 2,
		Middle_Finger = 3,
		Clap = 4,
		Shy = 5,
		The_Griddy = 6,
		Twerk = 7,
		Salute = 8,
		Prisyadka = 9,
		Sign = 10
	}
	public class EmotePatch
	{
		public static AssetBundle AnimationsBundle;

		public static AssetBundle AnimatorBundle;

		public static RuntimeAnimatorController local;

		public static RuntimeAnimatorController others;

		public static bool UseConfigFile;

		public static string[] ConfigFile_Keybinds;

		public static string ConfigFile_WheelKeybind;

		public static string ConfigFile_WheelKeybind_controller;

		public static bool ConfigFile_InventoryCheck;

		public static string EmoteWheelKeyboard;

		public static string EmoteWheelController;

		public static bool IncompatibleStuff;

		private static int s_currentEmoteID = 0;

		private static float s_defaultPlayerSpeed;

		private static bool[] s_wasPerformingEmote = new bool[32];

		public static bool IsEmoteWheelOpen;

		private static bool s_isPlayerFirstFrame;

		private static bool s_isFirstTimeOnMenu;

		private static bool s_isPlayerSpawning;

		public const int AlternateEmoteIDOffset = 1000;

		private static int[] s_doubleEmotesIDS = new int[2] { 3, 4 };

		public static bool LocalArmsSeparatedFromCamera;

		private static Transform s_freeArmsTarget;

		private static Transform s_lockedArmsTarget;

		private static CallbackContext emptyContext;

		public static GameObject ButtonPrefab;

		public static GameObject SettingsPrefab;

		public static GameObject LegsPrefab;

		public static GameObject SignPrefab;

		public static GameObject SignUIPrefab;

		public static GameObject WheelPrefab;

		private static GameObject s_localPlayerLevelBadge;

		private static GameObject s_localPlayerBetaBadge;

		private static Transform s_legsMesh;

		private static EmoteWheel s_selectionWheel;

		private static SignUI s_customSignInputField;

		private static SyncAnimatorToOthers s_syncAnimator;

		private static int _AlternateEmoteIDOffset => 1000;

		private static void InstantiateSettingsMenu(Transform container)
		{
			RebindButton.ConfigFile_Keybinds = ConfigFile_Keybinds;
			if (!PlayerPrefs.HasKey("InvCheck") || UseConfigFile)
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			ToggleButton.s_InventoryCheck = (UseConfigFile ? ConfigFile_InventoryCheck : (PlayerPrefs.GetInt("InvCheck") == 1));
			SetupUI.UseConfigFile = UseConfigFile;
			SetupUI.InventoryCheck = ToggleButton.s_InventoryCheck;
			GameObject gameObject = ((Component)((Component)container).transform.Find("SettingsPanel")).gameObject;
			Object.Instantiate<GameObject>(ButtonPrefab, gameObject.transform).transform.SetSiblingIndex(7);
			Object.Instantiate<GameObject>(SettingsPrefab, gameObject.transform);
			gameObject.AddComponent<SetupUI>();
		}

		private static void CheckEmoteInput(string keyBind, bool needsEmptyHands, int emoteID, PlayerControllerB player)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			Emotes emotes = (Emotes)emoteID;
			string text = emotes.ToString();
			bool flag;
			if (UseConfigFile)
			{
				flag = ConfigFile_InventoryCheck;
				keyBind = ConfigFile_Keybinds[emoteID - 1];
			}
			else
			{
				flag = PlayerPrefs.GetInt("InvCheck") == 1;
				if (PlayerPrefs.HasKey(text))
				{
					keyBind = PlayerPrefs.GetString(text);
				}
				else
				{
					PlayerPrefs.SetString(text, keyBind);
				}
			}
			if (!keyBind.Equals(string.Empty) && InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keyBind], 0f) && (!player.isHoldingObject || !needsEmptyHands || !flag))
			{
				player.PerformEmote(emptyContext, emoteID);
			}
		}

		private static void CheckWheelInput(string keybind, string controller, PlayerControllerB player)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			bool flag2 = false;
			if (Gamepad.all.Count != 0 && !controller.Equals(string.Empty))
			{
				flag = InputControlExtensions.IsPressed(((InputControl)Gamepad.current)[controller], 0f);
			}
			if (keybind != string.Empty)
			{
				flag2 = InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keybind], 0f) && !((ButtonControl)Keyboard.current[(Key)55]).wasPressedThisFrame;
			}
			bool flag3 = flag || flag2;
			if (flag3 && !IsEmoteWheelOpen && !player.isPlayerDead && !player.inTerminalMenu && !player.quickMenuManager.isMenuOpen && !player.isTypingChat && !s_customSignInputField.IsSignUIOpen)
			{
				IsEmoteWheelOpen = true;
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)2;
				((Component)s_selectionWheel).gameObject.SetActive(IsEmoteWheelOpen);
				player.disableLookInput = true;
			}
			else
			{
				if (!IsEmoteWheelOpen || (flag3 && !player.quickMenuManager.isMenuOpen && !player.isTypingChat && !s_customSignInputField.IsSignUIOpen))
				{
					return;
				}
				int selectedEmoteID = s_selectionWheel.SelectedEmoteID;
				if (!player.quickMenuManager.isMenuOpen && !s_customSignInputField.IsSignUIOpen)
				{
					Cursor.visible = false;
					Cursor.lockState = (CursorLockMode)1;
				}
				if (!player.isPlayerDead && !player.quickMenuManager.isMenuOpen)
				{
					if (selectedEmoteID <= 3 || selectedEmoteID == 6 || !ConfigFile_InventoryCheck)
					{
						player.PerformEmote(emptyContext, selectedEmoteID);
					}
					else if (!player.isHoldingObject)
					{
						player.PerformEmote(emptyContext, selectedEmoteID);
					}
				}
				if (!s_customSignInputField.IsSignUIOpen)
				{
					player.disableLookInput = false;
				}
				IsEmoteWheelOpen = false;
				((Component)s_selectionWheel).gameObject.SetActive(IsEmoteWheelOpen);
			}
		}

		private static void OnFirstLocalPlayerFrameWithNewAnimator(PlayerControllerB player)
		{
			s_isPlayerFirstFrame = false;
			TurnControllerIntoAnOverrideController(player.playerBodyAnimator.runtimeAnimatorController);
			s_syncAnimator = ((Component)player).GetComponent<SyncAnimatorToOthers>();
			s_customSignInputField.Player = player;
			s_freeArmsTarget = Object.Instantiate<Transform>(player.localArmsRotationTarget, player.localArmsRotationTarget.parent.parent);
			s_lockedArmsTarget = player.localArmsRotationTarget;
			Transform val = ((Component)player).transform.Find("ScavengerModel").Find("metarig").Find("spine")
				.Find("spine.001")
				.Find("spine.002")
				.Find("spine.003");
			s_localPlayerLevelBadge = ((Component)val.Find("LevelSticker")).gameObject;
			s_localPlayerBetaBadge = ((Component)val.Find("BetaBadge")).gameObject;
			player.SpawnPlayerAnimation();
		}

		private static void SpawnSign(PlayerControllerB player)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(SignPrefab, ((Component)((Component)((Component)player).transform.Find("ScavengerModel")).transform.Find("metarig")).transform);
			val.transform.SetSiblingIndex(6);
			((Object)val).name = "Sign";
			val.transform.localPosition = new Vector3(0.029f, -0.45f, 1.3217f);
			val.transform.localRotation = Quaternion.Euler(65.556f, 180f, 180f);
		}

		private static void SpawnLegs(PlayerControllerB player)
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(LegsPrefab, ((Component)((Component)player.playerBodyAnimator).transform.parent).transform);
			s_legsMesh = val.transform.Find("Mesh");
			((Component)s_legsMesh).transform.parent = ((Component)player.playerBodyAnimator).transform.parent;
			((Object)s_legsMesh).name = "LEGS";
			GameObject gameObject = ((Component)val.transform.Find("Armature")).gameObject;
			gameObject.transform.parent = ((Component)player.playerBodyAnimator).transform;
			((Object)gameObject).name = "FistPersonLegs";
			gameObject.transform.position = new Vector3(0f, 0.197f, 0f);
			gameObject.transform.localScale = new Vector3(13.99568f, 13.99568f, 13.99568f);
			Object.Destroy((Object)(object)val);
		}

		private static void ResetIKWeights(PlayerControllerB player)
		{
			Transform val = ((Component)player.playerBodyAnimator).transform.Find("Rig 1");
			ChainIKConstraint component = ((Component)val.Find("RightArm")).GetComponent<ChainIKConstraint>();
			ChainIKConstraint component2 = ((Component)val.Find("LeftArm")).GetComponent<ChainIKConstraint>();
			TwoBoneIKConstraint component3 = ((Component)val.Find("RightLeg")).GetComponent<TwoBoneIKConstraint>();
			TwoBoneIKConstraint component4 = ((Component)val.Find("LeftLeg")).GetComponent<TwoBoneIKConstraint>();
			Transform val2 = ((Component)player.playerBodyAnimator).transform.Find("ScavengerModelArmsOnly").Find("metarig").Find("spine.003")
				.Find("RigArms");
			ChainIKConstraint component5 = ((Component)val2.Find("RightArm")).GetComponent<ChainIKConstraint>();
			ChainIKConstraint component6 = ((Component)val2.Find("LeftArm")).GetComponent<ChainIKConstraint>();
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component2).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component).weight = 1f;
			((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)component4).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component5).weight = 1f;
			((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component6).weight = 1f;
		}

		private static void UpdateLegsMaterial(PlayerControllerB player)
		{
			((Renderer)((Component)s_legsMesh).GetComponent<SkinnedMeshRenderer>()).material = ((Renderer)((Component)((Component)((Component)player.playerBodyAnimator).transform.parent).transform.Find("LOD1")).gameObject.GetComponent<SkinnedMeshRenderer>()).material;
		}

		private static void TogglePlayerBadges(bool enabled)
		{
			if ((Object)(object)s_localPlayerBetaBadge != (Object)null)
			{
				((Renderer)s_localPlayerBetaBadge.GetComponent<MeshRenderer>()).enabled = enabled;
			}
			if ((Object)(object)s_localPlayerLevelBadge != (Object)null)
			{
				((Renderer)s_localPlayerLevelBadge.GetComponent<MeshRenderer>()).enabled = enabled;
			}
			else
			{
				Debug.LogError((object)"[MoreEmotes-Sligili] Couldn't find the level badge");
			}
		}

		private static bool CheckIfTooManyEmotesIsPlaying(PlayerControllerB player)
		{
			//IL_000a: 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)
			Animator playerBodyAnimator = player.playerBodyAnimator;
			AnimatorStateInfo currentAnimatorStateInfo = playerBodyAnimator.GetCurrentAnimatorStateInfo(1);
			return ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("Dance1") && player.performingEmote && GetAnimatorEmoteClipName(playerBodyAnimator) != "Dance1";
		}

		private static string GetAnimatorEmoteClipName(Animator animator)
		{
			AnimatorClipInfo[] currentAnimatorClipInfo = animator.GetCurrentAnimatorClipInfo(1);
			return ((Object)((AnimatorClipInfo)(ref currentAnimatorClipInfo[0])).clip).name;
		}

		private static void TurnControllerIntoAnOverrideController(RuntimeAnimatorController controller)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			if (!(controller is AnimatorOverrideController))
			{
				controller = (RuntimeAnimatorController)new AnimatorOverrideController(controller);
			}
		}

		public static void UpdateWheelKeybinds()
		{
			if (UseConfigFile)
			{
				EmoteWheelKeyboard = ConfigFile_WheelKeybind;
				EmoteWheelController = ConfigFile_WheelKeybind_controller;
				return;
			}
			if (!PlayerPrefs.HasKey("Emote_Wheel_c"))
			{
				PlayerPrefs.SetString("Emote_Wheel_c", ConfigFile_WheelKeybind_controller);
			}
			EmoteWheelController = PlayerPrefs.GetString("Emote_Wheel_c");
			if (!PlayerPrefs.HasKey("Emote_Wheel"))
			{
				PlayerPrefs.SetString("Emote_Wheel", ConfigFile_WheelKeybind);
			}
			EmoteWheelKeyboard = PlayerPrefs.GetString("Emote_Wheel");
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			ConfigFile_InventoryCheck = PlayerPrefs.GetInt("InvCheck") == 1;
		}

		[HarmonyPatch(typeof(MenuManager), "Start")]
		[HarmonyPostfix]
		private static void MenuStart(MenuManager __instance)
		{
			D.Debug = true;
			try
			{
				InstantiateSettingsMenu(((Component)((Component)__instance).transform.parent).transform.Find("MenuContainer"));
			}
			catch (Exception ex)
			{
				if (!s_isFirstTimeOnMenu)
				{
					s_isFirstTimeOnMenu = true;
				}
				else
				{
					Debug.LogError((object)(ex.Message + "\n[MoreEmotes-Sligili] Couldn't find MenuContainer"));
				}
			}
		}

		[HarmonyPatch(typeof(RoundManager), "Awake")]
		[HarmonyPostfix]
		private static void AwakePost(RoundManager __instance)
		{
			if (!PlayerPrefs.HasKey("InvCheck"))
			{
				PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0);
			}
			UpdateWheelKeybinds();
			GameObject gameObject = ((Component)((Component)GameObject.Find("Systems").gameObject.transform.Find("UI")).gameObject.transform.Find("Canvas")).gameObject;
			InstantiateSettingsMenu(gameObject.transform.Find("QuickMenu"));
			s_selectionWheel = Object.Instantiate<GameObject>(WheelPrefab, gameObject.transform).AddComponent<EmoteWheel>();
			s_customSignInputField = Object.Instantiate<GameObject>(SignUIPrefab, gameObject.transform).AddComponent<SignUI>();
			EmoteWheel.Keybinds = new string[ConfigFile_Keybinds.Length + 1];
			EmoteWheel.Keybinds = ConfigFile_Keybinds;
			s_isPlayerFirstFrame = true;
		}

		[HarmonyPatch(typeof(HUDManager), "EnableChat_performed")]
		[HarmonyPrefix]
		private static bool OpenChatPrefix()
		{
			if (s_customSignInputField.IsSignUIOpen)
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")]
		[HarmonyPrefix]
		private static bool SubmitChatPrefix()
		{
			if (s_customSignInputField.IsSignUIOpen)
			{
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(PlayerControllerB __instance)
		{
			((Component)((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel")).transform.Find("metarig")).gameObject.AddComponent<MoreEmotesEvents>().Player = __instance;
			s_defaultPlayerSpeed = __instance.movementSpeed;
			((Component)__instance).gameObject.AddComponent<CustomAnimationObjects>();
			SpawnSign(__instance);
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerControllerB __instance)
		{
			if (!__instance.isPlayerControlled || !((NetworkBehaviour)__instance).IsOwner)
			{
				__instance.playerBodyAnimator.runtimeAnimatorController = others;
				TurnControllerIntoAnOverrideController(__instance.playerBodyAnimator.runtimeAnimatorController);
				return;
			}
			if ((Object)(object)__instance.playerBodyAnimator != (Object)(object)local)
			{
				if (s_isPlayerFirstFrame)
				{
					SpawnLegs(__instance);
				}
				__instance.playerBodyAnimator.runtimeAnimatorController = local;
				if (s_isPlayerFirstFrame)
				{
					OnFirstLocalPlayerFrameWithNewAnimator(__instance);
				}
				if (s_isPlayerSpawning)
				{
					__instance.SpawnPlayerAnimation();
					s_isPlayerSpawning = false;
				}
			}
			if (!IncompatibleStuff)
			{
				if ((bool)Ref.Method(__instance, "CheckConditionsForEmote") && __instance.performingEmote)
				{
					switch (s_currentEmoteID)
					{
					case 6:
						__instance.movementSpeed = s_defaultPlayerSpeed / 2f;
						break;
					case 9:
						__instance.movementSpeed = s_defaultPlayerSpeed / 3f;
						break;
					}
				}
				else
				{
					__instance.movementSpeed = s_defaultPlayerSpeed;
				}
			}
			__instance.localArmsRotationTarget = (LocalArmsSeparatedFromCamera ? (__instance.localArmsRotationTarget = s_freeArmsTarget) : (__instance.localArmsRotationTarget = s_lockedArmsTarget));
			CheckWheelInput(EmoteWheelKeyboard, EmoteWheelController, __instance);
			if (!__instance.quickMenuManager.isMenuOpen && !IsEmoteWheelOpen)
			{
				CheckEmoteInput(ConfigFile_Keybinds[2], needsEmptyHands: false, 3, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[3], needsEmptyHands: true, 4, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[4], needsEmptyHands: true, 5, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[5], needsEmptyHands: false, 6, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[6], needsEmptyHands: true, 7, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[7], needsEmptyHands: true, 8, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[8], needsEmptyHands: true, 9, __instance);
				CheckEmoteInput(ConfigFile_Keybinds[9], needsEmptyHands: true, 10, __instance);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPrefix]
		private static void UpdatePrefix(PlayerControllerB __instance)
		{
			if (__instance.performingEmote)
			{
				s_wasPerformingEmote[__instance.playerClientId] = true;
			}
			if (!__instance.performingEmote && s_wasPerformingEmote[__instance.playerClientId])
			{
				s_wasPerformingEmote[__instance.playerClientId] = false;
				ResetIKWeights(__instance);
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "SpawnPlayerAnimation")]
		[HarmonyPrefix]
		private static void OnLocalPlayerSpawn(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				s_isPlayerSpawning = true;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "CheckConditionsForEmote")]
		[HarmonyPrefix]
		private static bool CheckConditionsPrefix(ref bool __result, PlayerControllerB __instance)
		{
			bool flag = (bool)Ref.GetInstanceField(typeof(PlayerControllerB), __instance, "isJumping");
			bool flag2 = (bool)Ref.GetInstanceField(typeof(PlayerControllerB), __instance, "isWalking");
			if (s_currentEmoteID == 6 || s_currentEmoteID == 9)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && __instance.moveInputVector.x == 0f && !__instance.isSprinting && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu && !__instance.isTypingChat;
				return false;
			}
			if (s_currentEmoteID == 10 || s_currentEmoteID == 1010)
			{
				__result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && !flag2 && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu;
				return false;
			}
			return true;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "PerformEmote")]
		[HarmonyPrefix]
		private static bool PerformEmotePrefix(CallbackContext context, int emoteID, PlayerControllerB __instance)
		{
			if ((emoteID < 0 || CheckIfTooManyEmotesIsPlaying(__instance)) && emoteID > 2)
			{
				return false;
			}
			if ((!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || (((NetworkBehaviour)__instance).IsServer && !__instance.isHostPlayerObject)) && !__instance.isTestingPlayer)
			{
				return false;
			}
			if (s_customSignInputField.IsSignUIOpen && emoteID != 1010)
			{
				return false;
			}
			if (emoteID > 0 && emoteID < 3 && !IsEmoteWheelOpen && !((CallbackContext)(ref context)).performed)
			{
				return false;
			}
			int[] array = s_doubleEmotesIDS;
			foreach (int num in array)
			{
				int num2 = num + _AlternateEmoteIDOffset;
				bool flag = (UseConfigFile ? ConfigFile_InventoryCheck : (PlayerPrefs.GetInt("InvCheck") == 1));
				if (emoteID == num && s_currentEmoteID == emoteID && __instance.performingEmote && (!__instance.isHoldingObject || !flag))
				{
					if (emoteID == num)
					{
						emoteID += _AlternateEmoteIDOffset;
					}
					else
					{
						emoteID -= 1000;
					}
				}
			}
			if ((s_currentEmoteID != emoteID && emoteID < 3) || !__instance.performingEmote)
			{
				ResetIKWeights(__instance);
			}
			if (!(bool)Ref.Method(__instance, "CheckConditionsForEmote"))
			{
				return false;
			}
			if (__instance.timeSinceStartingEmote < 0.5f)
			{
				return false;
			}
			s_currentEmoteID = emoteID;
			Action action = delegate
			{
				__instance.timeSinceStartingEmote = 0f;
				__instance.playerBodyAnimator.SetInteger("emoteNumber", emoteID);
				__instance.performingEmote = true;
				__instance.StartPerformingEmoteServerRpc();
				s_syncAnimator.UpdateEmoteIDForOthers(emoteID);
				TogglePlayerBadges(enabled: false);
			};
			switch (emoteID)
			{
			case 9:
				action = (Action)Delegate.Combine(action, (Action)delegate
				{
					UpdateLegsMaterial(__instance);
				});
				break;
			case 10:
				action = (Action)Delegate.Combine(action, (Action)delegate
				{
					((Component)s_customSignInputField).gameObject.SetActive(true);
				});
				break;
			}
			action();
			return false;
		}

		[HarmonyPatch(typeof(PlayerControllerB), "StopPerformingEmoteServerRpc")]
		[HarmonyPostfix]
		private static void StopPerformingEmoteServerPrefix(PlayerControllerB __instance)
		{
			if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				__instance.playerBodyAnimator.SetInteger("emoteNumber", 0);
			}
			TogglePlayerBadges(enabled: true);
			s_syncAnimator.UpdateEmoteIDForOthers(0);
			s_currentEmoteID = 0;
		}
	}
}
namespace MoreEmotes.Scripts
{
	public class MoreEmotesEvents : MonoBehaviour
	{
		private Animator _playerAnimator;

		private AudioSource _playerAudioSource;

		public static AudioClip[] ClapSounds = (AudioClip[])(object)new AudioClip[2];

		public PlayerControllerB Player;

		private void Start()
		{
			_playerAnimator = ((Component)this).GetComponent<Animator>();
			_playerAudioSource = Player.movementAudio;
		}

		public void PlayClapSound()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (Player.performingEmote)
			{
				int currentEmoteID = GetCurrentEmoteID();
				if (!((NetworkBehaviour)Player).IsOwner || !Player.isPlayerControlled || currentEmoteID == 4)
				{
					bool flag = Player.isInHangarShipRoom && Player.playersManager.hangarDoorsClosed;
					RoundManager.Instance.PlayAudibleNoise(((Component)Player).transform.position, 22f, 0.6f, 0, flag, 6);
					_playerAudioSource.pitch = Random.Range(0.59f, 0.79f);
					_playerAudioSource.PlayOneShot(ClapSounds[Random.Range(0, ClapSounds.Length)]);
				}
			}
		}

		public void PlayFootstepSound()
		{
			if (Player.performingEmote)
			{
				int currentEmoteID = GetCurrentEmoteID();
				if ((!((NetworkBehaviour)Player).IsOwner || !Player.isPlayerControlled || currentEmoteID == 6 || currentEmoteID == 8 || currentEmoteID == 9) && ((Vector2)(ref Player.moveInputVector)).sqrMagnitude == 0f)
				{
					Player.PlayFootstepLocal();
					Player.PlayFootstepServer();
				}
			}
		}

		private int GetCurrentEmoteID()
		{
			int num = _playerAnimator.GetInteger("emoteNumber");
			if (num >= 1000)
			{
				num -= 1000;
			}
			return num;
		}
	}
	public class SignEmoteText : NetworkBehaviour
	{
		private PlayerControllerB _playerInstance;

		private TextMeshPro _signModelText;

		public string Text => ((TMP_Text)_signModelText).text;

		private void Start()
		{
			_playerInstance = ((Component)this).GetComponent<PlayerControllerB>();
			_signModelText = ((Component)((Component)_playerInstance).transform.Find("ScavengerModel").Find("metarig").Find("Sign")
				.Find("Text")).GetComponent<TextMeshPro>();
		}

		public void UpdateSignText(string newText)
		{
			if (((NetworkBehaviour)_playerInstance).IsOwner && _playerInstance.isPlayerControlled)
			{
				UpdateSignTextServerRpc(newText);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void UpdateSignTextServerRpc(string newText)
		{
			UpdateSignTextClientRpc(newText);
		}

		[ClientRpc]
		private void UpdateSignTextClientRpc(string newText)
		{
			((TMP_Text)_signModelText).text = newText;
		}
	}
	public class EmoteWheel : MonoBehaviour
	{
		private RectTransform _graphics_selectedBlock;

		private RectTransform _graphics_selectionArrow;

		private Text _graphics_emoteInformation;

		private Text _graphics_pageInformation;

		private int _blocksNumber = 8;

		private int _selectedBlock = 1;

		private float _changePageCooldown = 0.1f;

		private float _selectionArrowLerpSpeed = 30f;

		private float _angle;

		private GameObject[] _pages;

		public float WheelMovementDeadzone = 3.3f;

		public float WheelMovementDeadzoneController = 0.7f;

		public static string[] Keybinds;

		private Vector2 _wheelCenter;

		private Vector2 _lastMouseCoords;

		public int SelectedPageNumber { get; private set; }

		public int SelectedEmoteID { get; private set; }

		public bool IsUsingController { get; private set; }

		private void Awake()
		{
			GetVanillaKeybinds();
			FindGraphics();
			FindPages(((Component)this).gameObject.transform.Find("FunctionalContent"));
			UpdatePageInfo();
		}

		private void OnEnable()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			_wheelCenter = new Vector2((float)(Screen.width / 2), (float)(Screen.height / 2));
			Mouse.current.WarpCursorPosition(_wheelCenter);
		}

		private void GetVanillaKeybinds()
		{
			PlayerInput component = GameObject.Find("PlayerSettingsObject").GetComponent<PlayerInput>();
			if ((Object)(object)component == (Object)null)
			{
				Debug.LogError((object)" MoreEmotes: PlayerSettingsObject is null");
				return;
			}
			Keybinds[0] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote1", false), 0, (DisplayStringOptions)0);
			Keybinds[1] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote2", false), 0, (DisplayStringOptions)0);
		}

		private void FindGraphics()
		{
			_graphics_selectionArrow = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("SelectionArrow")).gameObject.GetComponent<RectTransform>();
			_graphics_selectedBlock = ((Component)((Component)this).gameObject.transform.Find("SelectedEmote")).gameObject.GetComponent<RectTransform>();
			_graphics_emoteInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("EmoteInfo")).GetComponent<Text>();
			_graphics_pageInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("PageNumber")).GetComponent<Text>();
		}

		private void FindPages(Transform contentParent)
		{
			_pages = (GameObject[])(object)new GameObject[((Component)contentParent).transform.childCount];
			_graphics_pageInformation.text = "< Page " + (SelectedPageNumber + 1) + "/" + _pages.Length + " >";
			for (int i = 0; i < ((Component)contentParent).transform.childCount; i++)
			{
				_pages[i] = ((Component)((Component)contentParent).transform.GetChild(i)).gameObject;
			}
		}

		private void Update()
		{
			ControllerInput();
			if (!IsUsingController)
			{
				MouseInput();
			}
			Cursor.visible = !IsUsingController;
			UpdateSelectionArrow();
			PageSelection();
			SelectedEmoteID = _selectedBlock + Mathf.RoundToInt((float)(_blocksNumber / 4)) + _blocksNumber * SelectedPageNumber;
			UpdateEmoteInfo();
		}

		private unsafe void ControllerInput()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (Gamepad.all.Count == 0)
			{
				IsUsingController = false;
				return;
			}
			float num = ((InputControl<float>)(object)((Vector2Control)Gamepad.current.rightStick).x).ReadUnprocessedValue();
			float num2 = ((InputControl<float>)(object)((Vector2Control)Gamepad.current.rightStick).y).ReadUnprocessedValue();
			if (Mathf.Abs(num) < WheelMovementDeadzoneController && Mathf.Abs(num2) < WheelMovementDeadzoneController)
			{
				if (System.Runtime.CompilerServices.Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).value) != _lastMouseCoords)
				{
					IsUsingController = false;
				}
			}
			else
			{
				IsUsingController = true;
				_lastMouseCoords = System.Runtime.CompilerServices.Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).value);
				WheelSelection(Vector2.zero, num, num2);
			}
		}

		private void MouseInput()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (!(Vector2.Distance(_wheelCenter, ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue()) < WheelMovementDeadzone))
			{
				WheelSelection(_wheelCenter, ((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue(), ((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue());
			}
		}

		private void WheelSelection(Vector2 origin, float xAxisValue, float yAxisValue)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			bool flag = xAxisValue > origin.x;
			bool flag2 = yAxisValue > origin.y;
			int num = ((!flag) ? (flag2 ? 2 : 3) : (flag2 ? 1 : 4));
			float num2 = (yAxisValue - origin.y) / (xAxisValue - origin.x);
			float num3 = 180 * (num - ((num <= 2) ? 1 : 2));
			_angle = Mathf.Atan(num2) * (180f / (float)Math.PI) + num3;
			if (_angle == 90f)
			{
				_angle = 270f;
			}
			else if (_angle == 270f)
			{
				_angle = 90f;
			}
			float num4 = 360 / _blocksNumber;
			_selectedBlock = Mathf.RoundToInt((_angle - num4 * 1.5f) / num4);
			((Transform)_graphics_selectedBlock).localRotation = Quaternion.Euler(((Component)this).transform.rotation.z, ((Component)this).transform.rotation.y, num4 * (float)_selectedBlock);
		}

		private void PageSelection()
		{
			UpdatePageInfo();
			if (_changePageCooldown > 0f)
			{
				_changePageCooldown -= Time.deltaTime;
				return;
			}
			int num;
			if (IsUsingController)
			{
				if (!Gamepad.current.dpad.left.isPressed && !Gamepad.current.dpad.right.isPressed)
				{
					return;
				}
				num = (Gamepad.current.dpad.left.isPressed ? 1 : (-1));
			}
			else
			{
				if (((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() == 0f)
				{
					return;
				}
				num = ((((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() > 0f) ? 1 : (-1));
			}
			GameObject[] pages = _pages;
			foreach (GameObject val in pages)
			{
				val.SetActive(false);
			}
			SelectedPageNumber = (SelectedPageNumber + num + _pages.Length) % _pages.Length;
			_pages[SelectedPageNumber].SetActive(true);
			_changePageCooldown = ((!IsUsingController) ? 0.1f : 0.3f);
		}

		private void UpdatePageInfo()
		{
			_graphics_pageInformation.text = $"<color=#fe6b02><</color> Page {SelectedPageNumber + 1}/{_pages.Length} <color=#fe6b02>></color>";
		}

		private void UpdateEmoteInfo()
		{
			string text = ((SelectedEmoteID > Keybinds.Length) ? "" : Keybinds[SelectedEmoteID - 1]);
			int num = 0;
			foreach (Emotes value in Enum.GetValues(typeof(Emotes)))
			{
				if (value >= Emotes.Dance && value < (Emotes)64)
				{
					num++;
				}
			}
			string text2 = ((SelectedEmoteID > num) ? "EMPTY" : ((Emotes)SelectedEmoteID).ToString().Replace("_", " "));
			if (SelectedEmoteID > 2 && SelectedEmoteID <= Keybinds.Length)
			{
				if (!PlayerPrefs.HasKey(text2.Replace(" ", "_")))
				{
					PlayerPrefs.SetString(text2.Replace(" ", "_"), (SelectedEmoteID > Keybinds.Length) ? "" : Keybinds[SelectedEmoteID - 1]);
				}
				else
				{
					text = PlayerPrefs.GetString(text2.Replace(" ", "_"));
				}
			}
			text = "<size=120>[" + text + "]</size>";
			_graphics_emoteInformation.text = text2 + "\n" + text.ToUpper();
		}

		private void UpdateSelectionArrow()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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)
			float num = 360 / _blocksNumber;
			Quaternion val = Quaternion.Euler(0f, 0f, _angle - num * 2f);
			((Transform)_graphics_selectionArrow).localRotation = Quaternion.Lerp(((Transform)_graphics_selectionArrow).localRotation, val, Time.deltaTime * _selectionArrowLerpSpeed);
		}
	}
	public class RebindButton : MonoBehaviour
	{
		public static string[] ConfigFile_Keybinds;

		private string _defaultKey;

		private string _playerPrefsString;

		private Transform _waitingForInput;

		private Text _keyInfo;

		public bool IsControllerButton { get; private set; } = false;


		private void Start()
		{
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			string text = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text;
			IsControllerButton = GetControllerFlag();
			_playerPrefsString = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text.Replace(" ", "_") + (IsControllerButton ? "_c" : "");
			_defaultKey = GetDefaultKey(text);
			FindComponents();
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(GetKey));
			if (!PlayerPrefs.HasKey(_playerPrefsString))
			{
				PlayerPrefs.SetString(_playerPrefsString, _defaultKey);
			}
			SetKeybind(PlayerPrefs.GetString(_playerPrefsString));
		}

		private string GetDefaultKey(string emoteName)
		{
			if (Enum.TryParse<Emotes>(emoteName.Replace(" ", "_"), out var result))
			{
				return ConfigFile_Keybinds[(int)(result - 1)];
			}
			return IsControllerButton ? "leftshoulder" : "V";
		}

		private bool GetControllerFlag()
		{
			Transform val = ((Component)this).gameObject.transform.Find("Description").Find("Subtext");
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			Text val2 = default(Text);
			if (((Component)val).TryGetComponent<Text>(ref val2))
			{
				return val2.text.Equals("(Controller)", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		private void FindComponents()
		{
			((Component)((Component)((Component)this).transform.parent).transform.Find("Delete")).gameObject.AddComponent<DeleteButton>();
			_keyInfo = ((Component)((Component)this).transform.Find("InputText")).GetComponent<Text>();
			_waitingForInput = ((Component)this).transform.Find("wait");
		}

		public void SetKeybind(string key)
		{
			List<string> list = new List<string> { "up", "down", "left", "right" };
			if (list.Contains(key.ToLower()) && key.Length < 5)
			{
				key = "dpad/" + key;
			}
			PlayerPrefs.SetString(_playerPrefsString, key);
			_keyInfo.text = key.ToUpper();
			((MonoBehaviour)this).StopAllCoroutines();
			((Component)_waitingForInput).gameObject.SetActive(false);
		}

		private void GetKey()
		{
			((Component)_waitingForInput).gameObject.SetActive(true);
			((MonoBehaviour)this).StartCoroutine(WaitForKey(delegate(string key)
			{
				SetKeybind(key);
			}));
		}

		private IEnumerator WaitForKey(Action<string> callback)
		{
			while (!((ButtonControl)Keyboard.current.anyKey).wasPressedThisFrame || (!((InputDevice)Gamepad.current).wasUpdatedThisFrame && !InputControlExtensions.IsActuated((InputControl)(object)Gamepad.current.leftStick, 0f) && !InputControlExtensions.IsActuated((InputControl)(object)Gamepad.current.rightStick, 0f)))
			{
				yield return (object)new WaitForEndOfFrame();
				Observable.CallOnce<InputControl>(InputSystem.onAnyButtonPress, (Action<InputControl>)delegate(InputControl ctrl)
				{
					callback(((ctrl.device == Gamepad.current && IsControllerButton) || (ctrl.device == Keyboard.current && !IsControllerButton)) ? ctrl.name : _defaultKey);
				});
			}
		}
	}
	public class DeleteButton : MonoBehaviour
	{
		private void Start()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			RebindButton _rebindButton = ((Component)((Component)((Component)this).transform.parent).transform.Find("Button")).GetComponent<RebindButton>();
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				_rebindButton.SetKeybind(string.Empty);
			});
		}
	}
	public class ToggleButton : MonoBehaviour
	{
		private Toggle _toggle;

		public static bool s_InventoryCheck;

		public string PlayerPrefsString;

		private void Start()
		{
			_toggle = ((Component)this).GetComponent<Toggle>();
			_toggle.isOn = s_InventoryCheck;
			((UnityEvent<bool>)(object)_toggle.onValueChanged).AddListener((UnityAction<bool>)SetNewValue);
			if (!PlayerPrefs.HasKey(PlayerPrefsString))
			{
				SetNewValue(s_InventoryCheck);
			}
		}

		public void SetNewValue(bool arg)
		{
			PlayerPrefs.SetInt(PlayerPrefsString, arg ? 1 : 0);
		}
	}
	public class EnableDisableButton : MonoBehaviour
	{
		public GameObject[] ToAlternateUI = (GameObject[])(object)new GameObject[1];

		private void Start()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener((UnityAction)delegate
			{
				GameObject[] toAlternateUI = ToAlternateUI;
				foreach (GameObject val in toAlternateUI)
				{
					val.SetActive((!val.activeInHierarchy) ? true : false);
				}
			});
			if (((Object)((Component)this).gameObject).name.Equals("BackButton", StringComparison.OrdinalIgnoreCase))
			{
				ToAlternateUI[0] = ((Component)((Component)this).transform.parent).gameObject;
			}
			if (((Object)((Component)this).gameObject).name.Equals("MoreEmotesButton(Clone)", StringComparison.OrdinalIgnoreCase))
			{
				ToAlternateUI[0] = ((Component)((Component)((Component)this).transform.parent).gameObject.transform.Find("MoreEmotesPanel(Clone)")).gameObject;
			}
		}
	}
	public class SetupUI : MonoBehaviour
	{
		public static bool UseConfigFile;

		public static bool InventoryCheck;

		private void Awake()
		{
			Transform settingsUIPanel = ((Component)this).transform.Find("MoreEmotesPanel(Clone)");
			((Component)settingsUIPanel.Find("Version")).GetComponent<Text>().text = "1.3.3 - Sligili";
			SetupOpenSettingsButton();
			SetupBackButton();
			SetupRebindButtons(((Component)settingsUIPanel).transform.Find("KeybindButtons"));
			SetupRebindButtons(((Component)((Component)((Component)settingsUIPanel).transform.Find("Scroll View")).transform.Find("Viewport")).transform.Find("Content"));
			SetupInventoryCheckToggle();
			SetupUseConfigFileToggle();
			void SetupBackButton()
			{
				((Component)((Component)settingsUIPanel).transform.Find("BackButton")).gameObject.AddComponent<EnableDisableButton>();
			}
			void SetupInventoryCheckToggle()
			{
				((Component)((Component)settingsUIPanel).transform.Find("Inv")).gameObject.AddComponent<ToggleButton>().PlayerPrefsString = "InvCheck";
			}
			void SetupOpenSettingsButton()
			{
				((Component)((Component)this).transform.Find("MoreEmotesButton(Clone)")).gameObject.AddComponent<EnableDisableButton>();
			}
			static void SetupRebindButtons(Transform ButtonsParent)
			{
				Transform[] array = (Transform[])(object)new Transform[ButtonsParent.childCount];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = ButtonsParent.GetChild(i);
				}
				Transform[] array2 = array;
				foreach (Transform val in array2)
				{
					((Component)val.Find("Button")).gameObject.AddComponent<RebindButton>();
				}
			}
			void SetupUseConfigFileToggle()
			{
				((Component)((Component)settingsUIPanel).transform.Find("cfg")).gameObject.GetComponent<Toggle>().isOn = UseConfigFile;
			}
		}

		private void Update()
		{
			EmotePatch.UpdateWheelKeybinds();
		}
	}
	public class SignUI : MonoBehaviour
	{
		public PlayerControllerB Player;

		private TMP_InputField _inputField;

		private Text _charactersLeftText;

		private TMP_Text _previewText;

		private Button _submitButton;

		private Button _cancelButton;

		public bool IsSignUIOpen;

		private void Awake()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			FindComponents();
			((UnityEvent)_submitButton.onClick).AddListener(new UnityAction(SubmitText));
			((UnityEvent)_cancelButton.onClick).AddListener((UnityAction)delegate
			{
				Close(cancelAction: true);
			});
			((UnityEvent<string>)(object)_inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string fieldText)
			{
				UpdatePreviewText(fieldText);
				UpdateCharactersLeftText();
			});
		}

		private void OnEnable()
		{
			Player.isTypingChat = true;
			IsSignUIOpen = true;
			((Selectable)_inputField).Select();
			_inputField.text = string.Empty;
			_previewText.text = "PREVIEW";
			Player.disableLookInput = true;
		}

		private void Update()
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			Cursor.visible = true;
			Cursor.lockState = (CursorLockMode)2;
			if (!Player.performingEmote)
			{
				Close(cancelAction: true);
			}
			if (((ButtonControl)Keyboard.current[(Key)2]).wasPressedThisFrame && !((ButtonControl)Keyboard.current[(Key)51]).isPressed)
			{
				SubmitText();
			}
			if (Player.quickMenuManager.isMenuOpen || EmotePatch.IsEmoteWheelOpen || InputControlExtensions.IsPressed(((InputControl)Mouse.current)["rightButton"], 0f))
			{
				Close(cancelAction: true);
			}
			if (Gamepad.all.Count != 0)
			{
				if (Gamepad.current.buttonWest.isPressed || Gamepad.current.startButton.isPressed)
				{
					SubmitText();
				}
				if (Gamepad.current.buttonEast.isPressed || Gamepad.current.selectButton.isPressed)
				{
					Close(cancelAction: true);
				}
			}
		}

		private void FindComponents()
		{
			_inputField = ((Component)((Component)this).transform.Find("InputField")).GetComponent<TMP_InputField>();
			_charactersLeftText = ((Component)((Component)this).transform.Find("CharsLeft")).GetComponent<Text>();
			_submitButton = ((Component)((Component)this).transform.Find("Submit")).GetComponent<Button>();
			_cancelButton = ((Component)((Component)this).transform.Find("Cancel")).GetComponent<Button>();
			_previewText = ((Component)((Component)((Component)this).transform.Find("Sign")).transform.Find("Text")).GetComponent<TMP_Text>();
		}

		private void UpdateCharactersLeftText()
		{
			_charactersLeftText.text = $"CHARACTERS LEFT: <color=yellow>{_inputField.characterLimit - _inputField.text.Length}</color>";
		}

		private void UpdatePreviewText(string text)
		{
			_previewText.text = text;
		}

		private void SubmitText()
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			if (_inputField.text.Equals(string.Empty))
			{
				Close(cancelAction: true);
				return;
			}
			D.L("Submitted " + _inputField.text + " to server");
			((Component)Player).GetComponent<SignEmoteText>().UpdateSignText(_inputField.text);
			float num = 0.5f;
			if (Player.timeSinceStartingEmote > num)
			{
				Player.PerformEmote(default(CallbackContext), 1010);
			}
			Close(cancelAction: false);
		}

		private void Close(bool cancelAction)
		{
			Player.isTypingChat = false;
			IsSignUIOpen = false;
			if (cancelAction)
			{
				Player.performingEmote = false;
				Player.StopPerformingEmoteServerRpc();
			}
			if (!Player.quickMenuManager.isMenuOpen)
			{
				Cursor.visible = false;
				Cursor.lockState = (CursorLockMode)1;
			}
			Player.disableLookInput = false;
			((Component)this).gameObject.SetActive(false);
		}
	}
	public class SyncAnimatorToOthers : NetworkBehaviour
	{
		private PlayerControllerB _player;

		private void Start()
		{
			_player = ((Component)this).GetComponent<PlayerControllerB>();
		}

		public void UpdateEmoteIDForOthers(int newID)
		{
			if (((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				UpdateCurrentEmoteIDServerRpc(newID);
			}
		}

		[ServerRpc(RequireOwnership = false)]
		private void UpdateCurrentEmoteIDServerRpc(int newID)
		{
			UpdateCurrentEmoteIDClientRpc(newID);
		}

		[ClientRpc]
		private void UpdateCurrentEmoteIDClientRpc(int newID)
		{
			if (!((NetworkBehaviour)_player).IsOwner)
			{
				_player.playerBodyAnimator.SetInteger("emoteNumber", newID);
			}
		}
	}
	public class CustomAnimationObjects : MonoBehaviour
	{
		private PlayerControllerB _player;

		private MeshRenderer _sign;

		private GameObject _signText;

		private SkinnedMeshRenderer _legs;

		private void Start()
		{
			_player = ((Component)this).GetComponent<PlayerControllerB>();
		}

		private void Update()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_sign == (Object)null || (Object)(object)_signText == (Object)null)
			{
				FindSign();
				return;
			}
			((Component)_sign).transform.localPosition = ((Component)_sign).transform.parent.Find("spine").localPosition;
			if ((Object)(object)_legs == (Object)null && ((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				FindLegs();
				return;
			}
			DisableEverything();
			if (!_player.performingEmote)
			{
				return;
			}
			switch (_player.playerBodyAnimator.GetInteger("emoteNumber"))
			{
			case 10:
			case 1010:
				((Renderer)_sign).enabled = true;
				if (!_signText.activeSelf)
				{
					_signText.SetActive(true);
				}
				if (((NetworkBehaviour)_player).IsOwner)
				{
					EmotePatch.LocalArmsSeparatedFromCamera = true;
				}
				break;
			case 9:
				if ((Object)(object)_legs != (Object)null)
				{
					((Renderer)_legs).enabled = true;
				}
				if (((NetworkBehaviour)_player).IsOwner)
				{
					EmotePatch.LocalArmsSeparatedFromCamera = true;
				}
				break;
			}
		}

		private void DisableEverything()
		{
			if ((Object)(object)_legs != (Object)null)
			{
				((Renderer)_legs).enabled = false;
			}
			((Renderer)_sign).enabled = false;
			if (_signText.activeSelf)
			{
				_signText.SetActive(false);
			}
			if (((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled)
			{
				EmotePatch.LocalArmsSeparatedFromCamera = false;
			}
		}

		private void FindSign()
		{
			_sign = ((Component)((Component)_player).transform.Find("ScavengerModel").Find("metarig").Find("Sign")).GetComponent<MeshRenderer>();
			_signText = ((Component)((Component)_sign).transform.Find("Text")).gameObject;
		}

		private void FindLegs()
		{
			_legs = ((Component)((Component)_player).transform.Find("ScavengerModel").Find("LEGS")).GetComponent<SkinnedMeshRenderer>();
		}
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/MoreSuits.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("MoreSuits")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A mod that adds more suit options to Lethal Company")]
[assembly: AssemblyFileVersion("1.4.1.0")]
[assembly: AssemblyInformationalVersion("1.4.1")]
[assembly: AssemblyProduct("MoreSuits")]
[assembly: AssemblyTitle("MoreSuits")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.1.0")]
[module: UnverifiableCode]
namespace MoreSuits;

[BepInPlugin("x753.More_Suits", "More Suits", "1.4.1")]
public class MoreSuitsMod : BaseUnityPlugin
{
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPrefix]
		private static void StartPatch(ref StartOfRound __instance)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_067c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0681: Unknown result type (might be due to invalid IL or missing references)
			//IL_0687: Unknown result type (might be due to invalid IL or missing references)
			//IL_068c: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0400: Expected O, but got Unknown
			//IL_0310: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Expected O, but got Unknown
			//IL_0598: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Expected O, but got Unknown
			try
			{
				if (SuitsAdded)
				{
					return;
				}
				int count = __instance.unlockablesList.unlockables.Count;
				UnlockableItem val = new UnlockableItem();
				int num = 0;
				for (int i = 0; i < __instance.unlockablesList.unlockables.Count; i++)
				{
					UnlockableItem val2 = __instance.unlockablesList.unlockables[i];
					if (!((Object)(object)val2.suitMaterial != (Object)null) || !val2.alreadyUnlocked)
					{
						continue;
					}
					val = val2;
					List<string> list = Directory.GetDirectories(Paths.PluginPath, "moresuits", SearchOption.AllDirectories).ToList();
					List<string> list2 = new List<string>();
					List<string> list3 = new List<string>();
					List<string> list4 = DisabledSuits.ToLower().Replace(".png", "").Split(',')
						.ToList();
					List<string> list5 = new List<string>();
					if (!LoadAllSuits)
					{
						foreach (string item2 in list)
						{
							if (File.Exists(Path.Combine(item2, "!less-suits.txt")))
							{
								string[] collection = new string[9] { "glow", "kirby", "knuckles", "luigi", "mario", "minion", "skeleton", "slayer", "smile" };
								list5.AddRange(collection);
								break;
							}
						}
					}
					foreach (string item3 in list)
					{
						if (item3 != "")
						{
							string[] files = Directory.GetFiles(item3, "*.png");
							string[] files2 = Directory.GetFiles(item3, "*.matbundle");
							list2.AddRange(files);
							list3.AddRange(files2);
						}
					}
					list3.Sort();
					list2.Sort();
					try
					{
						foreach (string item4 in list3)
						{
							Object[] array = AssetBundle.LoadFromFile(item4).LoadAllAssets();
							foreach (Object val3 in array)
							{
								if (val3 is Material)
								{
									Material item = (Material)val3;
									customMaterials.Add(item);
								}
							}
						}
					}
					catch (Exception ex)
					{
						Debug.Log((object)("Something went wrong with More Suits! Could not load materials from asset bundle(s). Error: " + ex));
					}
					foreach (string item5 in list2)
					{
						if (list4.Contains(Path.GetFileNameWithoutExtension(item5).ToLower()))
						{
							continue;
						}
						string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
						if (list5.Contains(Path.GetFileNameWithoutExtension(item5).ToLower()) && item5.Contains(directoryName))
						{
							continue;
						}
						UnlockableItem val4;
						Material val5;
						if (Path.GetFileNameWithoutExtension(item5).ToLower() == "default")
						{
							val4 = val;
							val5 = val4.suitMaterial;
						}
						else
						{
							val4 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val));
							val5 = Object.Instantiate<Material>(val4.suitMaterial);
						}
						byte[] array2 = File.ReadAllBytes(item5);
						Texture2D val6 = new Texture2D(2, 2);
						ImageConversion.LoadImage(val6, array2);
						val5.mainTexture = (Texture)(object)val6;
						val4.unlockableName = Path.GetFileNameWithoutExtension(item5);
						try
						{
							string path = Path.Combine(Path.GetDirectoryName(item5), "advanced", val4.unlockableName + ".json");
							if (File.Exists(path))
							{
								string[] array3 = File.ReadAllLines(path);
								for (int j = 0; j < array3.Length; j++)
								{
									string[] array4 = array3[j].Trim().Split(':');
									if (array4.Length != 2)
									{
										continue;
									}
									string text = array4[0].Trim('"', ' ', ',');
									string text2 = array4[1].Trim('"', ' ', ',');
									if (text2.Contains(".png"))
									{
										byte[] array5 = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(item5), "advanced", text2));
										Texture2D val7 = new Texture2D(2, 2);
										ImageConversion.LoadImage(val7, array5);
										val5.SetTexture(text, (Texture)(object)val7);
										continue;
									}
									if (text == "PRICE" && int.TryParse(text2, out var result))
									{
										try
										{
											val4 = AddToRotatingShop(val4, result, __instance.unlockablesList.unlockables.Count);
										}
										catch (Exception ex2)
										{
											Debug.Log((object)("Something went wrong with More Suits! Could not add a suit to the rotating shop. Error: " + ex2));
										}
										continue;
									}
									switch (text2)
									{
									case "KEYWORD":
										val5.EnableKeyword(text);
										continue;
									case "DISABLEKEYWORD":
										val5.DisableKeyword(text);
										continue;
									case "SHADERPASS":
										val5.SetShaderPassEnabled(text, true);
										continue;
									case "DISABLESHADERPASS":
										val5.SetShaderPassEnabled(text, false);
										continue;
									}
									float result2;
									Vector4 vector;
									if (text == "SHADER")
									{
										Shader shader = Shader.Find(text2);
										val5.shader = shader;
									}
									else if (text == "MATERIAL")
									{
										foreach (Material customMaterial in customMaterials)
										{
											if (((Object)customMaterial).name == text2)
											{
												val5 = Object.Instantiate<Material>(customMaterial);
												val5.mainTexture = (Texture)(object)val6;
												break;
											}
										}
									}
									else if (float.TryParse(text2, out result2))
									{
										val5.SetFloat(text, result2);
									}
									else if (TryParseVector4(text2, out vector))
									{
										val5.SetVector(text, vector);
									}
								}
							}
						}
						catch (Exception ex3)
						{
							Debug.Log((object)("Something went wrong with More Suits! Error: " + ex3));
						}
						val4.suitMaterial = val5;
						if (val4.unlockableName.ToLower() != "default")
						{
							if (num == MaxSuits)
							{
								Debug.Log((object)"Attempted to add a suit, but you've already reached the max number of suits! Modify the config if you want more.");
								continue;
							}
							__instance.unlockablesList.unlockables.Add(val4);
							num++;
						}
					}
					SuitsAdded = true;
					break;
				}
				UnlockableItem val8 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val));
				val8.alreadyUnlocked = false;
				val8.hasBeenMoved = false;
				val8.placedPosition = Vector3.zero;
				val8.placedRotation = Vector3.zero;
				val8.unlockableType = 753;
				while (__instance.unlockablesList.unlockables.Count < count + MaxSuits)
				{
					__instance.unlockablesList.unlockables.Add(val8);
				}
			}
			catch (Exception ex4)
			{
				Debug.Log((object)("Something went wrong with More Suits! Error: " + ex4));
			}
		}

		[HarmonyPatch("PositionSuitsOnRack")]
		[HarmonyPrefix]
		private static bool PositionSuitsOnRackPatch(ref StartOfRound __instance)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			List<UnlockableSuit> source = Object.FindObjectsOfType<UnlockableSuit>().ToList();
			source = source.OrderBy((UnlockableSuit suit) => suit.syncedSuitID.Value).ToList();
			int num = 0;
			foreach (UnlockableSuit item in source)
			{
				AutoParentToShip component = ((Component)item).gameObject.GetComponent<AutoParentToShip>();
				component.overrideOffset = true;
				float num2 = 0.18f;
				if (MakeSuitsFitOnRack && source.Count > 13)
				{
					num2 /= (float)Math.Min(source.Count, 20) / 12f;
				}
				component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + __instance.rightmostSuitPosition.forward * num2 * (float)num;
				component.rotationOffset = new Vector3(0f, 90f, 0f);
				num++;
			}
			return false;
		}
	}

	private const string modGUID = "x753.More_Suits";

	private const string modName = "More Suits";

	private const string modVersion = "1.4.1";

	private readonly Harmony harmony = new Harmony("x753.More_Suits");

	private static MoreSuitsMod Instance;

	public static bool SuitsAdded = false;

	public static string DisabledSuits;

	public static bool LoadAllSuits;

	public static bool MakeSuitsFitOnRack;

	public static int MaxSuits;

	public static List<Material> customMaterials = new List<Material>();

	private static TerminalNode cancelPurchase;

	private static TerminalKeyword buyKeyword;

	private void Awake()
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Instance = this;
		}
		DisabledSuits = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Disabled Suit List", "UglySuit751.png,UglySuit752.png,UglySuit753.png", "Comma-separated list of suits that shouldn't be loaded").Value;
		LoadAllSuits = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Ignore !less-suits.txt", false, "If true, ignores the !less-suits.txt file and will attempt to load every suit, except those in the disabled list. This should be true if you're not worried about having too many suits.").Value;
		MakeSuitsFitOnRack = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Make Suits Fit on Rack", true, "If true, squishes the suits together so more can fit on the rack.").Value;
		MaxSuits = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Max Suits", 100, "The maximum number of suits to load. If you have more, some will be ignored.").Value;
		harmony.PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin More Suits is loaded!");
	}

	private static UnlockableItem AddToRotatingShop(UnlockableItem newSuit, int price, int unlockableID)
	{
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0111: Expected O, but got Unknown
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d4: Expected O, but got Unknown
		//IL_0298: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Expected O, but got Unknown
		Terminal val = Object.FindObjectOfType<Terminal>();
		for (int i = 0; i < val.terminalNodes.allKeywords.Length; i++)
		{
			if (((Object)val.terminalNodes.allKeywords[i]).name == "Buy")
			{
				buyKeyword = val.terminalNodes.allKeywords[i];
				break;
			}
		}
		newSuit.alreadyUnlocked = false;
		newSuit.hasBeenMoved = false;
		newSuit.placedPosition = Vector3.zero;
		newSuit.placedRotation = Vector3.zero;
		newSuit.shopSelectionNode = ScriptableObject.CreateInstance<TerminalNode>();
		((Object)newSuit.shopSelectionNode).name = newSuit.unlockableName + "SuitBuy1";
		newSuit.shopSelectionNode.creatureName = newSuit.unlockableName + " suit";
		newSuit.shopSelectionNode.displayText = "You have requested to order " + newSuit.unlockableName + " suits.\nTotal cost of item: [totalCost].\n\nPlease CONFIRM or DENY.\n\n";
		newSuit.shopSelectionNode.clearPreviousText = true;
		newSuit.shopSelectionNode.shipUnlockableID = unlockableID;
		newSuit.shopSelectionNode.itemCost = price;
		newSuit.shopSelectionNode.overrideOptions = true;
		CompatibleNoun val2 = new CompatibleNoun();
		val2.noun = ScriptableObject.CreateInstance<TerminalKeyword>();
		val2.noun.word = "confirm";
		val2.noun.isVerb = true;
		val2.result = ScriptableObject.CreateInstance<TerminalNode>();
		((Object)val2.result).name = newSuit.unlockableName + "SuitBuyConfirm";
		val2.result.creatureName = "";
		val2.result.displayText = "Ordered " + newSuit.unlockableName + " suits! Your new balance is [playerCredits].\n\n";
		val2.result.clearPreviousText = true;
		val2.result.shipUnlockableID = unlockableID;
		val2.result.buyUnlockable = true;
		val2.result.itemCost = price;
		val2.result.terminalEvent = "";
		CompatibleNoun val3 = new CompatibleNoun();
		val3.noun = ScriptableObject.CreateInstance<TerminalKeyword>();
		val3.noun.word = "deny";
		val3.noun.isVerb = true;
		if ((Object)(object)cancelPurchase == (Object)null)
		{
			cancelPurchase = ScriptableObject.CreateInstance<TerminalNode>();
		}
		val3.result = cancelPurchase;
		((Object)val3.result).name = "MoreSuitsCancelPurchase";
		val3.result.displayText = "Cancelled order.\n";
		newSuit.shopSelectionNode.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { val2, val3 };
		TerminalKeyword val4 = ScriptableObject.CreateInstance<TerminalKeyword>();
		((Object)val4).name = newSuit.unlockableName + "Suit";
		val4.word = newSuit.unlockableName.ToLower() + " suit";
		val4.defaultVerb = buyKeyword;
		CompatibleNoun val5 = new CompatibleNoun();
		val5.noun = val4;
		val5.result = newSuit.shopSelectionNode;
		List<CompatibleNoun> list = buyKeyword.compatibleNouns.ToList();
		list.Add(val5);
		buyKeyword.compatibleNouns = list.ToArray();
		List<TerminalKeyword> list2 = val.terminalNodes.allKeywords.ToList();
		list2.Add(val4);
		list2.Add(val2.noun);
		list2.Add(val3.noun);
		val.terminalNodes.allKeywords = list2.ToArray();
		return newSuit;
	}

	public static bool TryParseVector4(string input, out Vector4 vector)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		vector = Vector4.zero;
		string[] array = input.Split(',');
		if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4))
		{
			vector = new Vector4(result, result2, result3, result4);
			return true;
		}
		return false;
	}
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/PlayerDogModel/PlayerDogModel.dll

Decompiled 7 months ago
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using GameNetcodeStuff;
using HarmonyLib;
using LC_API.BundleAPI;
using LC_API.Networking;
using Newtonsoft.Json;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("PlayerDogModel")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A mod to replace Player models with a dog for Lethal Company")]
[assembly: AssemblyFileVersion("1.0.3.0")]
[assembly: AssemblyInformationalVersion("1.0.3")]
[assembly: AssemblyProduct("PlayerDogModel")]
[assembly: AssemblyTitle("PlayerDogModel")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.3.0")]
[module: UnverifiableCode]
namespace PlayerDogModel;

internal static class Networking
{
	public const string ModelSwitchMessageName = "modelswitch";

	public const string ModelInfoMessageName = "modelinfo";

	public static void Initialize()
	{
		Network.RegisterMessage<PlayerModelReplacer.ToggleData>("modelswitch", false, (Action<ulong, PlayerModelReplacer.ToggleData>)HandleModelSwitchMessage);
		Network.RegisterMessage("modelinfo", false, (Action<ulong>)HandleModelInfoMessage);
	}

	private static void HandleModelSwitchMessage(ulong senderId, PlayerModelReplacer.ToggleData toggleData)
	{
		Debug.Log((object)(string.Format("Got {0} network message from {1}: {{ ", "modelswitch", senderId) + string.Format("{0} = {1}, ", "playerClientId", toggleData.playerClientId) + string.Format("{0} = {1}, ", "playAudio", toggleData.playAudio) + string.Format("{0} = {1} ", "isDog", toggleData.isDog) + "}}"));
		PlayerModelReplacer playerModelReplacer = null;
		GameObject[] allPlayerObjects = StartOfRound.Instance.allPlayerObjects;
		for (int i = 0; i < allPlayerObjects.Length; i++)
		{
			PlayerModelReplacer component = allPlayerObjects[i].GetComponent<PlayerModelReplacer>();
			if ((Object)(object)component != (Object)null && component.PlayerClientId == toggleData.playerClientId)
			{
				playerModelReplacer = component;
				break;
			}
		}
		if ((Object)(object)playerModelReplacer == (Object)null)
		{
			Debug.LogWarning((object)string.Format("{0} message from client {1} will be ignored because replacer with this ID is not registered", "modelswitch", senderId));
			return;
		}
		if (!playerModelReplacer.IsValid)
		{
			Debug.LogError((object)"Dog encountered an error when it was initialized and it can't be toggled. Check the log for more info.");
			return;
		}
		Debug.Log((object)$"Received dog={toggleData.isDog} for {playerModelReplacer.PlayerClientId} ({playerModelReplacer.PlayerUsername}).");
		if (toggleData.isDog)
		{
			playerModelReplacer.EnableDogModel(toggleData.playAudio);
		}
		else
		{
			playerModelReplacer.EnableHumanModel(toggleData.playAudio);
		}
	}

	private static void HandleModelInfoMessage(ulong senderId)
	{
		Debug.Log((object)string.Format("Got {0} network message from {1}", "modelinfo", senderId));
		GameObject[] allPlayerObjects = StartOfRound.Instance.allPlayerObjects;
		for (int i = 0; i < allPlayerObjects.Length; i++)
		{
			PlayerModelReplacer component = allPlayerObjects[i].GetComponent<PlayerModelReplacer>();
			if ((Object)(object)component != (Object)null)
			{
				component.BroadcastSelectedModel(playAudio: false);
			}
		}
	}
}
[DefaultExecutionOrder(-1)]
public class PlayerModelReplacer : MonoBehaviour
{
	[JsonObject]
	internal class ToggleData
	{
		[JsonProperty]
		public ulong playerClientId { get; set; }

		[JsonProperty]
		public bool isDog { get; set; }

		[JsonProperty]
		public bool playAudio { get; set; }
	}

	public static PlayerModelReplacer LocalReplacer;

	private static bool loaded;

	private static string exceptionMessage;

	private static Exception exception;

	private PlayerControllerB playerController;

	private GameObject dogGameObject;

	private GameObject[] humanGameObjects;

	private SkinnedMeshRenderer[] dogRenderers;

	private Transform dogTorso;

	private PositionConstraint torsoConstraint;

	private static AudioClip humanClip;

	private static AudioClip dogClip;

	private Vector3 humanCameraPosition;

	private Transform localItemAnchor;

	private Transform serverItemAnchor;

	private static Image healthFill;

	private static Image healthOutline;

	private static Sprite humanFill;

	private static Sprite humanOutline;

	private static Sprite dogFill;

	private static Sprite dogOutline;

	private bool isDogActive;

	public ulong PlayerClientId
	{
		get
		{
			if (!((Object)(object)playerController != (Object)null))
			{
				return ulong.MaxValue;
			}
			return playerController.playerClientId;
		}
	}

	public string PlayerUsername
	{
		get
		{
			if (!((Object)(object)playerController != (Object)null))
			{
				return "";
			}
			return playerController.playerUsername;
		}
	}

	public bool IsValid => (Object)(object)dogGameObject != (Object)null;

	public bool IsDog => isDogActive;

	private void Awake()
	{
		if (!loaded)
		{
			loaded = true;
			LoadImageResources();
			((MonoBehaviour)this).StartCoroutine(LoadAudioResources());
		}
	}

	private void Start()
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		playerController = ((Component)this).GetComponent<PlayerControllerB>();
		if (((NetworkBehaviour)playerController).IsOwner)
		{
			LocalReplacer = this;
		}
		humanCameraPosition = ((Component)playerController.gameplayCamera).transform.localPosition;
		Debug.Log((object)$"Adding PlayerModelReplacer on {playerController.playerUsername} ({((NetworkBehaviour)playerController).IsOwner})");
		SpawnDogModel();
		EnableHumanModel(playAudio: false);
	}

	private void Update()
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		//IL_0189: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: 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_014e: Unknown result type (might be due to invalid IL or missing references)
		if (!string.IsNullOrEmpty(exceptionMessage))
		{
			return;
		}
		Vector3 val = humanCameraPosition;
		if (isDogActive && !playerController.inTerminalMenu && !playerController.inSpecialInteractAnimation)
		{
			if (!playerController.isCrouching)
			{
				((Vector3)(ref val))..ctor(0f, -1.1f, 0.3f);
			}
			else
			{
				((Vector3)(ref val))..ctor(0f, -0.5f, 0.3f);
			}
		}
		((Component)playerController.gameplayCamera).transform.localPosition = Vector3.MoveTowards(((Component)playerController.gameplayCamera).transform.localPosition, val, Time.deltaTime * 2f);
		if (playerController.isCrouching)
		{
			torsoConstraint.weight = Mathf.MoveTowards(torsoConstraint.weight, 0.5f, Time.deltaTime * 3f);
		}
		else
		{
			torsoConstraint.weight = Mathf.MoveTowards(torsoConstraint.weight, 1f, Time.deltaTime * 3f);
		}
		if (playerController.isClimbingLadder)
		{
			dogTorso.localRotation = Quaternion.RotateTowards(dogTorso.localRotation, Quaternion.Euler(90f, 0f, 0f), Time.deltaTime * 360f);
		}
		else
		{
			dogTorso.localRotation = Quaternion.RotateTowards(dogTorso.localRotation, Quaternion.Euler(180f, 0f, 0f), Time.deltaTime * 360f);
		}
	}

	private void LateUpdate()
	{
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)localItemAnchor == (Object)null) && !((Object)(object)serverItemAnchor == (Object)null))
		{
			if (isDogActive)
			{
				playerController.localItemHolder.position = localItemAnchor.position;
				playerController.serverItemHolder.position = serverItemAnchor.position;
			}
			if (((Renderer)dogRenderers[0]).shadowCastingMode != ((Renderer)playerController.thisPlayerModel).shadowCastingMode)
			{
				Debug.Log((object)$"Dog model is on the wrong shadow casting mode. ({((Renderer)dogRenderers[0]).shadowCastingMode} instead of {((Renderer)playerController.thisPlayerModel).shadowCastingMode})");
				((Renderer)dogRenderers[0]).shadowCastingMode = ((Renderer)playerController.thisPlayerModel).shadowCastingMode;
			}
			if (((Component)dogRenderers[0]).gameObject.layer != ((Component)playerController.thisPlayerModel).gameObject.layer)
			{
				Debug.Log((object)("Dog model is on the wrong layer. (" + LayerMask.LayerToName(((Component)dogRenderers[0]).gameObject.layer) + " instead of " + LayerMask.LayerToName(((Component)playerController.thisPlayerModel).gameObject.layer) + ")"));
				((Component)dogRenderers[0]).gameObject.layer = ((Component)playerController.thisPlayerModel).gameObject.layer;
			}
		}
	}

	private void SpawnDogModel()
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_017f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Unknown result type (might be due to invalid IL or missing references)
		//IL_0187: Unknown result type (might be due to invalid IL or missing references)
		//IL_0188: Unknown result type (might be due to invalid IL or missing references)
		//IL_018f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0191: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0311: Unknown result type (might be due to invalid IL or missing references)
		//IL_0329: Unknown result type (might be due to invalid IL or missing references)
		//IL_032e: Unknown result type (might be due to invalid IL or missing references)
		//IL_035f: Unknown result type (might be due to invalid IL or missing references)
		//IL_037a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0385: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0412: Unknown result type (might be due to invalid IL or missing references)
		//IL_041d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0443: Unknown result type (might be due to invalid IL or missing references)
		//IL_045e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0469: Unknown result type (might be due to invalid IL or missing references)
		//IL_048f: Unknown result type (might be due to invalid IL or missing references)
		//IL_04aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			GameObject loadedAsset = BundleLoader.GetLoadedAsset<GameObject>("assets/Dog.fbx");
			dogGameObject = Object.Instantiate<GameObject>(loadedAsset, ((Component)this).transform);
			dogGameObject.transform.position = ((Component)this).transform.position;
			dogGameObject.transform.eulerAngles = ((Component)this).transform.eulerAngles;
			Transform transform = dogGameObject.transform;
			transform.localScale *= 2f;
		}
		catch (Exception ex)
		{
			exceptionMessage = "Failed to spawn dog model.";
			exception = ex;
			Debug.LogError((object)exceptionMessage);
			Debug.LogException(exception);
		}
		dogRenderers = dogGameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
		UpdateMaterial();
		try
		{
			LODGroup val = dogGameObject.AddComponent<LODGroup>();
			val.fadeMode = (LODFadeMode)0;
			LOD val2 = default(LOD);
			val2.screenRelativeTransitionHeight = 0.4564583f;
			val2.renderers = (Renderer[])(object)new Renderer[1] { (Renderer)dogRenderers[0] };
			val2.fadeTransitionWidth = 0f;
			LOD val3 = val2;
			val2 = default(LOD);
			val2.screenRelativeTransitionHeight = 0.1795709f;
			val2.renderers = (Renderer[])(object)new Renderer[1] { (Renderer)dogRenderers[1] };
			val2.fadeTransitionWidth = 0f;
			LOD val4 = val2;
			val2 = default(LOD);
			val2.screenRelativeTransitionHeight = 0.009000001f;
			val2.renderers = (Renderer[])(object)new Renderer[1] { (Renderer)dogRenderers[2] };
			val2.fadeTransitionWidth = 0.435f;
			LOD val5 = val2;
			val.SetLODs((LOD[])(object)new LOD[3] { val3, val4, val5 });
		}
		catch (Exception ex2)
		{
			exceptionMessage = "Failed to set up the LOD.";
			exception = ex2;
			Debug.LogError((object)exceptionMessage);
			Debug.LogException(exception);
		}
		try
		{
			dogTorso = dogGameObject.transform.Find("Armature").Find("torso");
			Transform val6 = dogTorso.Find("head");
			Transform val7 = dogTorso.Find("arm.L");
			Transform val8 = dogTorso.Find("arm.R");
			Transform val9 = dogTorso.Find("butt").Find("leg.L");
			Transform val10 = dogTorso.Find("butt").Find("leg.R");
			Transform val11 = ((Component)this).transform.Find("ScavengerModel").Find("metarig").Find("spine");
			Transform sourceTransform = val11.Find("spine.001").Find("spine.002").Find("spine.003")
				.Find("spine.004");
			Transform sourceTransform2 = val11.Find("thigh.L");
			Transform sourceTransform3 = val11.Find("thigh.R");
			try
			{
				torsoConstraint = ((Component)dogTorso).gameObject.AddComponent<PositionConstraint>();
				PositionConstraint obj = torsoConstraint;
				ConstraintSource val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = val11;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj.AddSource(val12);
				torsoConstraint.translationAtRest = dogTorso.localPosition;
				torsoConstraint.translationOffset = dogTorso.InverseTransformPoint(val11.position);
				torsoConstraint.constraintActive = true;
				torsoConstraint.locked = true;
				RotationConstraint obj2 = ((Component)val6).gameObject.AddComponent<RotationConstraint>();
				val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = sourceTransform;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj2.AddSource(val12);
				obj2.rotationAtRest = val6.localEulerAngles;
				obj2.constraintActive = true;
				obj2.locked = true;
				RotationConstraint obj3 = ((Component)val7).gameObject.AddComponent<RotationConstraint>();
				val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = sourceTransform3;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj3.AddSource(val12);
				obj3.rotationAtRest = val7.localEulerAngles;
				obj3.constraintActive = true;
				obj3.locked = true;
				RotationConstraint obj4 = ((Component)val8).gameObject.AddComponent<RotationConstraint>();
				val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = sourceTransform2;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj4.AddSource(val12);
				obj4.rotationAtRest = val8.localEulerAngles;
				obj4.constraintActive = true;
				obj4.locked = true;
				RotationConstraint obj5 = ((Component)val9).gameObject.AddComponent<RotationConstraint>();
				val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = sourceTransform2;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj5.AddSource(val12);
				obj5.rotationAtRest = val9.localEulerAngles;
				obj5.constraintActive = true;
				obj5.locked = true;
				RotationConstraint obj6 = ((Component)val10).gameObject.AddComponent<RotationConstraint>();
				val12 = default(ConstraintSource);
				((ConstraintSource)(ref val12)).sourceTransform = sourceTransform3;
				((ConstraintSource)(ref val12)).weight = 1f;
				obj6.AddSource(val12);
				obj6.rotationAtRest = val10.localEulerAngles;
				obj6.constraintActive = true;
				obj6.locked = true;
			}
			catch (Exception ex3)
			{
				exceptionMessage = "Failed to set up the constraints.";
				exception = ex3;
				Debug.LogError((object)exceptionMessage);
				Debug.LogException(exception);
			}
			serverItemAnchor = val6.Find("serverItem");
			localItemAnchor = val6.Find("localItem");
		}
		catch (Exception ex4)
		{
			exceptionMessage = "Failed to retrieve bones. What the hell?";
			exception = ex4;
			Debug.LogError((object)exceptionMessage);
			Debug.LogException(exception);
		}
		humanGameObjects = (GameObject[])(object)new GameObject[6];
		humanGameObjects[0] = ((Component)playerController.thisPlayerModel).gameObject;
		humanGameObjects[1] = ((Component)playerController.thisPlayerModelLOD1).gameObject;
		humanGameObjects[2] = ((Component)playerController.thisPlayerModelLOD2).gameObject;
		humanGameObjects[3] = ((Component)playerController.thisPlayerModelArms).gameObject;
		humanGameObjects[4] = ((Component)playerController.playerBetaBadgeMesh).gameObject;
		humanGameObjects[5] = ((Component)((Component)playerController.playerBetaBadgeMesh).transform.parent.Find("LevelSticker")).gameObject;
	}

	public void EnableHumanModel(bool playAudio = true)
	{
		isDogActive = false;
		dogGameObject.SetActive(false);
		GameObject[] array = humanGameObjects;
		for (int i = 0; i < array.Length; i++)
		{
			array[i].SetActive(true);
		}
		if (playAudio)
		{
			playerController.movementAudio.PlayOneShot(humanClip);
		}
		if (((NetworkBehaviour)playerController).IsOwner && Object.op_Implicit((Object)(object)healthFill))
		{
			healthFill.sprite = humanFill;
			healthOutline.sprite = humanOutline;
		}
	}

	public void EnableDogModel(bool playAudio = true)
	{
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		isDogActive = true;
		dogGameObject.SetActive(true);
		((Renderer)dogRenderers[0]).shadowCastingMode = ((Renderer)playerController.thisPlayerModel).shadowCastingMode;
		GameObject[] array = humanGameObjects;
		for (int i = 0; i < array.Length; i++)
		{
			array[i].SetActive(false);
		}
		if (playAudio)
		{
			playerController.movementAudio.PlayOneShot(dogClip);
		}
		if (((NetworkBehaviour)playerController).IsOwner)
		{
			if (!Object.op_Implicit((Object)(object)healthFill))
			{
				healthFill = ((Component)HUDManager.Instance.selfRedCanvasGroup).GetComponent<Image>();
				healthOutline = ((Component)((Component)HUDManager.Instance.selfRedCanvasGroup).transform.parent.Find("Self")).GetComponent<Image>();
				humanFill = healthFill.sprite;
				humanOutline = healthOutline.sprite;
			}
			healthFill.sprite = dogFill;
			healthOutline.sprite = dogOutline;
		}
	}

	public void UpdateMaterial()
	{
		if (dogRenderers == null)
		{
			Debug.LogWarning((object)"Skipping material replacement on dog because there was an error earlier.");
			return;
		}
		SkinnedMeshRenderer[] array = dogRenderers;
		for (int i = 0; i < array.Length; i++)
		{
			((Renderer)array[i]).material = ((Renderer)playerController.thisPlayerModel).material;
		}
	}

	public void ToggleAndBroadcast(bool playAudio = true)
	{
		if (isDogActive)
		{
			EnableHumanModel();
		}
		else
		{
			EnableDogModel();
		}
		BroadcastSelectedModel(playAudio);
	}

	public void BroadcastSelectedModel(bool playAudio)
	{
		Debug.Log((object)$"Sent dog={isDogActive} on {playerController.playerClientId} ({playerController.playerUsername}).");
		ToggleData toggleData = new ToggleData
		{
			playerClientId = PlayerClientId,
			isDog = isDogActive,
			playAudio = playAudio
		};
		Network.Broadcast<ToggleData>("modelswitch", toggleData);
	}

	public static void RequestSelectedModelBroadcast()
	{
		Network.Broadcast("modelinfo");
	}

	private static void LoadImageResources()
	{
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: 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_007a: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Texture2D loadedAsset = BundleLoader.GetLoadedAsset<Texture2D>("assets/TPoseFilled.png");
			dogFill = Sprite.Create(loadedAsset, new Rect(0f, 0f, (float)((Texture)loadedAsset).width, (float)((Texture)loadedAsset).height), new Vector2(0.5f, 0.5f), 100f);
			Texture2D loadedAsset2 = BundleLoader.GetLoadedAsset<Texture2D>("assets/TPoseOutline.png");
			dogOutline = Sprite.Create(loadedAsset2, new Rect(0f, 0f, (float)((Texture)loadedAsset2).width, (float)((Texture)loadedAsset2).height), new Vector2(0.5f, 0.5f), 100f);
		}
		catch (Exception ex)
		{
			exceptionMessage = "Failed to retrieve images.";
			exception = ex;
			Debug.LogError((object)exceptionMessage);
			Debug.LogException(exception);
		}
	}

	private static IEnumerator LoadAudioResources()
	{
		string fullPath2 = GetAssemblyFullPath("ChangeSuitToHuman.wav");
		UnityWebRequest request2 = UnityWebRequestMultimedia.GetAudioClip(fullPath2, (AudioType)20);
		yield return request2.SendWebRequest();
		if (request2.error == null)
		{
			humanClip = DownloadHandlerAudioClip.GetContent(request2);
			((Object)humanClip).name = Path.GetFileName(fullPath2);
		}
		fullPath2 = GetAssemblyFullPath("ChangeSuitToDog.wav");
		request2 = UnityWebRequestMultimedia.GetAudioClip(fullPath2, (AudioType)20);
		yield return request2.SendWebRequest();
		if (request2.error == null)
		{
			dogClip = DownloadHandlerAudioClip.GetContent(request2);
			((Object)dogClip).name = Path.GetFileName(fullPath2);
		}
	}

	private static string GetAssemblyFullPath(string additionalPath)
	{
		string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
		return Path.GetFullPath((additionalPath != null) ? Path.Combine(directoryName, ".\\" + additionalPath) : directoryName);
	}
}
public class PlayerModelSwitcher : MonoBehaviour
{
	private void Start()
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_0162: Unknown result type (might be due to invalid IL or missing references)
		//IL_0167: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		GameObject obj = Object.Instantiate<GameObject>(BundleLoader.GetLoadedAsset<GameObject>("assets/Helmets.fbx"), ((Component)this).transform);
		obj.transform.localPosition = Vector3.zero;
		obj.transform.localRotation = Quaternion.identity;
		obj.transform.localScale = Vector3.one * 0.75f;
		Renderer component = obj.GetComponent<Renderer>();
		Material[] materials = component.materials;
		for (int i = 0; i < StartOfRound.Instance.unlockablesList.unlockables.Count; i++)
		{
			if (Object.op_Implicit((Object)(object)StartOfRound.Instance.unlockablesList.unlockables[0].suitMaterial))
			{
				materials[0] = StartOfRound.Instance.unlockablesList.unlockables[0].suitMaterial;
				break;
			}
		}
		materials[1] = ((Component)this).GetComponent<Renderer>().material;
		component.materials = materials;
		GameObject gameObject = ((Component)Object.Instantiate<ScanNodeProperties>(Object.FindObjectOfType<ScanNodeProperties>())).gameObject;
		gameObject.transform.parent = ((Component)this).transform;
		gameObject.transform.localPosition = new Vector3(0.75f, 0f, 0.8f);
		ScanNodeProperties component2 = gameObject.GetComponent<ScanNodeProperties>();
		component2.headerText = "Dog equipment";
		component2.subText = "Switch to the dog model here.";
		InteractTrigger obj2 = Object.Instantiate<InteractTrigger>(((Component)GameObject.Find("SpeakerAudio").transform.parent).GetComponentInChildren<InteractTrigger>());
		((Component)obj2).transform.position = ((Component)this).transform.TransformPoint(new Vector3(0.75f, 0f, 0.9f));
		((Component)obj2).transform.localScale = new Vector3(0.3f, 0.7f, 0.3f);
		obj2.hoverTip = "Switch model";
		obj2.interactable = true;
		obj2.cooldownTime = 1f;
		((UnityEventBase)obj2.onCancelAnimation).RemoveAllListeners();
		((UnityEventBase)obj2.onInteractEarly).RemoveAllListeners();
		((UnityEventBase)obj2.onStopInteract).RemoveAllListeners();
		((UnityEventBase)obj2.onInteract).RemoveAllListeners();
		((UnityEvent<PlayerControllerB>)(object)obj2.onInteract).AddListener((UnityAction<PlayerControllerB>)Interacted);
	}

	private void Interacted(PlayerControllerB player)
	{
		((Component)player).GetComponentInChildren<PlayerModelReplacer>().ToggleAndBroadcast();
	}
}
[BepInPlugin("PlayerDogModel", "PlayerDogModel", "1.0.3")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInProcess("Lethal Company.exe")]
public class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(PlayerControllerB))]
	internal class PlayerControllerBPatch
	{
		[HarmonyPatch("SpawnPlayerAnimation")]
		[HarmonyPostfix]
		public static void SpawnPlayerAnimationPatch(ref PlayerControllerB __instance)
		{
			GameObject[] allPlayerObjects = StartOfRound.Instance.allPlayerObjects;
			foreach (GameObject val in allPlayerObjects)
			{
				if (!Object.op_Implicit((Object)(object)val.GetComponent<PlayerModelReplacer>()))
				{
					val.gameObject.AddComponent<PlayerModelReplacer>();
				}
			}
			PlayerModelReplacer.RequestSelectedModelBroadcast();
		}
	}

	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("PositionSuitsOnRack")]
		[HarmonyPostfix]
		public static void PositionSuitsOnRackPatch(ref StartOfRound __instance)
		{
			if (!Object.op_Implicit((Object)(object)Object.FindObjectOfType<PlayerModelSwitcher>()))
			{
				GameObject.Find("NurbsPath.002").AddComponent<PlayerModelSwitcher>();
			}
		}
	}

	[HarmonyPatch(typeof(UnlockableSuit))]
	internal class UnlockableSuitPatch
	{
		[HarmonyPatch("SwitchSuitForPlayer")]
		[HarmonyPostfix]
		public static void SwitchSuitForPlayerPatch(PlayerControllerB player, int suitID, bool playAudio = true)
		{
			PlayerModelReplacer component = ((Component)player).GetComponent<PlayerModelReplacer>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.UpdateMaterial();
			}
		}
	}

	[HarmonyPatch(typeof(DeadBodyInfo))]
	internal class DeadBodyPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void StartPatch(ref DeadBodyInfo __instance)
		{
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			if (((Component)__instance.playerScript).GetComponent<PlayerModelReplacer>().IsDog)
			{
				SkinnedMeshRenderer component = ((Component)__instance).GetComponent<SkinnedMeshRenderer>();
				((Renderer)component).enabled = false;
				Material material = ((Renderer)component).material;
				Transform obj = ((Component)__instance).transform.Find("spine.001");
				Transform sourceTransform = obj.Find("spine.002").Find("spine.003").Find("spine.004");
				Transform sourceTransform2 = obj.Find("spine.002").Find("spine.003").Find("shoulder.L")
					.Find("arm.L_upper");
				Transform sourceTransform3 = obj.Find("spine.002").Find("spine.003").Find("shoulder.R")
					.Find("arm.R_upper");
				Transform sourceTransform4 = obj.Find("thigh.L");
				Transform sourceTransform5 = obj.Find("thigh.R");
				GameObject val = Object.Instantiate<GameObject>(BundleLoader.GetLoadedAsset<GameObject>("assets/DogRagdoll.fbx"), ((Component)__instance).transform);
				val.transform.position = ((Component)__instance).transform.position;
				val.transform.eulerAngles = ((Component)__instance).transform.eulerAngles;
				Transform transform = val.transform;
				transform.localScale *= 1.8f;
				SkinnedMeshRenderer[] componentsInChildren = val.GetComponentsInChildren<SkinnedMeshRenderer>();
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((Renderer)componentsInChildren[i]).material = material;
				}
				Transform obj2 = val.transform.Find("Armature").Find("torso");
				Transform val2 = obj2.Find("head");
				Transform val3 = obj2.Find("arm.L");
				Transform val4 = obj2.Find("arm.R");
				Transform val5 = obj2.Find("butt").Find("leg.L");
				Transform val6 = obj2.Find("butt").Find("leg.R");
				RotationConstraint obj3 = ((Component)val2).gameObject.AddComponent<RotationConstraint>();
				ConstraintSource val7 = default(ConstraintSource);
				((ConstraintSource)(ref val7)).sourceTransform = sourceTransform;
				((ConstraintSource)(ref val7)).weight = 1f;
				obj3.AddSource(val7);
				obj3.rotationAtRest = val2.localEulerAngles;
				obj3.constraintActive = true;
				obj3.locked = true;
				RotationConstraint obj4 = ((Component)val3).gameObject.AddComponent<RotationConstraint>();
				val7 = default(ConstraintSource);
				((ConstraintSource)(ref val7)).sourceTransform = sourceTransform3;
				((ConstraintSource)(ref val7)).weight = 1f;
				obj4.AddSource(val7);
				obj4.rotationAtRest = val3.localEulerAngles;
				obj4.constraintActive = true;
				obj4.locked = true;
				RotationConstraint obj5 = ((Component)val4).gameObject.AddComponent<RotationConstraint>();
				val7 = default(ConstraintSource);
				((ConstraintSource)(ref val7)).sourceTransform = sourceTransform2;
				((ConstraintSource)(ref val7)).weight = 1f;
				obj5.AddSource(val7);
				obj5.rotationAtRest = val4.localEulerAngles;
				obj5.constraintActive = true;
				obj5.locked = true;
				RotationConstraint obj6 = ((Component)val5).gameObject.AddComponent<RotationConstraint>();
				val7 = default(ConstraintSource);
				((ConstraintSource)(ref val7)).sourceTransform = sourceTransform4;
				((ConstraintSource)(ref val7)).weight = 1f;
				obj6.AddSource(val7);
				obj6.rotationAtRest = val5.localEulerAngles;
				obj6.constraintActive = true;
				obj6.locked = true;
				RotationConstraint obj7 = ((Component)val6).gameObject.AddComponent<RotationConstraint>();
				val7 = default(ConstraintSource);
				((ConstraintSource)(ref val7)).sourceTransform = sourceTransform5;
				((ConstraintSource)(ref val7)).weight = 1f;
				obj7.AddSource(val7);
				obj7.rotationAtRest = val6.localEulerAngles;
				obj7.constraintActive = true;
				obj7.locked = true;
			}
		}
	}

	public static Harmony _harmony;

	private void Awake()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Expected O, but got Unknown
		_harmony = new Harmony("PlayerDogModel");
		_harmony.PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"PlayerDogModel loaded");
		Networking.Initialize();
		BundleLoader.LoadAssetBundle(GetAssemblyFullPath("playerdog"), true);
	}

	private static string GetAssemblyFullPath(string additionalPath)
	{
		string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
		return Path.GetFullPath((additionalPath != null) ? Path.Combine(directoryName, ".\\" + additionalPath) : directoryName);
	}
}
public static class PluginInfo
{
	public const string PLUGIN_GUID = "PlayerDogModel";

	public const string PLUGIN_NAME = "PlayerDogModel";

	public const string PLUGIN_VERSION = "1.0.3";
}

FrozenDevv-ModPack-1.1.0/BepInEx/plugins/WeepingAngels/WeepingAngels.dll

Decompiled 7 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("WeepingAngel")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Change coilhead model to a wheeping angel")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("WeepingAngel")]
[assembly: AssemblyTitle("WeepingAngel")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace WeepingAngel
{
	[BepInPlugin("raydenoir.WeepingAngel", "WeepingAngel", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string BundleFolderPath = "assets/weepingangels/";

		public static ConfigEntry<bool> EnableConcreteSounds;

		public static ConfigEntry<int> VarietyChance;

		public static string PluginDirectory;

		public static ManualLogSource Logging;

		public static AudioClip Concrete;

		public static GameObject[] AngelModel;

		public static AssetBundle Bundle;

		private void Awake()
		{
			PluginDirectory = ((BaseUnityPlugin)this).Info.Location;
			Logging = ((BaseUnityPlugin)this).Logger;
			EnableConcreteSounds = ((BaseUnityPlugin)this).Config.Bind<bool>("Sounds", "EnableConcreteSounds", false, "true/false: If set to true, enables concrete grinding walking sounds instead of silence.");
			VarietyChance = ((BaseUnityPlugin)this).Config.Bind<int>("Variety", "VarietyChance", 100, "Integer number from 0 to 100 inclusive. A chance in percent to spawn a Weeping Angel instead of regular Coilhead. Values below 100 allow regular coilheads to also spawn.");
			if (VarietyChance.Value < 0)
			{
				VarietyChance.Value = 0;
			}
			if (VarietyChance.Value > 100)
			{
				VarietyChance.Value = 100;
			}
			LoadAssets();
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin raydenoir.WeepingAngel is loaded!");
		}

		private void LoadAssets()
		{
			try
			{
				Bundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(PluginDirectory), "weepingangels"));
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Couldn't load asset bundle: " + ex.Message));
				return;
			}
			try
			{
				if (EnableConcreteSounds.Value)
				{
					Concrete = Bundle.LoadAsset<AudioClip>("assets/weepingangels/concrete.wav");
				}
				AngelModel = (GameObject[])(object)new GameObject[3];
				for (int i = 0; i < 3; i++)
				{
					AngelModel[i] = Bundle.LoadAsset<GameObject>("assets/weepingangels/angel" + (i + 1) + ".prefab");
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Successfully loaded assets.");
			}
			catch (Exception ex2)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Couldn't load assets: " + ex2.Message));
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "WeepingAngel";

		public const string PLUGIN_NAME = "WeepingAngel";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace WeepingAngel.Patches
{
	[HarmonyPatch]
	public class CoilheadPatch : MonoBehaviour
	{
		private static HashSet<SpringManAI> angels = new HashSet<SpringManAI>();

		public static ManualLogSource Logging = Plugin.Logging;

		[HarmonyPatch(typeof(EnemyAI), "Start")]
		[HarmonyPostfix]
		public static void Summon173(EnemyAI __instance)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			if (__instance is SpringManAI)
			{
				SpringManAI val;
				try
				{
					val = (SpringManAI)__instance;
				}
				catch (Exception ex)
				{
					Logging.LogError((object)("Couldn't cast EnemyAI instance to SpringManAI: " + ex.Message));
					return;
				}
				Random random = new Random();
				int num = random.Next(100);
				if (num < Plugin.VarietyChance.Value)
				{
					angels.Add(val);
					Object.Destroy((Object)(object)((Component)((Component)val).transform.Find("SpringManModel").Find("Body")).gameObject.GetComponent<SkinnedMeshRenderer>());
					Object.Destroy((Object)(object)((Component)((Component)val).transform.Find("SpringManModel").Find("Head")).gameObject.GetComponent<MeshRenderer>());
					((Component)((Component)val).transform.Find("SpringManModel").Find("FoostepSFX")).gameObject.GetComponent<AudioSource>().mute = true;
					val.springNoises = (AudioClip[])(object)new AudioClip[1];
					InstantiateAngel(val);
					Logging.LogInfo((object)"Weeping Angel resources are loaded.");
				}
			}
		}

		private static void InstantiateAngel(SpringManAI parent)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.AngelModel != null && !((Object)(object)Plugin.AngelModel[0] == (Object)null) && angels.Contains(parent))
			{
				int num = new Random().Next(0, 3);
				GameObject val = Object.Instantiate<GameObject>(Plugin.AngelModel[num]);
				val.transform.SetParent(((Component)parent).transform.Find("SpringManModel"));
				val.transform.localPosition = Vector3.zero;
				val.transform.localRotation = Quaternion.identity;
				val.transform.localScale = Vector3.one;
			}
		}

		private static void ChangeAngelPose(SpringManAI parent)
		{
			//IL_0097: 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)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.AngelModel != null && !((Object)(object)Plugin.AngelModel[0] == (Object)null) && angels.Contains(parent))
			{
				Transform val = ((Component)parent).transform.Find("SpringManModel");
				Object.Destroy((Object)(object)((Component)val.GetChild(val.childCount - 1)).gameObject);
				int num = new Random().Next(0, 3);
				GameObject val2 = Object.Instantiate<GameObject>(Plugin.AngelModel[num]);
				val2.transform.SetParent(((Component)parent).transform.Find("SpringManModel"));
				val2.transform.localPosition = Vector3.zero;
				val2.transform.localRotation = Quaternion.identity;
				val2.transform.localScale = Vector3.one;
			}
		}

		[HarmonyPatch(typeof(SpringManAI), "SetAnimationGoClientRpc")]
		[HarmonyPostfix]
		[ClientRpc]
		public static void PlayWalkSounds(SpringManAI __instance)
		{
			ChangeAngelPose(__instance);
			if (Plugin.EnableConcreteSounds.Value && !((Object)(object)Plugin.Concrete == (Object)null) && angels.Contains(__instance))
			{
				((EnemyAI)__instance).creatureSFX.PlayOneShot(Plugin.Concrete, 0.6f);
				WalkieTalkie.TransmitOneShotAudio(((EnemyAI)__instance).creatureSFX, Plugin.Concrete, 0.4f);
			}
		}

		[HarmonyPatch(typeof(SpringManAI), "SetAnimationStopClientRpc")]
		[HarmonyPostfix]
		[ClientRpc]
		public static void StopWalkSounds(SpringManAI __instance)
		{
			if (Plugin.EnableConcreteSounds.Value && !((Object)(object)Plugin.Concrete == (Object)null) && angels.Contains(__instance) && ((EnemyAI)__instance).creatureSFX.isPlaying)
			{
				((EnemyAI)__instance).creatureSFX.Stop();
			}
		}
	}
}