Decompiled source of Smushi Archipelago v1.0.4

Smushi_Archipelago\Archipelago.MultiClient.Net.dll

Decompiled 3 days ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Archipelago.MultiClient.Net.Colors;
using Archipelago.MultiClient.Net.ConcurrentCollection;
using Archipelago.MultiClient.Net.Converters;
using Archipelago.MultiClient.Net.DataPackage;
using Archipelago.MultiClient.Net.Enums;
using Archipelago.MultiClient.Net.Exceptions;
using Archipelago.MultiClient.Net.Extensions;
using Archipelago.MultiClient.Net.Helpers;
using Archipelago.MultiClient.Net.MessageLog.Messages;
using Archipelago.MultiClient.Net.MessageLog.Parts;
using Archipelago.MultiClient.Net.Models;
using Archipelago.MultiClient.Net.Packets;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: ComVisible(false)]
[assembly: Guid("35a803ad-85ed-42e9-b1e3-c6b72096f0c1")]
[assembly: InternalsVisibleTo("Archipelago.MultiClient.Net.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Jarno Westhof, Hussein Farran, Zach Parks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © 2025")]
[assembly: AssemblyDescription("A client library for use with .NET based prog-langs for interfacing with Archipelago hosts.")]
[assembly: AssemblyFileVersion("6.7.0.0")]
[assembly: AssemblyInformationalVersion("6.7.0+c807746b6f1774cf1afe12af819acb078b55a333")]
[assembly: AssemblyProduct("Archipelago.MultiClient.Net")]
[assembly: AssemblyTitle("Archipelago.MultiClient.Net")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ArchipelagoMW/Archipelago.MultiClient.Net")]
[assembly: AssemblyVersion("6.7.0.0")]
internal interface IConcurrentHashSet<T>
{
	bool TryAdd(T item);

	bool Contains(T item);

	void UnionWith(T[] otherSet);

	T[] ToArray();

	ReadOnlyCollection<T> AsToReadOnlyCollection();

	ReadOnlyCollection<T> AsToReadOnlyCollectionExcept(IConcurrentHashSet<T> otherSet);
}
public class AttemptingStringEnumConverter : StringEnumConverter
{
	public AttemptingStringEnumConverter()
	{
	}

	public AttemptingStringEnumConverter(Type namingStrategyType)
		: base(namingStrategyType)
	{
	}

	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
	{
		try
		{
			return ((StringEnumConverter)this).ReadJson(reader, objectType, existingValue, serializer);
		}
		catch (JsonSerializationException)
		{
			return objectType.IsValueType ? Activator.CreateInstance(objectType) : null;
		}
	}
}
namespace Archipelago.MultiClient.Net
{
	[Serializable]
	public abstract class ArchipelagoPacketBase
	{
		[JsonIgnore]
		internal JObject jobject;

		[JsonProperty("cmd")]
		[JsonConverter(typeof(StringEnumConverter))]
		public abstract ArchipelagoPacketType PacketType { get; }

		public JObject ToJObject()
		{
			return jobject;
		}
	}
	public interface IArchipelagoSession : IArchipelagoSessionActions
	{
		IArchipelagoSocketHelper Socket { get; }

		IReceivedItemsHelper Items { get; }

		ILocationCheckHelper Locations { get; }

		IPlayerHelper Players { get; }

		IDataStorageHelper DataStorage { get; }

		IConnectionInfoProvider ConnectionInfo { get; }

		IRoomStateHelper RoomState { get; }

		IMessageLogHelper MessageLog { get; }

		IHintsHelper Hints { get; }

		Task<RoomInfoPacket> ConnectAsync();

		Task<LoginResult> LoginAsync(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true);

		LoginResult TryConnectAndLogin(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true);
	}
	public class ArchipelagoSession : IArchipelagoSession, IArchipelagoSessionActions
	{
		private const int ArchipelagoConnectionTimeoutInSeconds = 4;

		private ConnectionInfoHelper connectionInfo;

		private TaskCompletionSource<LoginResult> loginResultTask = new TaskCompletionSource<LoginResult>();

		private TaskCompletionSource<RoomInfoPacket> roomInfoPacketTask = new TaskCompletionSource<RoomInfoPacket>();

		public IArchipelagoSocketHelper Socket { get; }

		public IReceivedItemsHelper Items { get; }

		public ILocationCheckHelper Locations { get; }

		public IPlayerHelper Players { get; }

		public IDataStorageHelper DataStorage { get; }

		public IConnectionInfoProvider ConnectionInfo => connectionInfo;

		public IRoomStateHelper RoomState { get; }

		public IMessageLogHelper MessageLog { get; }

		public IHintsHelper Hints { get; }

		internal ArchipelagoSession(IArchipelagoSocketHelper socket, IReceivedItemsHelper items, ILocationCheckHelper locations, IPlayerHelper players, IRoomStateHelper roomState, ConnectionInfoHelper connectionInfoHelper, IDataStorageHelper dataStorage, IMessageLogHelper messageLog, IHintsHelper createHints)
		{
			Socket = socket;
			Items = items;
			Locations = locations;
			Players = players;
			RoomState = roomState;
			connectionInfo = connectionInfoHelper;
			DataStorage = dataStorage;
			MessageLog = messageLog;
			Hints = createHints;
			socket.PacketReceived += Socket_PacketReceived;
		}

		private void Socket_PacketReceived(ArchipelagoPacketBase packet)
		{
			if (!(packet is ConnectedPacket) && !(packet is ConnectionRefusedPacket))
			{
				if (packet is RoomInfoPacket result)
				{
					roomInfoPacketTask.TrySetResult(result);
				}
			}
			else
			{
				loginResultTask.TrySetResult(LoginResult.FromPacket(packet));
			}
		}

		public Task<RoomInfoPacket> ConnectAsync()
		{
			roomInfoPacketTask = new TaskCompletionSource<RoomInfoPacket>();
			Task.Factory.StartNew(delegate
			{
				try
				{
					Task task = Socket.ConnectAsync();
					task.Wait(TimeSpan.FromSeconds(4.0));
					if (!task.IsCompleted)
					{
						roomInfoPacketTask.TrySetCanceled();
					}
				}
				catch (AggregateException)
				{
					roomInfoPacketTask.TrySetCanceled();
				}
			});
			return roomInfoPacketTask.Task;
		}

		public Task<LoginResult> LoginAsync(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true)
		{
			loginResultTask = new TaskCompletionSource<LoginResult>();
			if (!roomInfoPacketTask.Task.IsCompleted)
			{
				loginResultTask.TrySetResult(new LoginFailure("You are not connected, run ConnectAsync() first"));
				return loginResultTask.Task;
			}
			connectionInfo.SetConnectionParameters(game, tags, itemsHandlingFlags, uuid);
			try
			{
				Socket.SendPacket(BuildConnectPacket(name, password, version, requestSlotData));
			}
			catch (ArchipelagoSocketClosedException)
			{
				loginResultTask.TrySetResult(new LoginFailure("You are not connected, run ConnectAsync() first"));
				return loginResultTask.Task;
			}
			SetResultAfterTimeout(loginResultTask, 4, new LoginFailure("Connection timed out."));
			return loginResultTask.Task;
		}

		private static void SetResultAfterTimeout<T>(TaskCompletionSource<T> task, int timeoutInSeconds, T result)
		{
			new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)).Token.Register(delegate
			{
				task.TrySetResult(result);
			});
		}

		public LoginResult TryConnectAndLogin(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true)
		{
			Task<RoomInfoPacket> task = ConnectAsync();
			try
			{
				task.Wait(TimeSpan.FromSeconds(4.0));
			}
			catch (AggregateException ex)
			{
				if (ex.GetBaseException() is OperationCanceledException)
				{
					return new LoginFailure("Connection timed out.");
				}
				return new LoginFailure(ex.GetBaseException().Message);
			}
			if (!task.IsCompleted)
			{
				return new LoginFailure("Connection timed out.");
			}
			return LoginAsync(game, name, itemsHandlingFlags, version, tags, uuid, password, requestSlotData).Result;
		}

		private ConnectPacket BuildConnectPacket(string name, string password, Version version, bool requestSlotData)
		{
			return new ConnectPacket
			{
				Game = ConnectionInfo.Game,
				Name = name,
				Password = password,
				Tags = ConnectionInfo.Tags,
				Uuid = ConnectionInfo.Uuid,
				Version = ((version != null) ? new NetworkVersion(version) : new NetworkVersion(0, 6, 0)),
				ItemsHandling = ConnectionInfo.ItemsHandlingFlags,
				RequestSlotData = requestSlotData
			};
		}

		public void Say(string message)
		{
			Socket.SendPacket(new SayPacket
			{
				Text = message
			});
		}

		public void SetClientState(ArchipelagoClientState state)
		{
			Socket.SendPacket(new StatusUpdatePacket
			{
				Status = state
			});
		}

		public void SetGoalAchieved()
		{
			SetClientState(ArchipelagoClientState.ClientGoal);
		}
	}
	public interface IArchipelagoSessionActions
	{
		void Say(string message);

		void SetClientState(ArchipelagoClientState state);

		void SetGoalAchieved();
	}
	public static class ArchipelagoSessionFactory
	{
		public static ArchipelagoSession CreateSession(Uri uri)
		{
			ArchipelagoSocketHelper socket = new ArchipelagoSocketHelper(uri);
			DataPackageCache cache = new DataPackageCache(socket);
			ConnectionInfoHelper connectionInfoHelper = new ConnectionInfoHelper(socket);
			PlayerHelper playerHelper = new PlayerHelper(socket, connectionInfoHelper);
			ItemInfoResolver itemInfoResolver = new ItemInfoResolver(cache, connectionInfoHelper);
			LocationCheckHelper locationCheckHelper = new LocationCheckHelper(socket, itemInfoResolver, connectionInfoHelper, playerHelper);
			ReceivedItemsHelper items = new ReceivedItemsHelper(socket, locationCheckHelper, itemInfoResolver, connectionInfoHelper, playerHelper);
			RoomStateHelper roomStateHelper = new RoomStateHelper(socket, locationCheckHelper);
			DataStorageHelper dataStorageHelper = new DataStorageHelper(socket, connectionInfoHelper);
			MessageLogHelper messageLog = new MessageLogHelper(socket, itemInfoResolver, playerHelper, connectionInfoHelper);
			HintsHelper createHints = new HintsHelper(socket, playerHelper, locationCheckHelper, roomStateHelper, dataStorageHelper);
			return new ArchipelagoSession(socket, items, locationCheckHelper, playerHelper, roomStateHelper, connectionInfoHelper, dataStorageHelper, messageLog, createHints);
		}

		public static ArchipelagoSession CreateSession(string hostname, int port = 38281)
		{
			return CreateSession(ParseUri(hostname, port));
		}

		internal static Uri ParseUri(string hostname, int port)
		{
			string text = hostname;
			if (!text.StartsWith("ws://") && !text.StartsWith("wss://"))
			{
				text = "unspecified://" + text;
			}
			if (!text.Substring(text.IndexOf("://", StringComparison.Ordinal) + 3).Contains(":"))
			{
				text += $":{port}";
			}
			if (text.EndsWith(":"))
			{
				text += port;
			}
			return new Uri(text);
		}
	}
	public abstract class LoginResult
	{
		public abstract bool Successful { get; }

		public static LoginResult FromPacket(ArchipelagoPacketBase packet)
		{
			if (!(packet is ConnectedPacket connectedPacket))
			{
				if (packet is ConnectionRefusedPacket connectionRefusedPacket)
				{
					return new LoginFailure(connectionRefusedPacket);
				}
				throw new ArgumentOutOfRangeException("packet", "packet is not a connection result packet");
			}
			return new LoginSuccessful(connectedPacket);
		}
	}
	public class LoginSuccessful : LoginResult
	{
		public override bool Successful => true;

		public int Team { get; }

		public int Slot { get; }

		public Dictionary<string, object> SlotData { get; }

		public LoginSuccessful(ConnectedPacket connectedPacket)
		{
			Team = connectedPacket.Team;
			Slot = connectedPacket.Slot;
			SlotData = connectedPacket.SlotData;
		}
	}
	public class LoginFailure : LoginResult
	{
		public override bool Successful => false;

		public ConnectionRefusedError[] ErrorCodes { get; }

		public string[] Errors { get; }

		public LoginFailure(ConnectionRefusedPacket connectionRefusedPacket)
		{
			if (connectionRefusedPacket.Errors != null)
			{
				ErrorCodes = connectionRefusedPacket.Errors.ToArray();
				Errors = ErrorCodes.Select(GetErrorMessage).ToArray();
			}
			else
			{
				ErrorCodes = new ConnectionRefusedError[0];
				Errors = new string[0];
			}
		}

		public LoginFailure(string message)
		{
			ErrorCodes = new ConnectionRefusedError[0];
			Errors = new string[1] { message };
		}

		private static string GetErrorMessage(ConnectionRefusedError errorCode)
		{
			return errorCode switch
			{
				ConnectionRefusedError.InvalidSlot => "The slot name did not match any slot on the server.", 
				ConnectionRefusedError.InvalidGame => "The slot is set to a different game on the server.", 
				ConnectionRefusedError.SlotAlreadyTaken => "The slot already has a connection with a different uuid established.", 
				ConnectionRefusedError.IncompatibleVersion => "The client and server version mismatch.", 
				ConnectionRefusedError.InvalidPassword => "The password is invalid.", 
				ConnectionRefusedError.InvalidItemsHandling => "The item handling flags provided are invalid.", 
				_ => $"Unknown error: {errorCode}.", 
			};
		}
	}
	internal class TwoWayLookup<TA, TB> : IEnumerable<KeyValuePair<TB, TA>>, IEnumerable
	{
		private readonly Dictionary<TA, TB> aToB = new Dictionary<TA, TB>();

		private readonly Dictionary<TB, TA> bToA = new Dictionary<TB, TA>();

		public TA this[TB b] => bToA[b];

		public TB this[TA a] => aToB[a];

		public void Add(TA a, TB b)
		{
			aToB[a] = b;
			bToA[b] = a;
		}

		public void Add(TB b, TA a)
		{
			Add(a, b);
		}

		public bool TryGetValue(TA a, out TB b)
		{
			return aToB.TryGetValue(a, out b);
		}

		public bool TryGetValue(TB b, out TA a)
		{
			return bToA.TryGetValue(b, out a);
		}

		public IEnumerator<KeyValuePair<TB, TA>> GetEnumerator()
		{
			return bToA.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
}
namespace Archipelago.MultiClient.Net.Packets
{
	public class BouncedPacket : BouncePacket
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Bounced;
	}
	public class BouncePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Bounce;

		[JsonProperty("games")]
		public List<string> Games { get; set; } = new List<string>();


		[JsonProperty("slots")]
		public List<int> Slots { get; set; } = new List<int>();


		[JsonProperty("tags")]
		public List<string> Tags { get; set; } = new List<string>();


		[JsonProperty("data")]
		public Dictionary<string, JToken> Data { get; set; }
	}
	public class ConnectedPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Connected;

		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }

		[JsonProperty("players")]
		public NetworkPlayer[] Players { get; set; }

		[JsonProperty("missing_locations")]
		public long[] MissingChecks { get; set; }

		[JsonProperty("checked_locations")]
		public long[] LocationsChecked { get; set; }

		[JsonProperty("slot_data")]
		public Dictionary<string, object> SlotData { get; set; }

		[JsonProperty("slot_info")]
		public Dictionary<int, NetworkSlot> SlotInfo { get; set; }

		[JsonProperty("hint_points")]
		public int? HintPoints { get; set; }
	}
	public class ConnectionRefusedPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.ConnectionRefused;

		[JsonProperty("errors", ItemConverterType = typeof(AttemptingStringEnumConverter))]
		public ConnectionRefusedError[] Errors { get; set; }
	}
	public class ConnectPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Connect;

		[JsonProperty("password")]
		public string Password { get; set; }

		[JsonProperty("game")]
		public string Game { get; set; }

		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("uuid")]
		public string Uuid { get; set; }

		[JsonProperty("version")]
		public NetworkVersion Version { get; set; }

		[JsonProperty("tags")]
		public string[] Tags { get; set; }

		[JsonProperty("items_handling")]
		public ItemsHandlingFlags ItemsHandling { get; set; }

		[JsonProperty("slot_data")]
		public bool RequestSlotData { get; set; }
	}
	public class ConnectUpdatePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.ConnectUpdate;

		[JsonProperty("tags")]
		public string[] Tags { get; set; }

		[JsonProperty("items_handling")]
		public ItemsHandlingFlags? ItemsHandling { get; set; }
	}
	public class CreateHintsPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.CreateHints;

		[JsonProperty("locations")]
		public long[] Locations { get; set; }

		[JsonProperty("player")]
		public int Player { get; set; }

		[JsonProperty("status")]
		public HintStatus Status { get; set; }
	}
	public class DataPackagePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.DataPackage;

		[JsonProperty("data")]
		public Archipelago.MultiClient.Net.Models.DataPackage DataPackage { get; set; }
	}
	public class GetDataPackagePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.GetDataPackage;

		[JsonProperty("games")]
		public string[] Games { get; set; }
	}
	public class GetPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Get;

		[JsonProperty("keys")]
		public string[] Keys { get; set; }
	}
	public class InvalidPacketPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.InvalidPacket;

		[JsonProperty("type")]
		public InvalidPacketErrorType ErrorType { get; set; }

		[JsonProperty("text")]
		public string ErrorText { get; set; }

		[JsonProperty("original_cmd")]
		public ArchipelagoPacketType OriginalCmd { get; set; }
	}
	public class LocationChecksPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.LocationChecks;

		[JsonProperty("locations")]
		public long[] Locations { get; set; }
	}
	public class LocationInfoPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.LocationInfo;

		[JsonProperty("locations")]
		public NetworkItem[] Locations { get; set; }
	}
	public class LocationScoutsPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.LocationScouts;

		[JsonProperty("locations")]
		public long[] Locations { get; set; }

		[JsonProperty("create_as_hint")]
		public int CreateAsHint { get; set; }
	}
	public class PrintJsonPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.PrintJSON;

		[JsonProperty("data")]
		public JsonMessagePart[] Data { get; set; }

		[JsonProperty("type")]
		[JsonConverter(typeof(AttemptingStringEnumConverter))]
		public JsonMessageType? MessageType { get; set; }
	}
	public class ItemPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("receiving")]
		public int ReceivingPlayer { get; set; }

		[JsonProperty("item")]
		public NetworkItem Item { get; set; }
	}
	public class ItemCheatPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("receiving")]
		public int ReceivingPlayer { get; set; }

		[JsonProperty("item")]
		public NetworkItem Item { get; set; }

		[JsonProperty("team")]
		public int Team { get; set; }
	}
	public class HintPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("receiving")]
		public int ReceivingPlayer { get; set; }

		[JsonProperty("item")]
		public NetworkItem Item { get; set; }

		[JsonProperty("found")]
		public bool? Found { get; set; }
	}
	public class JoinPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }

		[JsonProperty("tags")]
		public string[] Tags { get; set; }
	}
	public class LeavePrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }
	}
	public class ChatPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }

		[JsonProperty("message")]
		public string Message { get; set; }
	}
	public class ServerChatPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("message")]
		public string Message { get; set; }
	}
	public class TutorialPrintJsonPacket : PrintJsonPacket
	{
	}
	public class TagsChangedPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }

		[JsonProperty("tags")]
		public string[] Tags { get; set; }
	}
	public class CommandResultPrintJsonPacket : PrintJsonPacket
	{
	}
	public class AdminCommandResultPrintJsonPacket : PrintJsonPacket
	{
	}
	public class GoalPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }
	}
	public class ReleasePrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }
	}
	public class CollectPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }
	}
	public class CountdownPrintJsonPacket : PrintJsonPacket
	{
		[JsonProperty("countdown")]
		public int RemainingSeconds { get; set; }
	}
	public class ReceivedItemsPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.ReceivedItems;

		[JsonProperty("index")]
		public int Index { get; set; }

		[JsonProperty("items")]
		public NetworkItem[] Items { get; set; }
	}
	public class RetrievedPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Retrieved;

		[JsonProperty("keys")]
		public Dictionary<string, JToken> Data { get; set; }
	}
	public class RoomInfoPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.RoomInfo;

		[JsonProperty("version")]
		public NetworkVersion Version { get; set; }

		[JsonProperty("generator_version")]
		public NetworkVersion GeneratorVersion { get; set; }

		[JsonProperty("tags")]
		public string[] Tags { get; set; }

		[JsonProperty("password")]
		public bool Password { get; set; }

		[JsonProperty("permissions")]
		public Dictionary<string, Permissions> Permissions { get; set; }

		[JsonProperty("hint_cost")]
		public int HintCostPercentage { get; set; }

		[JsonProperty("location_check_points")]
		public int LocationCheckPoints { get; set; }

		[JsonProperty("players")]
		public NetworkPlayer[] Players { get; set; }

		[JsonProperty("games")]
		public string[] Games { get; set; }

		[JsonProperty("datapackage_checksums")]
		public Dictionary<string, string> DataPackageChecksums { get; set; }

		[JsonProperty("seed_name")]
		public string SeedName { get; set; }

		[JsonProperty("time")]
		public double Timestamp { get; set; }
	}
	public class RoomUpdatePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.RoomUpdate;

		[JsonProperty("tags")]
		public string[] Tags { get; set; }

		[JsonProperty("password")]
		public bool? Password { get; set; }

		[JsonProperty("permissions")]
		public Dictionary<string, Permissions> Permissions { get; set; } = new Dictionary<string, Permissions>();


		[JsonProperty("hint_cost")]
		public int? HintCostPercentage { get; set; }

		[JsonProperty("location_check_points")]
		public int? LocationCheckPoints { get; set; }

		[JsonProperty("players")]
		public NetworkPlayer[] Players { get; set; }

		[JsonProperty("hint_points")]
		public int? HintPoints { get; set; }

		[JsonProperty("checked_locations")]
		public long[] CheckedLocations { get; set; }
	}
	public class SayPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Say;

		[JsonProperty("text")]
		public string Text { get; set; }
	}
	public class SetNotifyPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.SetNotify;

		[JsonProperty("keys")]
		public string[] Keys { get; set; }
	}
	public class SetPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Set;

		[JsonProperty("key")]
		public string Key { get; set; }

		[JsonProperty("default")]
		public JToken DefaultValue { get; set; }

		[JsonProperty("operations")]
		public OperationSpecification[] Operations { get; set; }

		[JsonProperty("want_reply")]
		public bool WantReply { get; set; }

		[JsonExtensionData]
		public Dictionary<string, JToken> AdditionalArguments { get; set; }

		[OnDeserialized]
		internal void OnDeserializedMethod(StreamingContext context)
		{
			AdditionalArguments?.Remove("cmd");
		}
	}
	public class SetReplyPacket : SetPacket
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.SetReply;

		[JsonProperty("value")]
		public JToken Value { get; set; }

		[JsonProperty("original_value")]
		public JToken OriginalValue { get; set; }
	}
	public class StatusUpdatePacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.StatusUpdate;

		[JsonProperty("status")]
		public ArchipelagoClientState Status { get; set; }
	}
	public class SyncPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Sync;
	}
	internal class UnknownPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Unknown;
	}
	public class UpdateHintPacket : ArchipelagoPacketBase
	{
		public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.UpdateHint;

		[JsonProperty("player")]
		public int Player { get; set; }

		[JsonProperty("location")]
		public long Location { get; set; }

		[JsonProperty("status")]
		public HintStatus Status { get; set; }
	}
}
namespace Archipelago.MultiClient.Net.Models
{
	public struct Color : IEquatable<Color>
	{
		public static Color Red = new Color(byte.MaxValue, 0, 0);

		public static Color Green = new Color(0, 128, 0);

		public static Color Yellow = new Color(byte.MaxValue, byte.MaxValue, 0);

		public static Color Blue = new Color(0, 0, byte.MaxValue);

		public static Color Magenta = new Color(byte.MaxValue, 0, byte.MaxValue);

		public static Color Cyan = new Color(0, byte.MaxValue, byte.MaxValue);

		public static Color Black = new Color(0, 0, 0);

		public static Color White = new Color(byte.MaxValue, byte.MaxValue, byte.MaxValue);

		public static Color SlateBlue = new Color(106, 90, 205);

		public static Color Salmon = new Color(250, 128, 114);

		public static Color Plum = new Color(221, 160, 221);

		public byte R { get; set; }

		public byte G { get; set; }

		public byte B { get; set; }

		public Color(byte r, byte g, byte b)
		{
			R = r;
			G = g;
			B = b;
		}

		public override bool Equals(object obj)
		{
			if (obj is Color color && R == color.R && G == color.G)
			{
				return B == color.B;
			}
			return false;
		}

		public bool Equals(Color other)
		{
			if (R == other.R && G == other.G)
			{
				return B == other.B;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return ((-1520100960 * -1521134295 + R.GetHashCode()) * -1521134295 + G.GetHashCode()) * -1521134295 + B.GetHashCode();
		}

		public static bool operator ==(Color left, Color right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(Color left, Color right)
		{
			return !(left == right);
		}
	}
	public class DataPackage
	{
		[JsonProperty("games")]
		public Dictionary<string, GameData> Games { get; set; } = new Dictionary<string, GameData>();

	}
	public class DataStorageElement
	{
		internal DataStorageElementContext Context;

		internal List<OperationSpecification> Operations = new List<OperationSpecification>(0);

		internal DataStorageHelper.DataStorageUpdatedHandler Callbacks;

		internal Dictionary<string, JToken> AdditionalArguments = new Dictionary<string, JToken>(0);

		private JToken cachedValue;

		public event DataStorageHelper.DataStorageUpdatedHandler OnValueChanged
		{
			add
			{
				Context.AddHandler(Context.Key, value);
			}
			remove
			{
				Context.RemoveHandler(Context.Key, value);
			}
		}

		internal DataStorageElement(DataStorageElementContext context)
		{
			Context = context;
		}

		internal DataStorageElement(OperationType operationType, JToken value)
		{
			Operations = new List<OperationSpecification>(1)
			{
				new OperationSpecification
				{
					OperationType = operationType,
					Value = value
				}
			};
		}

		internal DataStorageElement(DataStorageElement source, OperationType operationType, JToken value)
			: this(source.Context)
		{
			Operations = source.Operations.ToList();
			Callbacks = source.Callbacks;
			AdditionalArguments = source.AdditionalArguments;
			Operations.Add(new OperationSpecification
			{
				OperationType = operationType,
				Value = value
			});
		}

		internal DataStorageElement(DataStorageElement source, Callback callback)
			: this(source.Context)
		{
			Operations = source.Operations.ToList();
			Callbacks = source.Callbacks;
			AdditionalArguments = source.AdditionalArguments;
			Callbacks = (DataStorageHelper.DataStorageUpdatedHandler)Delegate.Combine(Callbacks, callback.Method);
		}

		internal DataStorageElement(DataStorageElement source, AdditionalArgument additionalArgument)
			: this(source.Context)
		{
			Operations = source.Operations.ToList();
			Callbacks = source.Callbacks;
			AdditionalArguments = source.AdditionalArguments;
			AdditionalArguments[additionalArgument.Key] = additionalArgument.Value;
		}

		public static DataStorageElement operator ++(DataStorageElement a)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(1));
		}

		public static DataStorageElement operator --(DataStorageElement a)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(-1));
		}

		public static DataStorageElement operator +(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, string b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator +(DataStorageElement a, JToken b)
		{
			return new DataStorageElement(a, OperationType.Add, b);
		}

		public static DataStorageElement operator +(DataStorageElement a, IEnumerable b)
		{
			return new DataStorageElement(a, OperationType.Add, (JToken)(object)JArray.FromObject((object)b));
		}

		public static DataStorageElement operator +(DataStorageElement a, OperationSpecification s)
		{
			return new DataStorageElement(a, s.OperationType, s.Value);
		}

		public static DataStorageElement operator +(DataStorageElement a, Callback c)
		{
			return new DataStorageElement(a, c);
		}

		public static DataStorageElement operator +(DataStorageElement a, AdditionalArgument arg)
		{
			return new DataStorageElement(a, arg);
		}

		public static DataStorageElement operator *(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator *(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator *(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator *(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator *(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator %(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator %(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator %(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator %(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator %(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator ^(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator ^(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator ^(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator ^(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator ^(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b));
		}

		public static DataStorageElement operator -(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(-b)));
		}

		public static DataStorageElement operator -(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(-b)));
		}

		public static DataStorageElement operator -(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(0f - b)));
		}

		public static DataStorageElement operator -(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(0.0 - b)));
		}

		public static DataStorageElement operator -(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(-b)));
		}

		public static DataStorageElement operator /(DataStorageElement a, int b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1m / (decimal)b)));
		}

		public static DataStorageElement operator /(DataStorageElement a, long b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1m / (decimal)b)));
		}

		public static DataStorageElement operator /(DataStorageElement a, float b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1.0 / (double)b)));
		}

		public static DataStorageElement operator /(DataStorageElement a, double b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1.0 / b)));
		}

		public static DataStorageElement operator /(DataStorageElement a, decimal b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1m / b)));
		}

		public static implicit operator DataStorageElement(bool b)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(b));
		}

		public static implicit operator DataStorageElement(int i)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(i));
		}

		public static implicit operator DataStorageElement(long l)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(l));
		}

		public static implicit operator DataStorageElement(decimal m)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(m));
		}

		public static implicit operator DataStorageElement(double d)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(d));
		}

		public static implicit operator DataStorageElement(float f)
		{
			return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(f));
		}

		public static implicit operator DataStorageElement(string s)
		{
			if (s != null)
			{
				return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(s));
			}
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JValue.CreateNull());
		}

		public static implicit operator DataStorageElement(JToken o)
		{
			return new DataStorageElement(OperationType.Replace, o);
		}

		public static implicit operator DataStorageElement(Array a)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)a));
		}

		public static implicit operator DataStorageElement(List<bool> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<int> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<long> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<decimal> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<double> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<float> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<string> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator DataStorageElement(List<object> l)
		{
			return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l));
		}

		public static implicit operator bool(DataStorageElement e)
		{
			return RetrieveAndReturnBoolValue<bool>(e);
		}

		public static implicit operator bool?(DataStorageElement e)
		{
			return RetrieveAndReturnBoolValue<bool?>(e);
		}

		public static implicit operator int(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<int>(e);
		}

		public static implicit operator int?(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<int?>(e);
		}

		public static implicit operator long(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<long>(e);
		}

		public static implicit operator long?(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<long?>(e);
		}

		public static implicit operator float(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<float>(e);
		}

		public static implicit operator float?(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<float?>(e);
		}

		public static implicit operator double(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<double>(e);
		}

		public static implicit operator double?(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<double?>(e);
		}

		public static implicit operator decimal(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<decimal>(e);
		}

		public static implicit operator decimal?(DataStorageElement e)
		{
			return RetrieveAndReturnDecimalValue<decimal?>(e);
		}

		public static implicit operator string(DataStorageElement e)
		{
			return RetrieveAndReturnStringValue(e);
		}

		public static implicit operator bool[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<bool[]>(e);
		}

		public static implicit operator int[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<int[]>(e);
		}

		public static implicit operator long[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<long[]>(e);
		}

		public static implicit operator decimal[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<decimal[]>(e);
		}

		public static implicit operator double[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<double[]>(e);
		}

		public static implicit operator float[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<float[]>(e);
		}

		public static implicit operator string[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<string[]>(e);
		}

		public static implicit operator object[](DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<object[]>(e);
		}

		public static implicit operator List<bool>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<bool>>(e);
		}

		public static implicit operator List<int>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<int>>(e);
		}

		public static implicit operator List<long>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<long>>(e);
		}

		public static implicit operator List<decimal>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<decimal>>(e);
		}

		public static implicit operator List<double>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<double>>(e);
		}

		public static implicit operator List<float>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<float>>(e);
		}

		public static implicit operator List<string>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<string>>(e);
		}

		public static implicit operator List<object>(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<List<object>>(e);
		}

		public static implicit operator Array(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<Array>(e);
		}

		public static implicit operator JArray(DataStorageElement e)
		{
			return RetrieveAndReturnArrayValue<JArray>(e);
		}

		public static implicit operator JToken(DataStorageElement e)
		{
			return e.Context.GetData(e.Context.Key);
		}

		public static DataStorageElement operator +(DataStorageElement a, BigInteger b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.Parse(b.ToString()));
		}

		public static DataStorageElement operator *(DataStorageElement a, BigInteger b)
		{
			return new DataStorageElement(a, OperationType.Mul, JToken.Parse(b.ToString()));
		}

		public static DataStorageElement operator %(DataStorageElement a, BigInteger b)
		{
			return new DataStorageElement(a, OperationType.Mod, JToken.Parse(b.ToString()));
		}

		public static DataStorageElement operator ^(DataStorageElement a, BigInteger b)
		{
			return new DataStorageElement(a, OperationType.Pow, JToken.Parse(b.ToString()));
		}

		public static DataStorageElement operator -(DataStorageElement a, BigInteger b)
		{
			return new DataStorageElement(a, OperationType.Add, JToken.Parse((-b).ToString()));
		}

		public static DataStorageElement operator /(DataStorageElement a, BigInteger b)
		{
			throw new InvalidOperationException("DataStorage[Key] / BigInterger is not supported, due to loss of precision when using integer division");
		}

		public static implicit operator DataStorageElement(BigInteger bi)
		{
			return new DataStorageElement(OperationType.Replace, JToken.Parse(bi.ToString()));
		}

		public static implicit operator BigInteger(DataStorageElement e)
		{
			return RetrieveAndReturnBigIntegerValue<BigInteger>(e);
		}

		public static implicit operator BigInteger?(DataStorageElement e)
		{
			return RetrieveAndReturnBigIntegerValue<BigInteger?>(e);
		}

		private static T RetrieveAndReturnBigIntegerValue<T>(DataStorageElement e)
		{
			if (e.cachedValue != null)
			{
				if (!BigInteger.TryParse(((object)e.cachedValue).ToString(), out var result))
				{
					return default(T);
				}
				return (T)Convert.ChangeType(result, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T));
			}
			BigInteger result2;
			BigInteger? bigInteger = (BigInteger.TryParse(((object)e.Context.GetData(e.Context.Key)).ToString(), out result2) ? new BigInteger?(result2) : null);
			if (!bigInteger.HasValue && !IsNullable<T>())
			{
				bigInteger = Activator.CreateInstance<BigInteger>();
			}
			foreach (OperationSpecification operation in e.Operations)
			{
				if (operation.OperationType == OperationType.Floor || operation.OperationType == OperationType.Ceil)
				{
					continue;
				}
				if (!BigInteger.TryParse(((object)operation.Value).ToString(), NumberStyles.AllowLeadingSign, null, out var result3))
				{
					throw new InvalidOperationException($"DataStorage[Key] cannot be converted to BigInterger as its value its not an integer number, value: {operation.Value}");
				}
				switch (operation.OperationType)
				{
				case OperationType.Replace:
					bigInteger = result3;
					break;
				case OperationType.Add:
					bigInteger += result3;
					break;
				case OperationType.Mul:
					bigInteger *= result3;
					break;
				case OperationType.Mod:
					bigInteger %= result3;
					break;
				case OperationType.Pow:
					bigInteger = BigInteger.Pow(bigInteger.Value, (int)operation.Value);
					break;
				case OperationType.Max:
				{
					BigInteger value = result3;
					BigInteger? bigInteger2 = bigInteger;
					if (value > bigInteger2)
					{
						bigInteger = result3;
					}
					break;
				}
				case OperationType.Min:
				{
					BigInteger value = result3;
					BigInteger? bigInteger2 = bigInteger;
					if (value < bigInteger2)
					{
						bigInteger = result3;
					}
					break;
				}
				case OperationType.Xor:
					bigInteger ^= result3;
					break;
				case OperationType.Or:
					bigInteger |= result3;
					break;
				case OperationType.And:
					bigInteger &= result3;
					break;
				case OperationType.LeftShift:
					bigInteger <<= (int)operation.Value;
					break;
				case OperationType.RightShift:
					bigInteger >>= (int)operation.Value;
					break;
				}
			}
			e.cachedValue = JToken.Parse(bigInteger.ToString());
			if (!bigInteger.HasValue)
			{
				return default(T);
			}
			return (T)Convert.ChangeType(bigInteger.Value, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T));
		}

		public void Initialize(JToken value)
		{
			Context.Initialize(Context.Key, value);
		}

		public void Initialize(IEnumerable value)
		{
			Context.Initialize(Context.Key, (JToken)(object)JArray.FromObject((object)value));
		}

		public Task<T> GetAsync<T>()
		{
			return GetAsync().ContinueWith((Task<JToken> r) => r.Result.ToObject<T>());
		}

		public Task<JToken> GetAsync()
		{
			return Context.GetAsync(Context.Key);
		}

		private static T RetrieveAndReturnArrayValue<T>(DataStorageElement e)
		{
			//IL_000e: 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_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Invalid comparison between Unknown and I4
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Invalid comparison between Unknown and I4
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			if (e.cachedValue != null)
			{
				return ((JToken)(JArray)e.cachedValue).ToObject<T>();
			}
			JArray val = (JArray)(((object)e.Context.GetData(e.Context.Key).ToObject<JArray>()) ?? ((object)new JArray()));
			foreach (OperationSpecification operation in e.Operations)
			{
				switch (operation.OperationType)
				{
				case OperationType.Add:
					if ((int)operation.Value.Type != 2)
					{
						throw new InvalidOperationException($"Cannot perform operation {OperationType.Add} on Array value, with a non Array value: {operation.Value}");
					}
					((JContainer)val).Merge((object)operation.Value);
					break;
				case OperationType.Replace:
					if ((int)operation.Value.Type != 2)
					{
						throw new InvalidOperationException($"Cannot replace Array value, with a non Array value: {operation.Value}");
					}
					val = (JArray)(((object)operation.Value.ToObject<JArray>()) ?? ((object)new JArray()));
					break;
				default:
					throw new InvalidOperationException($"Cannot perform operation {operation.OperationType} on Array value");
				}
			}
			e.cachedValue = (JToken)(object)val;
			return ((JToken)val).ToObject<T>();
		}

		private static string RetrieveAndReturnStringValue(DataStorageElement e)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Invalid comparison between Unknown and I4
			if (e.cachedValue != null)
			{
				return (string)e.cachedValue;
			}
			JToken val = e.Context.GetData(e.Context.Key);
			string text = (((int)val.Type == 10) ? null : ((object)val).ToString());
			foreach (OperationSpecification operation in e.Operations)
			{
				switch (operation.OperationType)
				{
				case OperationType.Add:
					text += (string)operation.Value;
					break;
				case OperationType.Mul:
					if ((int)operation.Value.Type != 6)
					{
						throw new InvalidOperationException($"Cannot perform operation {OperationType.Mul} on string value, with a non interger value: {operation.Value}");
					}
					text = string.Concat(Enumerable.Repeat(text, (int)operation.Value));
					break;
				case OperationType.Replace:
					text = (string)operation.Value;
					break;
				default:
					throw new InvalidOperationException($"Cannot perform operation {operation.OperationType} on string value");
				}
			}
			if (text == null)
			{
				e.cachedValue = (JToken)(object)JValue.CreateNull();
			}
			else
			{
				e.cachedValue = JToken.op_Implicit(text);
			}
			return (string)e.cachedValue;
		}

		private static T RetrieveAndReturnBoolValue<T>(DataStorageElement e)
		{
			if (e.cachedValue != null)
			{
				return e.cachedValue.ToObject<T>();
			}
			bool? flag = e.Context.GetData(e.Context.Key).ToObject<bool?>() ?? ((bool?)Activator.CreateInstance(typeof(T)));
			foreach (OperationSpecification operation in e.Operations)
			{
				if (operation.OperationType == OperationType.Replace)
				{
					flag = (bool?)operation.Value;
					continue;
				}
				throw new InvalidOperationException($"Cannot perform operation {operation.OperationType} on boolean value");
			}
			e.cachedValue = JToken.op_Implicit(flag);
			if (!flag.HasValue)
			{
				return default(T);
			}
			return (T)Convert.ChangeType(flag.Value, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T));
		}

		private static T RetrieveAndReturnDecimalValue<T>(DataStorageElement e)
		{
			if (e.cachedValue != null)
			{
				return e.cachedValue.ToObject<T>();
			}
			decimal? num = e.Context.GetData(e.Context.Key).ToObject<decimal?>();
			if (!num.HasValue && !IsNullable<T>())
			{
				num = Activator.CreateInstance<decimal>();
			}
			foreach (OperationSpecification operation in e.Operations)
			{
				switch (operation.OperationType)
				{
				case OperationType.Replace:
					num = (decimal)operation.Value;
					break;
				case OperationType.Add:
					num += (decimal?)(decimal)operation.Value;
					break;
				case OperationType.Mul:
					num *= (decimal?)(decimal)operation.Value;
					break;
				case OperationType.Mod:
					num %= (decimal?)(decimal)operation.Value;
					break;
				case OperationType.Pow:
					num = (decimal)Math.Pow((double)num.Value, (double)operation.Value);
					break;
				case OperationType.Max:
					num = Math.Max(num.Value, (decimal)operation.Value);
					break;
				case OperationType.Min:
					num = Math.Min(num.Value, (decimal)operation.Value);
					break;
				case OperationType.Xor:
					num = (long)num.Value ^ (long)operation.Value;
					break;
				case OperationType.Or:
					num = (long)num.Value | (long)operation.Value;
					break;
				case OperationType.And:
					num = (long)num.Value & (long)operation.Value;
					break;
				case OperationType.LeftShift:
					num = (long)num.Value << (int)operation.Value;
					break;
				case OperationType.RightShift:
					num = (long)num.Value >> (int)operation.Value;
					break;
				case OperationType.Floor:
					num = Math.Floor(num.Value);
					break;
				case OperationType.Ceil:
					num = Math.Ceiling(num.Value);
					break;
				}
			}
			e.cachedValue = JToken.op_Implicit(num);
			if (!num.HasValue)
			{
				return default(T);
			}
			return (T)Convert.ChangeType(num.Value, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T));
		}

		private static bool IsNullable<T>()
		{
			if (typeof(T).IsGenericType)
			{
				return typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition();
			}
			return false;
		}

		public T To<T>()
		{
			if (Operations.Count != 0)
			{
				throw new InvalidOperationException("DataStorageElement.To<T>() cannot be used together with other operations on the DataStorageElement");
			}
			return Context.GetData(Context.Key).ToObject<T>();
		}

		public override string ToString()
		{
			return (Context?.ToString() ?? "(null)") + ", (" + ListOperations() + ")";
		}

		private string ListOperations()
		{
			if (Operations != null)
			{
				return string.Join(", ", Operations.Select((OperationSpecification o) => o.ToString()).ToArray());
			}
			return "none";
		}
	}
	internal class DataStorageElementContext
	{
		internal string Key { get; set; }

		internal Action<string, DataStorageHelper.DataStorageUpdatedHandler> AddHandler { get; set; }

		internal Action<string, DataStorageHelper.DataStorageUpdatedHandler> RemoveHandler { get; set; }

		internal Func<string, JToken> GetData { get; set; }

		internal Action<string, JToken> Initialize { get; set; }

		internal Func<string, Task<JToken>> GetAsync { get; set; }

		public override string ToString()
		{
			return "Key: " + Key;
		}
	}
	public class GameData
	{
		[JsonProperty("location_name_to_id")]
		public Dictionary<string, long> LocationLookup { get; set; } = new Dictionary<string, long>();


		[JsonProperty("item_name_to_id")]
		public Dictionary<string, long> ItemLookup { get; set; } = new Dictionary<string, long>();


		[Obsolete("use Checksum instead")]
		[JsonProperty("version")]
		public int Version { get; set; }

		[JsonProperty("checksum")]
		public string Checksum { get; set; }
	}
	public class Hint
	{
		[JsonProperty("receiving_player")]
		public int ReceivingPlayer { get; set; }

		[JsonProperty("finding_player")]
		public int FindingPlayer { get; set; }

		[JsonProperty("item")]
		public long ItemId { get; set; }

		[JsonProperty("location")]
		public long LocationId { get; set; }

		[JsonProperty("item_flags")]
		public ItemFlags ItemFlags { get; set; }

		[JsonProperty("found")]
		public bool Found { get; set; }

		[JsonProperty("entrance")]
		public string Entrance { get; set; }

		[JsonProperty("status")]
		public HintStatus Status { get; set; }
	}
	public class ItemInfo
	{
		private readonly IItemInfoResolver itemInfoResolver;

		public long ItemId { get; }

		public long LocationId { get; }

		public PlayerInfo Player { get; }

		public ItemFlags Flags { get; }

		public string ItemName => itemInfoResolver.GetItemName(ItemId, ItemGame);

		public string ItemDisplayName => ItemName ?? $"Item: {ItemId}";

		public string LocationName => itemInfoResolver.GetLocationName(LocationId, LocationGame);

		public string LocationDisplayName => LocationName ?? $"Location: {LocationId}";

		public string ItemGame { get; }

		public string LocationGame { get; }

		public ItemInfo(NetworkItem item, string receiverGame, string senderGame, IItemInfoResolver itemInfoResolver, PlayerInfo player)
		{
			this.itemInfoResolver = itemInfoResolver;
			ItemGame = receiverGame;
			LocationGame = senderGame;
			ItemId = item.Item;
			LocationId = item.Location;
			Flags = item.Flags;
			Player = player;
		}

		public SerializableItemInfo ToSerializable()
		{
			return new SerializableItemInfo
			{
				IsScout = (GetType() == typeof(ScoutedItemInfo)),
				ItemId = ItemId,
				LocationId = LocationId,
				PlayerSlot = Player,
				Player = Player,
				Flags = Flags,
				ItemGame = ItemGame,
				ItemName = ItemName,
				LocationGame = LocationGame,
				LocationName = LocationName
			};
		}
	}
	public class ScoutedItemInfo : ItemInfo
	{
		public new PlayerInfo Player => base.Player;

		public bool IsReceiverRelatedToActivePlayer { get; }

		public ScoutedItemInfo(NetworkItem item, string receiverGame, string senderGame, IItemInfoResolver itemInfoResolver, IPlayerHelper players, PlayerInfo player)
			: base(item, receiverGame, senderGame, itemInfoResolver, player)
		{
			IsReceiverRelatedToActivePlayer = (players.ActivePlayer ?? new PlayerInfo()).IsRelatedTo(player);
		}
	}
	public class JsonMessagePart
	{
		[JsonProperty("type")]
		[JsonConverter(typeof(AttemptingStringEnumConverter), new object[] { typeof(SnakeCaseNamingStrategy) })]
		public JsonMessagePartType? Type { get; set; }

		[JsonProperty("color")]
		[JsonConverter(typeof(AttemptingStringEnumConverter), new object[] { typeof(SnakeCaseNamingStrategy) })]
		public JsonMessagePartColor? Color { get; set; }

		[JsonProperty("text")]
		public string Text { get; set; }

		[JsonProperty("player")]
		public int? Player { get; set; }

		[JsonProperty("flags")]
		public ItemFlags? Flags { get; set; }

		[JsonProperty("hint_status")]
		public HintStatus? HintStatus { get; set; }
	}
	public struct NetworkItem
	{
		[JsonProperty("item")]
		public long Item { get; set; }

		[JsonProperty("location")]
		public long Location { get; set; }

		[JsonProperty("player")]
		public int Player { get; set; }

		[JsonProperty("flags")]
		public ItemFlags Flags { get; set; }
	}
	public struct NetworkPlayer
	{
		[JsonProperty("team")]
		public int Team { get; set; }

		[JsonProperty("slot")]
		public int Slot { get; set; }

		[JsonProperty("alias")]
		public string Alias { get; set; }

		[JsonProperty("name")]
		public string Name { get; set; }
	}
	public struct NetworkSlot
	{
		[JsonProperty("name")]
		public string Name { get; set; }

		[JsonProperty("game")]
		public string Game { get; set; }

		[JsonProperty("type")]
		public SlotType Type { get; set; }

		[JsonProperty("group_members")]
		public int[] GroupMembers { get; set; }
	}
	public class NetworkVersion
	{
		[JsonProperty("major")]
		public int Major { get; set; }

		[JsonProperty("minor")]
		public int Minor { get; set; }

		[JsonProperty("build")]
		public int Build { get; set; }

		[JsonProperty("class")]
		public string Class => "Version";

		public NetworkVersion()
		{
		}

		public NetworkVersion(int major, int minor, int build)
		{
			Major = major;
			Minor = minor;
			Build = build;
		}

		public NetworkVersion(Version version)
		{
			Major = version.Major;
			Minor = version.Minor;
			Build = version.Build;
		}

		public Version ToVersion()
		{
			return new Version(Major, Minor, Build);
		}
	}
	public class OperationSpecification
	{
		[JsonProperty("operation")]
		[JsonConverter(typeof(AttemptingStringEnumConverter), new object[] { typeof(SnakeCaseNamingStrategy) })]
		public OperationType OperationType;

		[JsonProperty("value")]
		public JToken Value { get; set; }

		public override string ToString()
		{
			return $"{OperationType}: {Value}";
		}
	}
	public static class Operation
	{
		public static OperationSpecification Min(int i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Min(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Min(float i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Min(double i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Min(decimal i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Min(JToken i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = i
			};
		}

		public static OperationSpecification Min(BigInteger i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Min,
				Value = JToken.Parse(i.ToString())
			};
		}

		public static OperationSpecification Max(int i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Max(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Max(float i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Max(double i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Max(decimal i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Max(JToken i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = i
			};
		}

		public static OperationSpecification Max(BigInteger i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Max,
				Value = JToken.Parse(i.ToString())
			};
		}

		public static OperationSpecification Remove(JToken value)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Remove,
				Value = value
			};
		}

		public static OperationSpecification Pop(int value)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Pop,
				Value = JToken.op_Implicit(value)
			};
		}

		public static OperationSpecification Pop(JToken value)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Pop,
				Value = value
			};
		}

		public static OperationSpecification Update(IDictionary dictionary)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Update,
				Value = (JToken)(object)JObject.FromObject((object)dictionary)
			};
		}

		public static OperationSpecification Floor()
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Floor,
				Value = null
			};
		}

		public static OperationSpecification Ceiling()
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Ceil,
				Value = null
			};
		}
	}
	public static class Bitwise
	{
		public static OperationSpecification Xor(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Xor,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Xor(BigInteger i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Xor,
				Value = JToken.Parse(i.ToString())
			};
		}

		public static OperationSpecification Or(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Or,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification Or(BigInteger i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.Or,
				Value = JToken.Parse(i.ToString())
			};
		}

		public static OperationSpecification And(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.And,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification And(BigInteger i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.And,
				Value = JToken.Parse(i.ToString())
			};
		}

		public static OperationSpecification LeftShift(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.LeftShift,
				Value = JToken.op_Implicit(i)
			};
		}

		public static OperationSpecification RightShift(long i)
		{
			return new OperationSpecification
			{
				OperationType = OperationType.RightShift,
				Value = JToken.op_Implicit(i)
			};
		}
	}
	public class Callback
	{
		internal DataStorageHelper.DataStorageUpdatedHandler Method { get; set; }

		private Callback()
		{
		}

		public static Callback Add(DataStorageHelper.DataStorageUpdatedHandler callback)
		{
			return new Callback
			{
				Method = callback
			};
		}
	}
	public class AdditionalArgument
	{
		internal string Key { get; set; }

		internal JToken Value { get; set; }

		private AdditionalArgument()
		{
		}

		public static AdditionalArgument Add(string name, JToken value)
		{
			return new AdditionalArgument
			{
				Key = name,
				Value = value
			};
		}
	}
	public class MinimalSerializableItemInfo
	{
		public long ItemId { get; set; }

		public long LocationId { get; set; }

		public int PlayerSlot { get; set; }

		public ItemFlags Flags { get; set; }

		public string ItemGame { get; set; }

		public string LocationGame { get; set; }
	}
	public class SerializableItemInfo : MinimalSerializableItemInfo
	{
		public bool IsScout { get; set; }

		public PlayerInfo Player { get; set; }

		public string ItemName { get; set; }

		public string LocationName { get; set; }

		[JsonIgnore]
		public string ItemDisplayName => ItemName ?? $"Item: {base.ItemId}";

		[JsonIgnore]
		public string LocationDisplayName => LocationName ?? $"Location: {base.LocationId}";

		public string ToJson(bool full = false)
		{
			//IL_005d: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			MinimalSerializableItemInfo minimalSerializableItemInfo = this;
			if (!full)
			{
				minimalSerializableItemInfo = new MinimalSerializableItemInfo
				{
					ItemId = base.ItemId,
					LocationId = base.LocationId,
					PlayerSlot = base.PlayerSlot,
					Flags = base.Flags
				};
				if (IsScout)
				{
					minimalSerializableItemInfo.ItemGame = base.ItemGame;
				}
				else
				{
					minimalSerializableItemInfo.LocationGame = base.LocationGame;
				}
			}
			JsonSerializerSettings val = new JsonSerializerSettings
			{
				NullValueHandling = (NullValueHandling)1,
				Formatting = (Formatting)0
			};
			return JsonConvert.SerializeObject((object)minimalSerializableItemInfo, val);
		}

		public static SerializableItemInfo FromJson(string json, IArchipelagoSession session = null)
		{
			//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_0050: Expected O, but got Unknown
			ItemInfoStreamingContext additional = ((session != null) ? new ItemInfoStreamingContext
			{
				Items = session.Items,
				Locations = session.Locations,
				PlayerHelper = session.Players,
				ConnectionInfo = session.ConnectionInfo
			} : null);
			JsonSerializerSettings val = new JsonSerializerSettings
			{
				Context = new StreamingContext(StreamingContextStates.Other, additional)
			};
			return JsonConvert.DeserializeObject<SerializableItemInfo>(json, val);
		}

		[OnDeserialized]
		internal void OnDeserializedMethod(StreamingContext streamingContext)
		{
			if (base.ItemGame == null && base.LocationGame != null)
			{
				IsScout = false;
			}
			else if (base.ItemGame != null && base.LocationGame == null)
			{
				IsScout = true;
			}
			if (streamingContext.Context is ItemInfoStreamingContext itemInfoStreamingContext)
			{
				if (IsScout && base.LocationGame == null)
				{
					base.LocationGame = itemInfoStreamingContext.ConnectionInfo.Game;
				}
				else if (!IsScout && base.ItemGame == null)
				{
					base.ItemGame = itemInfoStreamingContext.ConnectionInfo.Game;
				}
				if (ItemName == null)
				{
					ItemName = itemInfoStreamingContext.Items.GetItemName(base.ItemId, base.ItemGame);
				}
				if (LocationName == null)
				{
					LocationName = itemInfoStreamingContext.Locations.GetLocationNameFromId(base.LocationId, base.LocationGame);
				}
				if (Player == null)
				{
					Player = itemInfoStreamingContext.PlayerHelper.GetPlayerInfo(base.PlayerSlot);
				}
			}
		}
	}
	internal class ItemInfoStreamingContext
	{
		public IReceivedItemsHelper Items { get; set; }

		public ILocationCheckHelper Locations { get; set; }

		public IPlayerHelper PlayerHelper { get; set; }

		public IConnectionInfoProvider ConnectionInfo { get; set; }
	}
}
namespace Archipelago.MultiClient.Net.MessageLog.Parts
{
	public class EntranceMessagePart : MessagePart
	{
		internal EntranceMessagePart(JsonMessagePart messagePart)
			: base(MessagePartType.Entrance, messagePart, Archipelago.MultiClient.Net.Colors.PaletteColor.Blue)
		{
			base.Text = messagePart.Text;
		}
	}
	public class HintStatusMessagePart : MessagePart
	{
		internal HintStatusMessagePart(JsonMessagePart messagePart)
			: base(MessagePartType.HintStatus, messagePart)
		{
			base.Text = messagePart.Text;
			if (messagePart.HintStatus.HasValue)
			{
				base.PaletteColor = ColorUtils.GetColor(messagePart.HintStatus.Value);
			}
		}
	}
	public class ItemMessagePart : MessagePart
	{
		public ItemFlags Flags { get; }

		public long ItemId { get; }

		public int Player { get; }

		internal ItemMessagePart(IPlayerHelper players, IItemInfoResolver items, JsonMessagePart part)
			: base(MessagePartType.Item, part)
		{
			Flags = part.Flags.GetValueOrDefault();
			base.PaletteColor = ColorUtils.GetColor(Flags);
			Player = part.Player.GetValueOrDefault();
			string game = (players.GetPlayerInfo(Player) ?? new PlayerInfo()).Game;
			JsonMessagePartType? type = part.Type;
			if (type.HasValue)
			{
				switch (type.GetValueOrDefault())
				{
				case JsonMessagePartType.ItemId:
					ItemId = long.Parse(part.Text);
					base.Text = items.GetItemName(ItemId, game) ?? $"Item: {ItemId}";
					break;
				case JsonMessagePartType.ItemName:
					ItemId = 0L;
					base.Text = part.Text;
					break;
				}
			}
		}
	}
	public class LocationMessagePart : MessagePart
	{
		public long LocationId { get; }

		public int Player { get; }

		internal LocationMessagePart(IPlayerHelper players, IItemInfoResolver itemInfoResolver, JsonMessagePart part)
			: base(MessagePartType.Location, part, Archipelago.MultiClient.Net.Colors.PaletteColor.Green)
		{
			Player = part.Player.GetValueOrDefault();
			string game = (players.GetPlayerInfo(Player) ?? new PlayerInfo()).Game;
			JsonMessagePartType? type = part.Type;
			if (type.HasValue)
			{
				switch (type.GetValueOrDefault())
				{
				case JsonMessagePartType.LocationId:
					LocationId = long.Parse(part.Text);
					base.Text = itemInfoResolver.GetLocationName(LocationId, game) ?? $"Location: {LocationId}";
					break;
				case JsonMessagePartType.LocationName:
					LocationId = itemInfoResolver.GetLocationId(part.Text, game);
					base.Text = part.Text;
					break;
				}
			}
		}
	}
	public class MessagePart
	{
		public string Text { get; internal set; }

		public MessagePartType Type { get; internal set; }

		public Color Color => GetColor(BuiltInPalettes.Dark);

		public PaletteColor? PaletteColor { get; protected set; }

		public bool IsBackgroundColor { get; internal set; }

		internal MessagePart(MessagePartType type, JsonMessagePart messagePart, PaletteColor? color = null)
		{
			Type = type;
			Text = messagePart.Text;
			if (color.HasValue)
			{
				PaletteColor = color.Value;
			}
			else if (messagePart.Color.HasValue)
			{
				PaletteColor = ColorUtils.GetColor(messagePart.Color.Value);
				IsBackgroundColor = messagePart.Color.Value >= JsonMessagePartColor.BlackBg;
			}
			else
			{
				PaletteColor = null;
			}
		}

		public T GetColor<T>(Palette<T> palette)
		{
			return palette[PaletteColor];
		}

		public override string ToString()
		{
			return Text;
		}
	}
	public enum MessagePartType
	{
		Text,
		Player,
		Item,
		Location,
		Entrance,
		HintStatus
	}
	public class PlayerMessagePart : MessagePart
	{
		public bool IsActivePlayer { get; }

		public int SlotId { get; }

		internal PlayerMessagePart(IPlayerHelper players, IConnectionInfoProvider connectionInfo, JsonMessagePart part)
			: base(MessagePartType.Player, part)
		{
			switch (part.Type)
			{
			case JsonMessagePartType.PlayerId:
				SlotId = int.Parse(part.Text);
				IsActivePlayer = SlotId == connectionInfo.Slot;
				base.Text = players.GetPlayerAlias(SlotId) ?? $"Player {SlotId}";
				break;
			case JsonMessagePartType.PlayerName:
				SlotId = 0;
				IsActivePlayer = false;
				base.Text = part.Text;
				break;
			}
			base.PaletteColor = (IsActivePlayer ? Archipelago.MultiClient.Net.Colors.PaletteColor.Magenta : Archipelago.MultiClient.Net.Colors.PaletteColor.Yellow);
		}
	}
}
namespace Archipelago.MultiClient.Net.MessageLog.Messages
{
	public class AdminCommandResultLogMessage : LogMessage
	{
		internal AdminCommandResultLogMessage(MessagePart[] parts)
			: base(parts)
		{
		}
	}
	public class ChatLogMessage : PlayerSpecificLogMessage
	{
		public string Message { get; }

		internal ChatLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, string message)
			: base(parts, players, team, slot)
		{
			Message = message;
		}
	}
	public class CollectLogMessage : PlayerSpecificLogMessage
	{
		internal CollectLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot)
			: base(parts, players, team, slot)
		{
		}
	}
	public class CommandResultLogMessage : LogMessage
	{
		internal CommandResultLogMessage(MessagePart[] parts)
			: base(parts)
		{
		}
	}
	public class CountdownLogMessage : LogMessage
	{
		public int RemainingSeconds { get; }

		internal CountdownLogMessage(MessagePart[] parts, int remainingSeconds)
			: base(parts)
		{
			RemainingSeconds = remainingSeconds;
		}
	}
	public class GoalLogMessage : PlayerSpecificLogMessage
	{
		internal GoalLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot)
			: base(parts, players, team, slot)
		{
		}
	}
	public class HintItemSendLogMessage : ItemSendLogMessage
	{
		public bool IsFound { get; }

		internal HintItemSendLogMessage(MessagePart[] parts, IPlayerHelper players, int receiver, int sender, NetworkItem item, bool found, IItemInfoResolver itemInfoResolver)
			: base(parts, players, receiver, sender, item, itemInfoResolver)
		{
			IsFound = found;
		}
	}
	public class ItemCheatLogMessage : ItemSendLogMessage
	{
		internal ItemCheatLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, NetworkItem item, IItemInfoResolver itemInfoResolver)
			: base(parts, players, slot, 0, item, team, itemInfoResolver)
		{
		}
	}
	public class ItemSendLogMessage : LogMessage
	{
		private PlayerInfo ActivePlayer { get; }

		public PlayerInfo Receiver { get; }

		public PlayerInfo Sender { get; }

		public bool IsReceiverTheActivePlayer => Receiver == ActivePlayer;

		public bool IsSenderTheActivePlayer => Sender == ActivePlayer;

		public bool IsRelatedToActivePlayer
		{
			get
			{
				if (!ActivePlayer.IsRelatedTo(Receiver))
				{
					return ActivePlayer.IsRelatedTo(Sender);
				}
				return true;
			}
		}

		public ItemInfo Item { get; }

		internal ItemSendLogMessage(MessagePart[] parts, IPlayerHelper players, int receiver, int sender, NetworkItem item, IItemInfoResolver itemInfoResolver)
			: this(parts, players, receiver, sender, item, players.ActivePlayer.Team, itemInfoResolver)
		{
		}

		internal ItemSendLogMessage(MessagePart[] parts, IPlayerHelper players, int receiver, int sender, NetworkItem item, int team, IItemInfoResolver itemInfoResolver)
			: base(parts)
		{
			ActivePlayer = players.ActivePlayer ?? new PlayerInfo();
			Receiver = players.GetPlayerInfo(team, receiver) ?? new PlayerInfo();
			Sender = players.GetPlayerInfo(team, sender) ?? new PlayerInfo();
			PlayerInfo player = players.GetPlayerInfo(team, item.Player) ?? new PlayerInfo();
			Item = new ItemInfo(item, Receiver.Game, Sender.Game, itemInfoResolver, player);
		}
	}
	public class JoinLogMessage : PlayerSpecificLogMessage
	{
		public string[] Tags { get; }

		internal JoinLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, string[] tags)
			: base(parts, players, team, slot)
		{
			Tags = tags;
		}
	}
	public class LeaveLogMessage : PlayerSpecificLogMessage
	{
		internal LeaveLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot)
			: base(parts, players, team, slot)
		{
		}
	}
	public class LogMessage
	{
		public MessagePart[] Parts { get; }

		internal LogMessage(MessagePart[] parts)
		{
			Parts = parts;
		}

		public override string ToString()
		{
			if (Parts.Length == 1)
			{
				return Parts[0].Text;
			}
			StringBuilder stringBuilder = new StringBuilder();
			MessagePart[] parts = Parts;
			foreach (MessagePart messagePart in parts)
			{
				stringBuilder.Append(messagePart.Text);
			}
			return stringBuilder.ToString();
		}
	}
	public abstract class PlayerSpecificLogMessage : LogMessage
	{
		private PlayerInfo ActivePlayer { get; }

		public PlayerInfo Player { get; }

		public bool IsActivePlayer => Player == ActivePlayer;

		public bool IsRelatedToActivePlayer => ActivePlayer.IsRelatedTo(Player);

		internal PlayerSpecificLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot)
			: base(parts)
		{
			ActivePlayer = players.ActivePlayer ?? new PlayerInfo();
			Player = players.GetPlayerInfo(team, slot) ?? new PlayerInfo();
		}
	}
	public class ReleaseLogMessage : PlayerSpecificLogMessage
	{
		internal ReleaseLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot)
			: base(parts, players, team, slot)
		{
		}
	}
	public class ServerChatLogMessage : LogMessage
	{
		public string Message { get; }

		internal ServerChatLogMessage(MessagePart[] parts, string message)
			: base(parts)
		{
			Message = message;
		}
	}
	public class TagsChangedLogMessage : PlayerSpecificLogMessage
	{
		public string[] Tags { get; }

		internal TagsChangedLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, string[] tags)
			: base(parts, players, team, slot)
		{
			Tags = tags;
		}
	}
	public class TutorialLogMessage : LogMessage
	{
		internal TutorialLogMessage(MessagePart[] parts)
			: base(parts)
		{
		}
	}
}
namespace Archipelago.MultiClient.Net.Helpers
{
	public class ArchipelagoSocketHelper : BaseArchipelagoSocketHelper<ClientWebSocket>, IArchipelagoSocketHelper
	{
		public Uri Uri { get; }

		internal ArchipelagoSocketHelper(Uri hostUri)
			: base(CreateWebSocket(), 1024)
		{
			Uri = hostUri;
		}

		private static ClientWebSocket CreateWebSocket()
		{
			return new ClientWebSocket();
		}

		public async Task ConnectAsync()
		{
			await ConnectToProvidedUri(Uri);
			StartPolling();
		}

		private async Task ConnectToProvidedUri(Uri uri)
		{
			if (uri.Scheme != "unspecified")
			{
				try
				{
					await Socket.ConnectAsync(uri, CancellationToken.None);
					return;
				}
				catch (Exception e)
				{
					OnError(e);
					throw;
				}
			}
			List<Exception> errors = new List<Exception>(0);
			try
			{
				await Socket.ConnectAsync(uri.AsWss(), CancellationToken.None);
				if (Socket.State == WebSocketState.Open)
				{
					return;
				}
			}
			catch (Exception item)
			{
				errors.Add(item);
				Socket = CreateWebSocket();
			}
			try
			{
				await Socket.ConnectAsync(uri.AsWs(), CancellationToken.None);
			}
			catch (Exception item2)
			{
				errors.Add(item2);
				OnError(new AggregateException(errors));
				throw;
			}
		}
	}
	public class BaseArchipelagoSocketHelper<T> where T : WebSocket
	{
		private static readonly ArchipelagoPacketConverter Converter = new ArchipelagoPacketConverter();

		private readonly BlockingCollection<Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>>> sendQueue = new BlockingCollection<Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>>>();

		internal T Socket;

		private readonly int bufferSize;

		public bool Connected
		{
			get
			{
				if (Socket.State != WebSocketState.Open)
				{
					return Socket.State == WebSocketState.CloseReceived;
				}
				return true;
			}
		}

		public event ArchipelagoSocketHelperDelagates.PacketReceivedHandler PacketReceived;

		public event ArchipelagoSocketHelperDelagates.PacketsSentHandler PacketsSent;

		public event ArchipelagoSocketHelperDelagates.ErrorReceivedHandler ErrorReceived;

		public event ArchipelagoSocketHelperDelagates.SocketClosedHandler SocketClosed;

		public event ArchipelagoSocketHelperDelagates.SocketOpenedHandler SocketOpened;

		internal BaseArchipelagoSocketHelper(T socket, int bufferSize = 1024)
		{
			Socket = socket;
			this.bufferSize = bufferSize;
		}

		internal void StartPolling()
		{
			if (this.SocketOpened != null)
			{
				this.SocketOpened();
			}
			Task.Run((Func<Task?>)PollingLoop);
			Task.Run((Func<Task?>)SendLoop);
		}

		private async Task PollingLoop()
		{
			byte[] buffer = new byte[bufferSize];
			while (Socket.State == WebSocketState.Open)
			{
				string message = null;
				try
				{
					message = await ReadMessageAsync(buffer);
				}
				catch (Exception e)
				{
					OnError(e);
				}
				OnMessageReceived(message);
			}
		}

		private async Task SendLoop()
		{
			while (Socket.State == WebSocketState.Open)
			{
				try
				{
					await HandleSendBuffer();
				}
				catch (Exception e)
				{
					OnError(e);
				}
				await Task.Delay(20);
			}
		}

		private async Task<string> ReadMessageAsync(byte[] buffer)
		{
			using MemoryStream readStream = new MemoryStream(buffer.Length);
			WebSocketReceiveResult result;
			do
			{
				result = await Socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
				if (result.MessageType == WebSocketMessageType.Close)
				{
					try
					{
						await Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
					}
					catch
					{
					}
					OnSocketClosed();
				}
				else
				{
					readStream.Write(buffer, 0, result.Count);
				}
			}
			while (!result.EndOfMessage);
			return Encoding.UTF8.GetString(readStream.ToArray());
		}

		public async Task DisconnectAsync()
		{
			await Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closure requested by client", CancellationToken.None);
			OnSocketClosed();
		}

		public void SendPacket(ArchipelagoPacketBase packet)
		{
			SendMultiplePackets(new List<ArchipelagoPacketBase> { packet });
		}

		public void SendMultiplePackets(List<ArchipelagoPacketBase> packets)
		{
			SendMultiplePackets(packets.ToArray());
		}

		public void SendMultiplePackets(params ArchipelagoPacketBase[] packets)
		{
			SendMultiplePacketsAsync(packets).Wait();
		}

		public Task SendPacketAsync(ArchipelagoPacketBase packet)
		{
			return SendMultiplePacketsAsync(new List<ArchipelagoPacketBase> { packet });
		}

		public Task SendMultiplePacketsAsync(List<ArchipelagoPacketBase> packets)
		{
			return SendMultiplePacketsAsync(packets.ToArray());
		}

		public Task SendMultiplePacketsAsync(params ArchipelagoPacketBase[] packets)
		{
			TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
			foreach (ArchipelagoPacketBase item in packets)
			{
				sendQueue.Add(new Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>>(item, taskCompletionSource));
			}
			return taskCompletionSource.Task;
		}

		private async Task HandleSendBuffer()
		{
			List<ArchipelagoPacketBase> list = new List<ArchipelagoPacketBase>();
			List<TaskCompletionSource<bool>> tasks = new List<TaskCompletionSource<bool>>();
			Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>> tuple = sendQueue.Take();
			list.Add(tuple.Item1);
			tasks.Add(tuple.Item2);
			Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>> item;
			while (sendQueue.TryTake(out item))
			{
				list.Add(item.Item1);
				tasks.Add(item.Item2);
			}
			if (!list.Any())
			{
				return;
			}
			if (Socket.State != WebSocketState.Open)
			{
				throw new ArchipelagoSocketClosedException();
			}
			ArchipelagoPacketBase[] packets = list.ToArray();
			string s = JsonConvert.SerializeObject((object)packets);
			byte[] messageBuffer = Encoding.UTF8.GetBytes(s);
			int messagesCount = (int)Math.Ceiling((double)messageBuffer.Length / (double)bufferSize);
			for (int i = 0; i < messagesCount; i++)
			{
				int num = bufferSize * i;
				int num2 = bufferSize;
				bool endOfMessage = i + 1 == messagesCount;
				if (num2 * (i + 1) > messageBuffer.Length)
				{
					num2 = messageBuffer.Length - num;
				}
				await Socket.SendAsync(new ArraySegment<byte>(messageBuffer, num, num2), WebSocketMessageType.Text, endOfMessage, CancellationToken.None);
			}
			foreach (TaskCompletionSource<bool> item2 in tasks)
			{
				item2.TrySetResult(result: true);
			}
			OnPacketSend(packets);
		}

		private void OnPacketSend(ArchipelagoPacketBase[] packets)
		{
			try
			{
				if (this.PacketsSent != null)
				{
					this.PacketsSent(packets);
				}
			}
			catch (Exception e)
			{
				OnError(e);
			}
		}

		private void OnSocketClosed()
		{
			try
			{
				if (this.SocketClosed != null)
				{
					this.SocketClosed("");
				}
			}
			catch (Exception e)
			{
				OnError(e);
			}
		}

		private void OnMessageReceived(string message)
		{
			try
			{
				if (string.IsNullOrEmpty(message) || this.PacketReceived == null)
				{
					return;
				}
				List<ArchipelagoPacketBase> list = null;
				try
				{
					list = JsonConvert.DeserializeObject<List<ArchipelagoPacketBase>>(message, (JsonConverter[])(object)new JsonConverter[1] { Converter });
				}
				catch (Exception e)
				{
					OnError(e);
				}
				if (list == null)
				{
					return;
				}
				foreach (ArchipelagoPacketBase item in list)
				{
					this.PacketReceived(item);
				}
			}
			catch (Exception e2)
			{
				OnError(e2);
			}
		}

		protected void OnError(Exception e)
		{
			try
			{
				if (this.ErrorReceived != null)
				{
					this.ErrorReceived(e, e.Message);
				}
			}
			catch (Exception ex)
			{
				Console.Out.WriteLine("Error occured during reporting of errorOuter Errror: " + e.Message + " " + e.StackTrace + "Inner Errror: " + ex.Message + " " + ex.StackTrace);
			}
		}
	}
	public interface IConnectionInfoProvider
	{
		string Game { get; }

		int Team { get; }

		int Slot { get; }

		string[] Tags { get; }

		ItemsHandlingFlags ItemsHandlingFlags { get; }

		string Uuid { get; }

		void UpdateConnectionOptions(string[] tags);

		void UpdateConnectionOptions(ItemsHandlingFlags itemsHandlingFlags);

		void UpdateConnectionOptions(string[] tags, ItemsHandlingFlags itemsHandlingFlags);
	}
	public class ConnectionInfoHelper : IConnectionInfoProvider
	{
		private readonly IArchipelagoSocketHelper socket;

		public string Game { get; private set; }

		public int Team { get; private set; }

		public int Slot { get; private set; }

		public string[] Tags { get; internal set; }

		public ItemsHandlingFlags ItemsHandlingFlags { get; internal set; }

		public string Uuid { get; private set; }

		internal ConnectionInfoHelper(IArchipelagoSocketHelper socket)
		{
			this.socket = socket;
			Reset();
			socket.PacketReceived += PacketReceived;
		}

		private void PacketReceived(ArchipelagoPacketBase packet)
		{
			if (!(packet is ConnectedPacket connectedPacket))
			{
				if (packet is ConnectionRefusedPacket)
				{
					Reset();
				}
				return;
			}
			Team = connectedPacket.Team;
			Slot = connectedPacket.Slot;
			if (connectedPacket.SlotInfo != null && connectedPacket.SlotInfo.ContainsKey(Slot))
			{
				Game = connectedPacket.SlotInfo[Slot].Game;
			}
		}

		internal void SetConnectionParameters(string game, string[] tags, ItemsHandlingFlags itemsHandlingFlags, string uuid)
		{
			Game = game;
			Tags = tags ?? new string[0];
			ItemsHandlingFlags = itemsHandlingFlags;
			Uuid = uuid ?? Guid.NewGuid().ToString();
		}

		private void Reset()
		{
			Game = null;
			Team = -1;
			Slot = -1;
			Tags = new string[0];
			ItemsHandlingFlags = ItemsHandlingFlags.NoItems;
			Uuid = null;
		}

		public void UpdateConnectionOptions(string[] tags)
		{
			UpdateConnectionOptions(tags, ItemsHandlingFlags);
		}

		public void UpdateConnectionOptions(ItemsHandlingFlags itemsHandlingFlags)
		{
			UpdateConnectionOptions(Tags, ItemsHandlingFlags);
		}

		public void UpdateConnectionOptions(string[] tags, ItemsHandlingFlags itemsHandlingFlags)
		{
			SetConnectionParameters(Game, tags, itemsHandlingFlags, Uuid);
			socket.SendPacket(new ConnectUpdatePacket
			{
				Tags = Tags,
				ItemsHandling = ItemsHandlingFlags
			});
		}
	}
	public interface IDataStorageHelper : IDataStorageWrapper
	{
		DataStorageElement this[Scope scope, string key] { get; set; }

		DataStorageElement this[string key] { get; set; }
	}
	public class DataStorageHelper : IDataStorageHelper, IDataStorageWrapper
	{
		public delegate void DataStorageUpdatedHandler(JToken originalValue, JToken newValue, Dictionary<string, JToken> additionalArguments);

		private readonly Dictionary<string, DataStorageUpdatedHandler> onValueChangedEventHandlers = new Dictionary<string, DataStorageUpdatedHandler>();

		private readonly Dictionary<Guid, DataStorageUpdatedHandler> operationSpecificCallbacks = new Dictionary<Guid, DataStorageUpdatedHandler>();

		private readonly Dictionary<string, TaskCompletionSource<JToken>> asyncRetrievalTasks = new Dictionary<string, TaskCompletionSource<JToken>>();

		private readonly IArchipelagoSocketHelper socket;

		private readonly IConnectionInfoProvider connectionInfoProvider;

		public DataStorageElement this[Scope scope, string key]
		{
			get
			{
				return this[AddScope(scope, key)];
			}
			set
			{
				this[AddScope(scope, key)] = value;
			}
		}

		public DataStorageElement this[string key]
		{
			get
			{
				return new DataStorageElement(GetContextForKey(key));
			}
			set
			{
				SetValue(key, value);
			}
		}

		internal DataStorageHelper(IArchipelagoSocketHelper socket, IConnectionInfoProvider connectionInfoProvider)
		{
			this.socket = socket;
			this.connectionInfoProvider = connectionInfoProvider;
			socket.PacketReceived += OnPacketReceived;
		}

		private void OnPacketReceived(ArchipelagoPacketBase packet)
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Invalid comparison between Unknown and I4
			if (!(packet is RetrievedPacket retrievedPacket))
			{
				if (packet is SetReplyPacket setReplyPacket)
				{
					if (setReplyPacket.AdditionalArguments != null && setReplyPacket.AdditionalArguments.ContainsKey("Reference") && (int)setReplyPacket.AdditionalArguments["Reference"].Type == 8 && ((string)setReplyPacket.AdditionalArguments["Reference"]).TryParseNGuid(out var g) && operationSpecificCallbacks.TryGetValue(g, out var value))
					{
						value(setReplyPacket.OriginalValue, setReplyPacket.Value, setReplyPacket.AdditionalArguments);
						operationSpecificCallbacks.Remove(g);
					}
					if (onValueChangedEventHandlers.TryGetValue(setReplyPacket.Key, out var value2))
					{
						value2(setReplyPacket.OriginalValue, setReplyPacket.Value, setReplyPacket.AdditionalArguments);
					}
				}
				return;
			}
			foreach (KeyValuePair<string, JToken> datum in retrievedPacket.Data)
			{
				if (asyncRetrievalTasks.TryGetValue(datum.Key, out var value3))
				{
					value3.TrySetResult(datum.Value);
					asyncRetrievalTasks.Remove(datum.Key);
				}
			}
		}

		private Task<JToken> GetAsync(string key)
		{
			if (asyncRetrievalTasks.TryGetValue(key, out var value))
			{
				return value.Task;
			}
			TaskCompletionSource<JToken> taskCompletionSource = new TaskCompletionSource<JToken>();
			asyncRetrievalTasks[key] = taskCompletionSource;
			socket.SendPacketAsync(new GetPacket
			{
				Keys = new string[1] { key }
			});
			return taskCompletionSource.Task;
		}

		private void Initialize(string key, JToken value)
		{
			socket.SendPacketAsync(new SetPacket
			{
				Key = key,
				DefaultValue = value,
				Operations = new OperationSpecification[1]
				{
					new OperationSpecification
					{
						OperationType = OperationType.Default
					}
				}
			});
		}

		private JToken GetValue(string key)
		{
			Task<JToken> async = GetAsync(key);
			if (!async.Wait(TimeSpan.FromSeconds(2.0)))
			{
				throw new TimeoutException("Timed out retrieving data for key `" + key + "`. This may be due to an attempt to retrieve a value from the DataStorageHelper in a synchronous fashion from within a PacketReceived handler. When using the DataStorageHelper from within code which runs on the websocket thread then use the asynchronous getters. Ex: `DataStorageHelper[\"" + key + "\"].GetAsync().ContinueWith(x => {});`Be aware that DataStorageHelper calls tend to cause packet responses, so making a call from within a PacketReceived handler may cause an infinite loop.");
			}
			return async.Result;
		}

		private void SetValue(string key, DataStorageElement e)
		{
			if (key.StartsWith("_read_"))
			{
				throw new InvalidOperationException("DataStorage write operation on readonly key '" + key + "' is not allowed");
			}
			if (e == null)
			{
				e = new DataStorageElement(OperationType.Replace, (JToken)(object)JValue.CreateNull());
			}
			if (e.Context == null)
			{
				e.Context = GetContextForKey(key);
			}
			else if (e.Context.Key != key)
			{
				e.Operations.Insert(0, new OperationSpecification
				{
					OperationType = OperationType.Replace,
					Value = GetValue(e.Context.Key)
				});
			}
			Dictionary<string, JToken> dictionary = e.AdditionalArguments ?? new Dictionary<string, JToken>(0);
			if (e.Callbacks != null)
			{
				Guid key2 = Guid.NewGuid();
				operationSpecificCallbacks[key2] = e.Callbacks;
				dictionary["Reference"] = JToken.op_Implicit(key2.ToString("N"));
				socket.SendPacketAsync(new SetPacket
				{
					Key = key,
					Operations = e.Operations.ToArray(),
					WantReply = true,
					AdditionalArguments = dictionary
				});
			}
			else
			{
				socket.SendPacketAsync(new SetPacket
				{
					Key = key,
					Operations = e.Operations.ToArray(),
					AdditionalArguments = dictionary
				});
			}
		}

		private DataStorageElementContext GetContextForKey(string key)
		{
			return new DataStorageElementContext
			{
				Key = key,
				GetData = GetValue,
				GetAsync = GetAsync,
				Initialize = Initialize,
				AddHandler = AddHandler,
				RemoveHandler = RemoveHandler
			};
		}

		private void AddHandler(string key, DataStorageUpdatedHandler handler)
		{
			if (onValueChangedEventHandlers.ContainsKey(key))
			{
				Dictionary<string, DataStorageUpdatedHandler> dictionary = onValueChangedEventHandlers;
				dictionary[key] = (DataStorageUpdatedHandler)Delegate.Combine(dictionary[key], handler);
			}
			else
			{
				onValueChangedEventHandlers[key] = handler;
			}
			socket.SendPacketAsync(new SetNotifyPacket
			{
				Keys = new string[1] { key }
			});
		}

		private void RemoveHandler(string key, DataStorageUpdatedHandler handler)
		{
			if (onValueChangedEventHandlers.ContainsKey(key))
			{
				Dictionary<string, DataStorageUpdatedHandler> dictionary = onValueChangedEventHandlers;
				dictionary[key] = (DataStorageUpdatedHandler)Delegate.Remove(dictionary[key], handler);
				if (onValueChangedEventHandlers[key] == null)
				{
					onValueChangedEventHandlers.Remove(key);
				}
			}
		}

		private string AddScope(Scope scope, string key)
		{
			return scope switch
			{
				Scope.Global => key, 
				Scope.Game => $"{scope}:{connectionInfoProvider.Game}:{key}", 
				Scope.Team => $"{scope}:{connectionInfoProvider.Team}:{key}", 
				Scope.Slot => $"{scope}:{connectionInfoProvider.Slot}:{key}", 
				Scope.ReadOnly => "_read_" + key, 
				_ => throw new ArgumentOutOfRangeException("scope", scope, "Invalid scope for key " + key), 
			};
		}

		private DataStorageElement GetHintsElement(int? slot = null, int? team = null)
		{
			return this[Scope.ReadOnly, $"hints_{team ?? connectionInfoProvider.Team}_{slot ?? connectionInfoProvider.Slot}"];
		}

		private DataStorageElement GetSlotDataElement(int? slot = null)
		{
			return this[Scope.ReadOnly, $"slot_data_{slot ?? connectionInfoProvider.Slot}"];
		}

		private DataStorageElement GetItemNameGroupsElement(string game = null)
		{
			return this[Scope.ReadOnly, "item_name_groups_" + (game ?? connectionInfoProvider.Game)];
		}

		private DataStorageElement GetLocationNameGroupsElement(string game = null)
		{
			return this[Scope.ReadOnly, "location_name_groups_" + (game ?? connectionInfoProvider.Game)];
		}

		private DataStorageElement GetClientStatusElement(int? slot = null, int? team = null)
		{
			return this[Scope.ReadOnly, $"client_status_{team ?? connectionInfoProvider.Team}_{slot ?? connectionInfoProvider.Slot}"];
		}

		private DataStorageElement GetRaceModeElement()
		{
			return this[Scope.ReadOnly, "race_mode"];
		}

		public Hint[] GetHints(int? slot = null, int? team = null)
		{
			return GetHintsElement(slot, team).To<Hint[]>();
		}

		public Task<Hint[]> GetHintsAsync(int? slot = null, int? team = null)
		{
			return GetHintsElement(slot, team).GetAsync<Hint[]>();
		}

		public void TrackHints(Action<Hint[]> onHintsUpdated, bool retrieveCurrentlyUnlockedHints = true, int? slot = null, int? team = null)
		{
			GetHintsElement(slot, team).OnValueChanged += delegate(JToken _, JToken newValue, Dictionary<string, JToken> x)
			{
				onHintsUpdated(newValue.ToObject<Hint[]>());
			};
			if (retrieveCurrentlyUnlockedHints)
			{
				GetHintsAsync(slot, team).ContinueWith(delegate(Task<Hint[]> t)
				{
					onHintsUpdated(t.Result);
				});
			}
		}

		public Dictionary<string, object> GetSlotData(int? slot = null)
		{
			return GetSlotData<Dictionary<string, object>>(slot);
		}

		public T GetSlotData<T>(int? slot = null) where T : class
		{
			return GetSlotDataElement(slot).To<T>();
		}

		public Task<Dictionary<string, object>> GetSlotDataAsync(int? slot = null)
		{
			return GetSlotDataAsync<Dictionary<string, object>>(slot);
		}

		public Task<T> GetSlotDataAsync<T>(int? slot = null) where T : class
		{
			return GetSlotDataElement(slot).GetAsync<T>();
		}

		public Dictionary<string, string[]> GetItemNameGroups(string game = null)
		{
			return GetItemNameGroupsElement(game).To<Dictionary<string, string[]>>();
		}

		public Task<Dictionary<string, string[]>> GetItemNameGroupsAsync(string game = null)
		{
			return GetItemNameGroupsElement(game).GetAsync<Dictionary<string, string[]>>();
		}

		public Dictionary<string, string[]> GetLocationNameGroups(string game = null)
		{
			return GetLocationNameGroupsElement(game).To<Dictionary<string, string[]>>();
		}

		public Task<Dictionary<string, string[]>> GetLocationNameGroupsAsync(string game = null)
		{
			return GetLocationNameGroupsElement(game).GetAsync<Dictionary<string, string[]>>();
		}

		public ArchipelagoClientState GetClientStatus(int? slot = null, int? team = null)
		{
			return GetClientStatusElement(slot, team).To<ArchipelagoClientState?>().GetValueOrDefault();
		}

		public Task<ArchipelagoClientState> GetClientStatusAsync(int? slot = null, int? team = null)
		{
			return GetClientStatusElement(slot, team).GetAsync<ArchipelagoClientState?>().ContinueWith((Task<ArchipelagoClientState?> r) => r.Result.GetValueOrDefault());
		}

		public void TrackClientStatus(Action<ArchipelagoClientState> onStatusUpdated, bool retrieveCurrentClientStatus = true, int? slot = null, int? team = null)
		{
			GetClientStatusElement(slot, team).OnValueChanged += delegate(JToken _, JToken newValue, Dictionary<string, JToken> x)
			{
				onStatusUpdated(newValue.ToObject<ArchipelagoClientState>());
	

Smushi_Archipelago\MonoMod.Backports.dll

Decompiled 3 days ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("0x0ade, DaNike")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright 2024 0x0ade, DaNike")]
[assembly: AssemblyDescription("A set of backports of new BCL features to all frameworks which MonoMod supports.")]
[assembly: AssemblyFileVersion("1.1.2.0")]
[assembly: AssemblyInformationalVersion("1.1.2+a1b82852b")]
[assembly: AssemblyProduct("MonoMod.Backports")]
[assembly: AssemblyTitle("MonoMod.Backports")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/MonoMod/MonoMod.git")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.2.0")]
[assembly: TypeForwardedTo(typeof(ArrayPool<>))]
[assembly: TypeForwardedTo(typeof(BuffersExtensions))]
[assembly: TypeForwardedTo(typeof(IBufferWriter<>))]
[assembly: TypeForwardedTo(typeof(IMemoryOwner<>))]
[assembly: TypeForwardedTo(typeof(IPinnable))]
[assembly: TypeForwardedTo(typeof(MemoryHandle))]
[assembly: TypeForwardedTo(typeof(MemoryManager<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySequence<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySequenceSegment<>))]
[assembly: TypeForwardedTo(typeof(StandardFormat))]
[assembly: TypeForwardedTo(typeof(ConcurrentBag<>))]
[assembly: TypeForwardedTo(typeof(ConcurrentDictionary<, >))]
[assembly: TypeForwardedTo(typeof(ConcurrentQueue<>))]
[assembly: TypeForwardedTo(typeof(ConcurrentStack<>))]
[assembly: TypeForwardedTo(typeof(EnumerablePartitionerOptions))]
[assembly: TypeForwardedTo(typeof(IProducerConsumerCollection<>))]
[assembly: TypeForwardedTo(typeof(OrderablePartitioner<>))]
[assembly: TypeForwardedTo(typeof(Partitioner))]
[assembly: TypeForwardedTo(typeof(Partitioner<>))]
[assembly: TypeForwardedTo(typeof(IReadOnlyCollection<>))]
[assembly: TypeForwardedTo(typeof(IReadOnlyList<>))]
[assembly: TypeForwardedTo(typeof(IStructuralComparable))]
[assembly: TypeForwardedTo(typeof(IStructuralEquatable))]
[assembly: TypeForwardedTo(typeof(HashCode))]
[assembly: TypeForwardedTo(typeof(Memory<>))]
[assembly: TypeForwardedTo(typeof(MemoryExtensions))]
[assembly: TypeForwardedTo(typeof(ReadOnlyMemory<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySpan<>))]
[assembly: TypeForwardedTo(typeof(IntrospectionExtensions))]
[assembly: TypeForwardedTo(typeof(IReflectableType))]
[assembly: TypeForwardedTo(typeof(TypeDelegator))]
[assembly: TypeForwardedTo(typeof(TypeInfo))]
[assembly: TypeForwardedTo(typeof(CallerFilePathAttribute))]
[assembly: TypeForwardedTo(typeof(CallerLineNumberAttribute))]
[assembly: TypeForwardedTo(typeof(CallerMemberNameAttribute))]
[assembly: TypeForwardedTo(typeof(ConditionalWeakTable<, >))]
[assembly: TypeForwardedTo(typeof(TupleElementNamesAttribute))]
[assembly: TypeForwardedTo(typeof(Unsafe))]
[assembly: TypeForwardedTo(typeof(DefaultDllImportSearchPathsAttribute))]
[assembly: TypeForwardedTo(typeof(DllImportSearchPath))]
[assembly: TypeForwardedTo(typeof(MemoryMarshal))]
[assembly: TypeForwardedTo(typeof(SequenceMarshal))]
[assembly: TypeForwardedTo(typeof(SequencePosition))]
[assembly: TypeForwardedTo(typeof(Span<>))]
[assembly: TypeForwardedTo(typeof(SpinLock))]
[assembly: TypeForwardedTo(typeof(SpinWait))]
[assembly: TypeForwardedTo(typeof(ThreadLocal<>))]
[assembly: TypeForwardedTo(typeof(Volatile))]
[assembly: TypeForwardedTo(typeof(Tuple))]
[assembly: TypeForwardedTo(typeof(Tuple<>))]
[assembly: TypeForwardedTo(typeof(Tuple<, >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , , >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , , , >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , , , , >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , , , , , >))]
[assembly: TypeForwardedTo(typeof(Tuple<, , , , , , , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple))]
[assembly: TypeForwardedTo(typeof(ValueTuple<>))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , , >))]
[assembly: TypeForwardedTo(typeof(ValueTuple<, , , , , , , >))]
[assembly: TypeForwardedTo(typeof(WeakReference<>))]
[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.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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = 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;
		}
	}
}
internal static class AssemblyInfo
{
	public const string AssemblyName = "MonoMod.Backports";

	public const string AssemblyVersion = "1.1.2";
}
namespace MonoMod.SourceGen.Attributes
{
	[AttributeUsage(AttributeTargets.Class)]
	internal sealed class EmitILOverloadsAttribute : Attribute
	{
		public EmitILOverloadsAttribute(string filename, string kind)
		{
		}
	}
	internal static class ILOverloadKind
	{
		public const string Cursor = "ILCursor";

		public const string Matcher = "ILMatcher";
	}
}
namespace MonoMod.Backports
{
	public static class MethodImplOptionsEx
	{
		public const MethodImplOptions Unmanaged = MethodImplOptions.Unmanaged;

		public const MethodImplOptions NoInlining = MethodImplOptions.NoInlining;

		public const MethodImplOptions ForwardRef = MethodImplOptions.ForwardRef;

		public const MethodImplOptions Synchronized = MethodImplOptions.Synchronized;

		public const MethodImplOptions NoOptimization = MethodImplOptions.NoOptimization;

		public const MethodImplOptions PreserveSig = MethodImplOptions.PreserveSig;

		public const MethodImplOptions AggressiveInlining = MethodImplOptions.AggressiveInlining;

		public const MethodImplOptions AggressiveOptimization = MethodImplOptions.AggressiveOptimization;

		public const MethodImplOptions InternalCall = MethodImplOptions.InternalCall;
	}
}
namespace MonoMod.Backports.ILHelpers
{
	[CLSCompliant(false)]
	public static class UnsafeRaw
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static T Read<T>(void* source)
		{
			return Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static T ReadUnaligned<T>(void* source)
		{
			return Unsafe.ReadUnaligned<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static T ReadUnaligned<T>(ref byte source)
		{
			return Unsafe.ReadUnaligned<T>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void Write<T>(void* destination, T value)
		{
			Unsafe.Write(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void WriteUnaligned<T>(void* destination, T value)
		{
			Unsafe.WriteUnaligned(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void WriteUnaligned<T>(ref byte destination, T value)
		{
			Unsafe.WriteUnaligned(ref destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void Copy<T>(void* destination, ref T source)
		{
			Unsafe.Copy(destination, ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void Copy<T>(ref T destination, void* source)
		{
			Unsafe.Copy(ref destination, source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void* AsPointer<T>(ref T value)
		{
			return Unsafe.AsPointer(ref value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void SkipInit<T>(out T value)
		{
			Unsafe.SkipInit<T>(out value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void CopyBlock(void* destination, void* source, uint byteCount)
		{
			Unsafe.CopyBlock(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void CopyBlock(ref byte destination, ref byte source, uint byteCount)
		{
			Unsafe.CopyBlock(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount)
		{
			Unsafe.CopyBlockUnaligned(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount)
		{
			Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount)
		{
			Unsafe.InitBlock(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void InitBlock(ref byte startAddress, byte value, uint byteCount)
		{
			Unsafe.InitBlock(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount)
		{
			Unsafe.InitBlockUnaligned(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
		{
			Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static T As<T>(object o) where T : class
		{
			return Unsafe.As<T>(o);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static ref T AsRef<T>(void* source)
		{
			return ref Unsafe.AsRef<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T AsRef<T>(in T source)
		{
			return ref Unsafe.AsRef(in source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref TTo As<TFrom, TTo>(ref TFrom source)
		{
			return ref Unsafe.As<TFrom, TTo>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Unbox<T>(object box) where T : struct
		{
			return ref Unsafe.Unbox<T>(box);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, nint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, nuint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, nint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, nuint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static nint ByteOffset<T>(ref T origin, ref T target)
		{
			return Unsafe.ByteOffset(ref origin, ref target);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static bool AreSame<T>(ref T left, ref T right)
		{
			return Unsafe.AreSame(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static bool IsAddressGreaterThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressGreaterThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static bool IsAddressLessThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressLessThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static bool IsNullRef<T>(ref T source)
		{
			return Unsafe.IsNullRef(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T NullRef<T>()
		{
			return ref Unsafe.NullRef<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static int SizeOf<T>()
		{
			return Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Add<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void* Add<T>(void* source, int elementOffset)
		{
			return Unsafe.Add<T>(source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Add<T>(ref T source, nint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Add<T>(ref T source, nuint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Subtract<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public unsafe static void* Subtract<T>(void* source, int elementOffset)
		{
			return Unsafe.Subtract<T>(source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Subtract<T>(ref T source, nint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[NonVersionable]
		public static ref T Subtract<T>(ref T source, nuint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}
	}
}
namespace System
{
	public static class ArrayEx
	{
		public static int MaxLength => 1879048191;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static T[] Empty<T>()
		{
			return Array.Empty<T>();
		}
	}
	public static class EnvironmentEx
	{
		public static int CurrentManagedThreadId => Environment.CurrentManagedThreadId;
	}
	public sealed class Gen2GcCallback : CriticalFinalizerObject
	{
		private readonly Func<bool>? _callback0;

		private readonly Func<object, bool>? _callback1;

		private GCHandle _weakTargetObj;

		private Gen2GcCallback(Func<bool> callback)
		{
			_callback0 = callback;
		}

		private Gen2GcCallback(Func<object, bool> callback, object targetObj)
		{
			_callback1 = callback;
			_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak);
		}

		public static void Register(Func<bool> callback)
		{
			new Gen2GcCallback(callback);
		}

		public static void Register(Func<object, bool> callback, object targetObj)
		{
			new Gen2GcCallback(callback, targetObj);
		}

		~Gen2GcCallback()
		{
			if (_weakTargetObj.IsAllocated)
			{
				object target = _weakTargetObj.Target;
				if (target == null)
				{
					_weakTargetObj.Free();
					return;
				}
				try
				{
					if (!_callback1(target))
					{
						_weakTargetObj.Free();
						return;
					}
				}
				catch
				{
				}
			}
			else
			{
				try
				{
					if (!_callback0())
					{
						return;
					}
				}
				catch
				{
				}
			}
			GC.ReRegisterForFinalize(this);
		}
	}
	public static class MathEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static byte Clamp(byte value, byte min, byte max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static decimal Clamp(decimal value, decimal min, decimal max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static double Clamp(double value, double min, double max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static short Clamp(short value, short min, short max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int Clamp(int value, int min, int max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static long Clamp(long value, long min, long max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static nint Clamp(nint value, nint min, nint max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static sbyte Clamp(sbyte value, sbyte min, sbyte max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Clamp(float value, float min, float max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ushort Clamp(ushort value, ushort min, ushort max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint Clamp(uint value, uint min, uint max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong Clamp(ulong value, ulong min, ulong max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static nuint Clamp(nuint value, nuint min, nuint max)
		{
			if (min > max)
			{
				ThrowMinMaxException(min, max);
			}
			if (value < min)
			{
				return min;
			}
			if (value > max)
			{
				return max;
			}
			return value;
		}

		[DoesNotReturn]
		private static void ThrowMinMaxException<T>(T min, T max)
		{
			throw new ArgumentException($"Minimum {min} is less than maximum {max}");
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class NonVersionableAttribute : Attribute
	{
	}
	public static class StringComparerEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static StringComparer FromComparison(StringComparison comparisonType)
		{
			return StringComparer.FromComparison(comparisonType);
		}
	}
	public static class StringExtensions
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison)
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, System.ExceptionArgument.self);
			System.ThrowHelper.ThrowIfArgumentNull(oldValue, System.ExceptionArgument.oldValue);
			System.ThrowHelper.ThrowIfArgumentNull(newValue, System.ExceptionArgument.newValue);
			return self.Replace(oldValue, newValue, comparison);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool Contains(this string self, string value, StringComparison comparison)
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, System.ExceptionArgument.self);
			System.ThrowHelper.ThrowIfArgumentNull(value, System.ExceptionArgument.value);
			return self.Contains(value, comparison);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool Contains(this string self, char value, StringComparison comparison)
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, System.ExceptionArgument.self);
			return self.Contains(value, comparison);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetHashCode(this string self, StringComparison comparison)
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, System.ExceptionArgument.self);
			return self.GetHashCode(comparison);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int IndexOf(this string self, char value, StringComparison comparison)
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, System.ExceptionArgument.self);
			return self.IndexOf(value, comparison);
		}
	}
	internal static class ThrowHelper
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static void ThrowIfArgumentNull([NotNull] object? obj, System.ExceptionArgument argument)
		{
			if (obj == null)
			{
				ThrowArgumentNullException(argument);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static void ThrowIfArgumentNull([NotNull] object? obj, string argument, string? message = null)
		{
			if (obj == null)
			{
				ThrowArgumentNullException(argument, message);
			}
		}

		[DoesNotReturn]
		internal static void ThrowArgumentNullException(System.ExceptionArgument argument)
		{
			throw CreateArgumentNullException(argument);
		}

		[DoesNotReturn]
		internal static void ThrowArgumentNullException(string argument, string? message = null)
		{
			throw CreateArgumentNullException(argument, message);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentNullException(System.ExceptionArgument argument)
		{
			return CreateArgumentNullException(argument.ToString());
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentNullException(string argument, string? message = null)
		{
			return new ArgumentNullException(argument, message);
		}

		[DoesNotReturn]
		internal static void ThrowArrayTypeMismatchException()
		{
			throw CreateArrayTypeMismatchException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArrayTypeMismatchException()
		{
			return new ArrayTypeMismatchException();
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_InvalidTypeWithPointersNotSupported(Type type)
		{
			throw CreateArgumentException_InvalidTypeWithPointersNotSupported(type);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type)
		{
			return new ArgumentException($"Type {type} with managed pointers cannot be used in a Span");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_DestinationTooShort()
		{
			throw CreateArgumentException_DestinationTooShort();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_DestinationTooShort()
		{
			return new ArgumentException("Destination too short");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException(string message, string? argument = null)
		{
			throw CreateArgumentException(message, argument);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException(string message, string? argument)
		{
			return new ArgumentException(message, argument ?? "");
		}

		[DoesNotReturn]
		internal static void ThrowIndexOutOfRangeException()
		{
			throw CreateIndexOutOfRangeException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateIndexOutOfRangeException()
		{
			return new IndexOutOfRangeException();
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException()
		{
			throw CreateArgumentOutOfRangeException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException()
		{
			return new ArgumentOutOfRangeException();
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			throw CreateArgumentOutOfRangeException(argument);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			return new ArgumentOutOfRangeException(argument.ToString());
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge()
		{
			throw CreateArgumentOutOfRangeException_PrecisionTooLarge();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge()
		{
			return new ArgumentOutOfRangeException("precision", $"Precision too large (max: {99})");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit()
		{
			throw CreateArgumentOutOfRangeException_SymbolDoesNotFit();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_SymbolDoesNotFit()
		{
			return new ArgumentOutOfRangeException("symbol", "Bad format specifier");
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException()
		{
			throw CreateInvalidOperationException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException()
		{
			return new InvalidOperationException();
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException_OutstandingReferences()
		{
			throw CreateInvalidOperationException_OutstandingReferences();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_OutstandingReferences()
		{
			return new InvalidOperationException("Outstanding references");
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException_UnexpectedSegmentType()
		{
			throw CreateInvalidOperationException_UnexpectedSegmentType();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_UnexpectedSegmentType()
		{
			return new InvalidOperationException("Unexpected segment type");
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException_EndPositionNotReached()
		{
			throw CreateInvalidOperationException_EndPositionNotReached();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateInvalidOperationException_EndPositionNotReached()
		{
			return new InvalidOperationException("End position not reached");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException_PositionOutOfRange()
		{
			throw CreateArgumentOutOfRangeException_PositionOutOfRange();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_PositionOutOfRange()
		{
			return new ArgumentOutOfRangeException("position");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException_OffsetOutOfRange()
		{
			throw CreateArgumentOutOfRangeException_OffsetOutOfRange();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentOutOfRangeException_OffsetOutOfRange()
		{
			return new ArgumentOutOfRangeException("offset");
		}

		[DoesNotReturn]
		internal static void ThrowObjectDisposedException_ArrayMemoryPoolBuffer()
		{
			throw CreateObjectDisposedException_ArrayMemoryPoolBuffer();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateObjectDisposedException_ArrayMemoryPoolBuffer()
		{
			return new ObjectDisposedException("ArrayMemoryPoolBuffer");
		}

		[DoesNotReturn]
		internal static void ThrowFormatException_BadFormatSpecifier()
		{
			throw CreateFormatException_BadFormatSpecifier();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateFormatException_BadFormatSpecifier()
		{
			return new FormatException("Bad format specifier");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_OverlapAlignmentMismatch()
		{
			throw CreateArgumentException_OverlapAlignmentMismatch();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateArgumentException_OverlapAlignmentMismatch()
		{
			return new ArgumentException("Overlap alignment mismatch");
		}

		[DoesNotReturn]
		internal static void ThrowNotSupportedException(string? msg = null)
		{
			throw CreateThrowNotSupportedException(msg);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateThrowNotSupportedException(string? msg)
		{
			return new NotSupportedException();
		}

		[DoesNotReturn]
		internal static void ThrowKeyNullException()
		{
			ThrowArgumentNullException(System.ExceptionArgument.key);
		}

		[DoesNotReturn]
		internal static void ThrowValueNullException()
		{
			throw CreateThrowValueNullException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateThrowValueNullException()
		{
			return new ArgumentException("Value is null");
		}

		[DoesNotReturn]
		internal static void ThrowOutOfMemoryException()
		{
			throw CreateOutOfMemoryException();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static Exception CreateOutOfMemoryException()
		{
			return new OutOfMemoryException();
		}

		public static bool TryFormatThrowFormatException(out int bytesWritten)
		{
			bytesWritten = 0;
			ThrowFormatException_BadFormatSpecifier();
			return false;
		}

		public static bool TryParseThrowFormatException<T>(out T value, out int bytesConsumed)
		{
			value = default(T);
			bytesConsumed = 0;
			ThrowFormatException_BadFormatSpecifier();
			return false;
		}

		[DoesNotReturn]
		public static void ThrowArgumentValidationException<T>(ReadOnlySequenceSegment<T>? startSegment, int startIndex, ReadOnlySequenceSegment<T>? endSegment)
		{
			throw CreateArgumentValidationException(startSegment, startIndex, endSegment);
		}

		private static Exception CreateArgumentValidationException<T>(ReadOnlySequenceSegment<T>? startSegment, int startIndex, ReadOnlySequenceSegment<T>? endSegment)
		{
			if (startSegment == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.startSegment);
			}
			if (endSegment == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.endSegment);
			}
			if (startSegment != endSegment && startSegment.RunningIndex > endSegment.RunningIndex)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.endSegment);
			}
			if ((uint)startSegment.Memory.Length < (uint)startIndex)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.startIndex);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.endIndex);
		}

		[DoesNotReturn]
		public static void ThrowArgumentValidationException(Array? array, int start)
		{
			throw CreateArgumentValidationException(array, start);
		}

		private static Exception CreateArgumentValidationException(Array? array, int start)
		{
			if (array == null)
			{
				return CreateArgumentNullException(System.ExceptionArgument.array);
			}
			if ((uint)start > (uint)array.Length)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.length);
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_TupleIncorrectType(object other)
		{
			throw new ArgumentException($"Value tuple of incorrect type (found {other.GetType()})", "other");
		}

		[DoesNotReturn]
		public static void ThrowStartOrEndArgumentValidationException(long start)
		{
			throw CreateStartOrEndArgumentValidationException(start);
		}

		private static Exception CreateStartOrEndArgumentValidationException(long start)
		{
			if (start < 0)
			{
				return CreateArgumentOutOfRangeException(System.ExceptionArgument.start);
			}
			return CreateArgumentOutOfRangeException(System.ExceptionArgument.length);
		}
	}
	internal enum ExceptionArgument
	{
		length,
		start,
		bufferSize,
		minimumBufferSize,
		elementIndex,
		comparable,
		comparer,
		destination,
		offset,
		startSegment,
		endSegment,
		startIndex,
		endIndex,
		array,
		culture,
		manager,
		key,
		collection,
		index,
		type,
		self,
		value,
		oldValue,
		newValue
	}
	public static class TypeExtensions
	{
		public static bool IsByRefLike(this Type type)
		{
			System.ThrowHelper.ThrowIfArgumentNull(type, System.ExceptionArgument.type);
			if ((object)type == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.type);
			}
			return type.IsByRefLike;
		}
	}
}
namespace System.Threading
{
	public static class MonitorEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Enter(object obj, ref bool lockTaken)
		{
			Monitor.Enter(obj, ref lockTaken);
		}
	}
}
namespace System.Text
{
	public static class StringBuilderExtensions
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static StringBuilder Clear(this StringBuilder builder)
		{
			System.ThrowHelper.ThrowIfArgumentNull(builder, "builder");
			return builder.Clear();
		}
	}
}
namespace System.Numerics
{
	public static class BitOperations
	{
		private static ReadOnlySpan<byte> TrailingZeroCountDeBruijn => new byte[32]
		{
			0, 1, 28, 2, 29, 14, 24, 3, 30, 22,
			20, 15, 25, 17, 4, 8, 31, 27, 13, 23,
			21, 19, 16, 7, 26, 12, 18, 6, 11, 5,
			10, 9
		};

		private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32]
		{
			0, 9, 1, 10, 13, 21, 2, 29, 11, 14,
			16, 18, 22, 25, 3, 30, 8, 12, 20, 28,
			15, 17, 24, 7, 19, 27, 23, 6, 26, 5,
			4, 31
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int LeadingZeroCount(uint value)
		{
			if (value == 0)
			{
				return 32;
			}
			return 0x1F ^ Log2SoftwareFallback(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int LeadingZeroCount(ulong value)
		{
			uint num = (uint)(value >> 32);
			if (num == 0)
			{
				return 32 + LeadingZeroCount((uint)value);
			}
			return LeadingZeroCount(num);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int Log2(uint value)
		{
			value |= 1u;
			return Log2SoftwareFallback(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int Log2(ulong value)
		{
			value |= 1;
			uint num = (uint)(value >> 32);
			if (num == 0)
			{
				return Log2((uint)value);
			}
			return 32 + Log2(num);
		}

		private static int Log2SoftwareFallback(uint value)
		{
			value |= value >> 1;
			value |= value >> 2;
			value |= value >> 4;
			value |= value >> 8;
			value |= value >> 16;
			return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (IntPtr)(int)(value * 130329821 >> 27));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int Log2Ceiling(uint value)
		{
			int num = Log2(value);
			if (PopCount(value) != 1)
			{
				num++;
			}
			return num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int Log2Ceiling(ulong value)
		{
			int num = Log2(value);
			if (PopCount(value) != 1)
			{
				num++;
			}
			return num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int PopCount(uint value)
		{
			return SoftwareFallback(value);
			static int SoftwareFallback(uint value)
			{
				value -= (value >> 1) & 0x55555555;
				value = (value & 0x33333333) + ((value >> 2) & 0x33333333);
				value = ((value + (value >> 4)) & 0xF0F0F0F) * 16843009 >> 24;
				return (int)value;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int PopCount(ulong value)
		{
			if (IntPtr.Size == 8)
			{
				return PopCount((uint)value) + PopCount((uint)(value >> 32));
			}
			return SoftwareFallback(value);
			static int SoftwareFallback(ulong value)
			{
				value -= (value >> 1) & 0x5555555555555555L;
				value = (value & 0x3333333333333333L) + ((value >> 2) & 0x3333333333333333L);
				value = ((value + (value >> 4)) & 0xF0F0F0F0F0F0F0FL) * 72340172838076673L >> 56;
				return (int)value;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int TrailingZeroCount(int value)
		{
			return TrailingZeroCount((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int TrailingZeroCount(uint value)
		{
			if (value == 0)
			{
				return 32;
			}
			return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(TrailingZeroCountDeBruijn), (IntPtr)(int)((value & (0 - value)) * 125613361 >> 27));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int TrailingZeroCount(long value)
		{
			return TrailingZeroCount((ulong)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int TrailingZeroCount(ulong value)
		{
			uint num = (uint)value;
			if (num == 0)
			{
				return 32 + TrailingZeroCount((uint)(value >> 32));
			}
			return TrailingZeroCount(num);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint RotateLeft(uint value, int offset)
		{
			return (value << offset) | (value >> 32 - offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong RotateLeft(ulong value, int offset)
		{
			return (value << offset) | (value >> 64 - offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint RotateRight(uint value, int offset)
		{
			return (value >> offset) | (value << 32 - offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong RotateRight(ulong value, int offset)
		{
			return (value >> offset) | (value << 64 - offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static uint ResetLowestSetBit(uint value)
		{
			return value & (value - 1);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static uint ResetBit(uint value, int bitPos)
		{
			return value & (uint)(~(1 << bitPos));
		}
	}
	public static class BitOperationsEx
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsPow2(int value)
		{
			if ((value & (value - 1)) == 0)
			{
				return value > 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static bool IsPow2(uint value)
		{
			if ((value & (value - 1)) == 0)
			{
				return value != 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsPow2(long value)
		{
			if ((value & (value - 1)) == 0L)
			{
				return value > 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static bool IsPow2(ulong value)
		{
			if ((value & (value - 1)) == 0L)
			{
				return value != 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsPow2(nint value)
		{
			if ((value & (value - 1)) == 0)
			{
				return value > 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static bool IsPow2(nuint value)
		{
			if ((value & (value - 1)) == 0)
			{
				return value != 0;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint RoundUpToPowerOf2(uint value)
		{
			value--;
			value |= value >> 1;
			value |= value >> 2;
			value |= value >> 4;
			value |= value >> 8;
			value |= value >> 16;
			return value + 1;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong RoundUpToPowerOf2(ulong value)
		{
			value--;
			value |= value >> 1;
			value |= value >> 2;
			value |= value >> 4;
			value |= value >> 8;
			value |= value >> 16;
			value |= value >> 32;
			return value + 1;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static nuint RoundUpToPowerOf2(nuint value)
		{
			if (IntPtr.Size == 8)
			{
				return (nuint)RoundUpToPowerOf2((ulong)value);
			}
			return RoundUpToPowerOf2((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int LeadingZeroCount(uint value)
		{
			return BitOperations.LeadingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int LeadingZeroCount(ulong value)
		{
			return BitOperations.LeadingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int LeadingZeroCount(nuint value)
		{
			if (IntPtr.Size == 8)
			{
				return LeadingZeroCount((ulong)value);
			}
			return LeadingZeroCount((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int Log2(uint value)
		{
			return BitOperations.Log2(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int Log2(ulong value)
		{
			return BitOperations.Log2(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int Log2(nuint value)
		{
			if (IntPtr.Size == 8)
			{
				return Log2((ulong)value);
			}
			return Log2((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int PopCount(uint value)
		{
			return BitOperations.PopCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int PopCount(ulong value)
		{
			return BitOperations.PopCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int PopCount(nuint value)
		{
			if (IntPtr.Size == 8)
			{
				return PopCount((ulong)value);
			}
			return PopCount((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int TrailingZeroCount(int value)
		{
			return BitOperations.TrailingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int TrailingZeroCount(uint value)
		{
			return BitOperations.TrailingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int TrailingZeroCount(long value)
		{
			return BitOperations.TrailingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int TrailingZeroCount(ulong value)
		{
			return BitOperations.TrailingZeroCount(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int TrailingZeroCount(nint value)
		{
			if (IntPtr.Size == 8)
			{
				return TrailingZeroCount((long)value);
			}
			return TrailingZeroCount((int)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static int TrailingZeroCount(nuint value)
		{
			if (IntPtr.Size == 8)
			{
				return TrailingZeroCount((ulong)value);
			}
			return TrailingZeroCount((uint)value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint RotateLeft(uint value, int offset)
		{
			return BitOperations.RotateLeft(value, offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong RotateLeft(ulong value, int offset)
		{
			return BitOperations.RotateLeft(value, offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static nuint RotateLeft(nuint value, int offset)
		{
			if (IntPtr.Size == 8)
			{
				return (nuint)RotateLeft((ulong)value, offset);
			}
			return RotateLeft((uint)value, offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static uint RotateRight(uint value, int offset)
		{
			return BitOperations.RotateRight(value, offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static ulong RotateRight(ulong value, int offset)
		{
			return BitOperations.RotateRight(value, offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[CLSCompliant(false)]
		public static nuint RotateRight(nuint value, int offset)
		{
			if (IntPtr.Size == 8)
			{
				return (nuint)RotateRight((ulong)value, offset);
			}
			return RotateRight((uint)value, offset);
		}
	}
}
namespace System.IO
{
	public static class StreamExtensions
	{
		public static void CopyTo(this Stream src, Stream destination)
		{
			System.ThrowHelper.ThrowIfArgumentNull(src, "src");
			src.CopyTo(destination);
		}

		public static void CopyTo(this Stream src, Stream destination, int bufferSize)
		{
			System.ThrowHelper.ThrowIfArgumentNull(src, "src");
			src.CopyTo(destination, bufferSize);
		}
	}
}
namespace System.Collections
{
	internal static class HashHelpers
	{
		public const uint HashCollisionThreshold = 100u;

		public const int MaxPrimeArrayLength = 2147483587;

		public const int HashPrime = 101;

		private static readonly int[] s_primes = new int[72]
		{
			3, 7, 11, 17, 23, 29, 37, 47, 59, 71,
			89, 107, 131, 163, 197, 239, 293, 353, 431, 521,
			631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371,
			4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023,
			25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363,
			156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403,
			968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559,
			5999471, 7199369
		};

		public static bool IsPrime(int candidate)
		{
			if (((uint)candidate & (true ? 1u : 0u)) != 0)
			{
				int num = (int)Math.Sqrt(candidate);
				for (int i = 3; i <= num; i += 2)
				{
					if (candidate % i == 0)
					{
						return false;
					}
				}
				return true;
			}
			return candidate == 2;
		}

		public static int GetPrime(int min)
		{
			if (min < 0)
			{
				throw new ArgumentException("Prime minimum cannot be less than zero");
			}
			int[] array = s_primes;
			foreach (int num in array)
			{
				if (num >= min)
				{
					return num;
				}
			}
			for (int j = min | 1; j < int.MaxValue; j += 2)
			{
				if (IsPrime(j) && (j - 1) % 101 != 0)
				{
					return j;
				}
			}
			return min;
		}

		public static int ExpandPrime(int oldSize)
		{
			int num = 2 * oldSize;
			if ((uint)num > 2147483587u && 2147483587 > oldSize)
			{
				return 2147483587;
			}
			return GetPrime(num);
		}

		public static ulong GetFastModMultiplier(uint divisor)
		{
			return ulong.MaxValue / (ulong)divisor + 1;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static uint FastMod(uint value, uint divisor, ulong multiplier)
		{
			return (uint)(((multiplier * value >> 32) + 1) * divisor >> 32);
		}
	}
}
namespace System.Collections.Concurrent
{
	public static class ConcurrentExtensions
	{
		public static void Clear<T>(this ConcurrentBag<T> bag)
		{
			System.ThrowHelper.ThrowIfArgumentNull(bag, "bag");
			bag.Clear();
		}

		public static void Clear<T>(this ConcurrentQueue<T> queue)
		{
			System.ThrowHelper.ThrowIfArgumentNull(queue, "queue");
			queue.Clear();
		}

		public static TValue AddOrUpdate<TKey, TValue, TArg>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TKey, TArg, TValue> addValueFactory, Func<TKey, TValue, TArg, TValue> updateValueFactory, TArg factoryArgument) where TKey : notnull
		{
			System.ThrowHelper.ThrowIfArgumentNull(dict, "dict");
			return dict.AddOrUpdate(key, addValueFactory, updateValueFactory, factoryArgument);
		}

		public static TValue GetOrAdd<TKey, TValue, TArg>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TKey, TArg, TValue> valueFactory, TArg factoryArgument) where TKey : notnull
		{
			System.ThrowHelper.ThrowIfArgumentNull(dict, "dict");
			return dict.GetOrAdd(key, valueFactory, factoryArgument);
		}

		public static bool TryRemove<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, KeyValuePair<TKey, TValue> item) where TKey : notnull
		{
			System.ThrowHelper.ThrowIfArgumentNull(dict, "dict");
			if (dict.TryRemove(item.Key, out TValue value))
			{
				if (EqualityComparer<TValue>.Default.Equals(item.Value, value))
				{
					return true;
				}
				dict.AddOrUpdate(item.Key, (TKey _) => value, (TKey _, TValue _) => value);
				return false;
			}
			return false;
		}
	}
}
namespace System.Runtime
{
	public struct DependentHandle : IDisposable
	{
		private sealed class DependentHolder : CriticalFinalizerObject
		{
			public GCHandle TargetHandle;

			private IntPtr dependent;

			public object? Dependent
			{
				get
				{
					return GCHandle.FromIntPtr(dependent).Target;
				}
				set
				{
					IntPtr value2 = GCHandle.ToIntPtr(GCHandle.Alloc(value, GCHandleType.Normal));
					IntPtr intPtr;
					do
					{
						intPtr = dependent;
					}
					while (Interlocked.CompareExchange(ref dependent, value2, intPtr) == intPtr);
					GCHandle.FromIntPtr(intPtr).Free();
				}
			}

			public DependentHolder(GCHandle targetHandle, object dependent)
			{
				TargetHandle = targetHandle;
				this.dependent = GCHandle.ToIntPtr(GCHandle.Alloc(dependent, GCHandleType.Normal));
			}

			~DependentHolder()
			{
				if (!AppDomain.CurrentDomain.IsFinalizingForUnload() && (!Environment.HasShutdownStarted && (TargetHandle.IsAllocated && TargetHandle.Target != null)))
				{
					GC.ReRegisterForFinalize(this);
				}
				else
				{
					GCHandle.FromIntPtr(dependent).Free();
				}
			}
		}

		private GCHandle dependentHandle;

		private volatile bool allocated;

		public bool IsAllocated => allocated;

		public object? Target
		{
			get
			{
				if (!allocated)
				{
					throw new InvalidOperationException();
				}
				return UnsafeGetTarget();
			}
			set
			{
				if (!allocated || value != null)
				{
					throw new InvalidOperationException();
				}
				UnsafeSetTargetToNull();
			}
		}

		public object? Dependent
		{
			get
			{
				if (!allocated)
				{
					throw new InvalidOperationException();
				}
				return UnsafeGetHolder()?.Dependent;
			}
			set
			{
				if (!allocated)
				{
					throw new InvalidOperationException();
				}
				UnsafeSetDependent(value);
			}
		}

		public (object? Target, object? Dependent) TargetAndDependent
		{
			get
			{
				if (!allocated)
				{
					throw new InvalidOperationException();
				}
				return (UnsafeGetTarget(), Dependent);
			}
		}

		public DependentHandle(object? target, object? dependent)
		{
			GCHandle targetHandle = GCHandle.Alloc(target, GCHandleType.WeakTrackResurrection);
			dependentHandle = AllocDepHolder(targetHandle, dependent);
			GC.KeepAlive(target);
			allocated = true;
		}

		private static GCHandle AllocDepHolder(GCHandle targetHandle, object? dependent)
		{
			return GCHandle.Alloc((dependent != null) ? new DependentHolder(targetHandle, dependent) : null, GCHandleType.WeakTrackResurrection);
		}

		private DependentHolder? UnsafeGetHolder()
		{
			return Unsafe.As<DependentHolder>(dependentHandle.Target);
		}

		internal object? UnsafeGetTarget()
		{
			return UnsafeGetHolder()?.TargetHandle.Target;
		}

		internal object? UnsafeGetTargetAndDependent(out object? dependent)
		{
			dependent = null;
			DependentHolder dependentHolder = UnsafeGetHolder();
			if (dependentHolder == null)
			{
				return null;
			}
			object target = dependentHolder.TargetHandle.Target;
			if (target == null)
			{
				return null;
			}
			dependent = dependentHolder.Dependent;
			return target;
		}

		internal void UnsafeSetTargetToNull()
		{
			Free();
		}

		internal void UnsafeSetDependent(object? value)
		{
			DependentHolder dependentHolder = UnsafeGetHolder();
			if (dependentHolder != null)
			{
				if (!dependentHolder.TargetHandle.IsAllocated)
				{
					Free();
				}
				else
				{
					dependentHolder.Dependent = value;
				}
			}
		}

		private void FreeDependentHandle()
		{
			if (allocated)
			{
				UnsafeGetHolder()?.TargetHandle.Free();
				dependentHandle.Free();
			}
			allocated = false;
		}

		private void Free()
		{
			FreeDependentHandle();
		}

		public void Dispose()
		{
			Free();
			allocated = false;
		}
	}
}
namespace System.Runtime.InteropServices
{
	public static class MarshalEx
	{
		private static readonly MethodInfo? Marshal_SetLastWin32Error_Meth = typeof(Marshal).GetMethod("SetLastPInvokeError", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(Marshal).GetMethod("SetLastWin32Error", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

		private static readonly Action<int>? Marshal_SetLastWin32Error = (((object)Marshal_SetLastWin32Error_Meth == null) ? null : ((Action<int>)Delegate.CreateDelegate(typeof(Action<int>), Marshal_SetLastWin32Error_Meth)));

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int GetLastPInvokeError()
		{
			return Marshal.GetLastWin32Error();
		}

		public static void SetLastPInvokeError(int error)
		{
			(Marshal_SetLastWin32Error ?? throw new PlatformNotSupportedException("Cannot set last P/Invoke error (no method Marshal.SetLastWin32Error or Marshal.SetLastPInvokeError)"))(error);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal static class IsExternalInit
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	public sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	internal interface ICWTEnumerable<T>
	{
		IEnumerable<T> SelfEnumerable { get; }

		IEnumerator<T> GetEnumerator();
	}
	internal sealed class CWTEnumerable<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable where TKey : class where TValue : class?
	{
		private readonly ConditionalWeakTable<TKey, TValue> cwt;

		public CWTEnumerable(ConditionalWeakTable<TKey, TValue> table)
		{
			cwt = table;
		}

		public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
		{
			return cwt.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public static class ConditionalWeakTableExtensions
	{
		public static IEnumerable<KeyValuePair<TKey, TValue>> AsEnumerable<TKey, TValue>(this ConditionalWeakTable<TKey, TValue> self) where TKey : class where TValue : class?
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, "self");
			if (self != null)
			{
				return self;
			}
			if (self is ICWTEnumerable<KeyValuePair<TKey, TValue>> iCWTEnumerable)
			{
				return iCWTEnumerable.SelfEnumerable;
			}
			return new CWTEnumerable<TKey, TValue>(self);
		}

		public static IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator<TKey, TValue>(this ConditionalWeakTable<TKey, TValue> self) where TKey : class where TValue : class?
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, "self");
			if (self != null)
			{
				return ((IEnumerable<KeyValuePair<TKey, TValue>>)self).GetEnumerator();
			}
			if (self is ICWTEnumerable<KeyValuePair<TKey, TValue>> iCWTEnumerable)
			{
				return iCWTEnumerable.GetEnumerator();
			}
			throw new PlatformNotSupportedException("This version of MonoMod.Backports was built targeting a version of the framework where ConditionalWeakTable is enumerable, but it isn't!");
		}

		public static void Clear<TKey, TValue>(this ConditionalWeakTable<TKey, TValue> self) where TKey : class where TValue : class?
		{
			System.ThrowHelper.ThrowIfArgumentNull(self, "self");
			self.Clear();
		}

		public static bool TryAdd<TKey, TValue>(this ConditionalWeakTable<TKey, TValue> self, TKey key, TValue value) where TKey : class where TValue : class?
		{
			TValue value2 = value;
			System.ThrowHelper.ThrowIfArgumentNull(self, "self");
			bool didAdd = false;
			self.GetValue(key, delegate
			{
				didAdd = true;
				return value2;
			});
			return didAdd;
		}
	}
	[InterpolatedStringHandler]
	public ref struct DefaultInterpolatedStringHandler
	{
		private const int GuessedLengthPerHole = 11;

		private const int MinimumArrayPoolLength = 256;

		private readonly IFormatProvider? _provider;

		private char[]? _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		private readonly bool _hasCustomFormatter;

		internal ReadOnlySpan<char> Text => _chars.Slice(0, _pos);

		public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)
		{
			_provider = null;
			_chars = (_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(GetDefaultLength(literalLength, formattedCount)));
			_pos = 0;
			_hasCustomFormatter = false;
		}

		public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider)
		{
			_provider = provider;
			_chars = (_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(GetDefaultLength(literalLength, formattedCount)));
			_pos = 0;
			_hasCustomFormatter = provider != null && HasCustomFormatter(provider);
		}

		public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span<char> initialBuffer)
		{
			_provider = provider;
			_chars = initialBuffer;
			_arrayToReturnToPool = null;
			_pos = 0;
			_hasCustomFormatter = provider != null && HasCustomFormatter(provider);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static int GetDefaultLength(int literalLength, int formattedCount)
		{
			return Math.Max(256, literalLength + formattedCount * 11);
		}

		public override string ToString()
		{
			return Text.ToString();
		}

		public string ToStringAndClear()
		{
			string result = Text.ToString();
			Clear();
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void Clear()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(DefaultInterpolatedStringHandler);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void AppendLiteral(string value)
		{
			if (value.Length == 1)
			{
				Span<char> chars = _chars;
				int pos = _pos;
				if ((uint)pos < (uint)chars.Length)
				{
					chars[pos] = value[0];
					_pos = pos + 1;
				}
				else
				{
					GrowThenCopyString(value);
				}
			}
			else if (value.Length == 2)
			{
				Span<char> chars2 = _chars;
				int pos2 = _pos;
				if ((uint)pos2 < chars2.Length - 1)
				{
					value.AsSpan().CopyTo(chars2.Slice(pos2));
					_pos = pos2 + 2;
				}
				else
				{
					GrowThenCopyString(value);
				}
			}
			else
			{
				AppendStringDirect(value);
			}
		}

		private void AppendStringDirect(string value)
		{
			if (value.AsSpan().TryCopyTo(_chars.Slice(_pos)))
			{
				_pos += value.Length;
			}
			else
			{
				GrowThenCopyString(value);
			}
		}

		public void AppendFormatted<T>(T value)
		{
			if (_hasCustomFormatter)
			{
				AppendCustomFormatter(value, null);
				return;
			}
			if (typeof(T) == typeof(IntPtr))
			{
				AppendFormatted(Unsafe.As<T, IntPtr>(ref value));
				return;
			}
			if (typeof(T) == typeof(UIntPtr))
			{
				AppendFormatted(Unsafe.As<T, UIntPtr>(ref value));
				return;
			}
			string text = ((!(value is IFormattable)) ? value?.ToString() : ((IFormattable)(object)value).ToString(null, _provider));
			if (text != null)
			{
				AppendStringDirect(text);
			}
		}

		public void AppendFormatted<T>(T value, string? format)
		{
			if (_hasCustomFormatter)
			{
				AppendCustomFormatter(value, format);
				return;
			}
			if (typeof(T) == typeof(IntPtr))
			{
				AppendFormatted(Unsafe.As<T, IntPtr>(ref value), format);
				return;
			}
			if (typeof(T) == typeof(UIntPtr))
			{
				AppendFormatted(Unsafe.As<T, UIntPtr>(ref value), format);
				return;
			}
			string text = ((!(value is IFormattable)) ? value?.ToString() : ((IFormattable)(object)value).ToString(format, _provider));
			if (text != null)
			{
				AppendStringDirect(text);
			}
		}

		public void AppendFormatted<T>(T value, int alignment)
		{
			int pos = _pos;
			AppendFormatted(value);
			if (alignment != 0)
			{
				AppendOrInsertAlignmentIfNeeded(pos, alignment);
			}
		}

		public void AppendFormatted<T>(T value, int alignment, string? format)
		{
			int pos = _pos;
			AppendFormatted(value, format);
			if (alignment != 0)
			{
				AppendOrInsertAlignmentIfNeeded(pos, alignment);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AppendFormatted(IntPtr value)
		{
			if (IntPtr.Size == 4)
			{
				AppendFormatted((int)value);
			}
			else
			{
				AppendFormatted((long)value);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AppendFormatted(IntPtr value, string? format)
		{
			if (IntPtr.Size == 4)
			{
				AppendFormatted((int)value, format);
			}
			else
			{
				AppendFormatted((long)value, format);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AppendFormatted(UIntPtr value)
		{
			if (UIntPtr.Size == 4)
			{
				AppendFormatted((uint)value);
			}
			else
			{
				AppendFormatted((ulong)value);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AppendFormatted(UIntPtr value, string? format)
		{
			if (UIntPtr.Size == 4)
			{
				AppendFormatted((uint)value, format);
			}
			else
			{
				AppendFormatted((ulong)value, format);
			}
		}

		public void AppendFormatted(ReadOnlySpan<char> value)
		{
			if (value.TryCopyTo(_chars.Slice(_pos)))
			{
				_pos += value.Length;
			}
			else
			{
				GrowThenCopySpan(value);
			}
		}

		public void AppendFormatted(ReadOnlySpan<char> value, int alignment = 0, string? format = null)
		{
			bool flag = false;
			if (alignment < 0)
			{
				flag = true;
				alignment = -alignment;
			}
			int num = alignment - value.Length;
			if (num <= 0)
			{
				AppendFormatted(value);
				return;
			}
			EnsureCapacityForAdditionalChars(value.Length + num);
			if (flag)
			{
				value.CopyTo(_chars.Slice(_pos));
				_pos += value.Length;
				_chars.Slice(_pos, num).Fill(' ');
				_pos += num;
			}
			else
			{
				_chars.Slice(_pos, num).Fill(' ');
				_pos += num;
				value.CopyTo(_chars.Slice(_pos));
				_pos += value.Length;
			}
		}

		public void AppendFormatted(string? value)
		{
			if (!_hasCustomFormatter && value != null && value.AsSpan().TryCopyTo(_chars.Slice(_pos)))
			{
				_pos += value.Length;
			}
			else
			{
				AppendFormattedSlow(value);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void AppendFormattedSlow(string? value)
		{
			if (_hasCustomFormatter)
			{
				AppendCustomFormatter(value, null);
			}
			else if (value != null)
			{
				EnsureCapacityForAdditionalChars(value.Length);
				value.AsSpan().CopyTo(_chars.Slice(_pos));
				_pos += value.Length;
			}
		}

		public void AppendFormatted(string? value, int alignment = 0, string? format = null)
		{
			this.AppendFormatted<string>(value, alignment, format);
		}

		public void AppendFormatted(object? value, int alignment = 0, string? format = null)
		{
			this.AppendFormatted<object>(value, alignment, format);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static bool HasCustomFormatter(IFormatProvider provider)
		{
			if (provider.GetType() != typeof(CultureInfo))
			{
				return provider.GetFormat(typeof(ICustomFormatter)) != null;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void AppendCustomFormatter<T>(T value, string? format)
		{
			ICustomFormatter customFormatter = (ICustomFormatter)_provider.GetFormat(typeof(ICustomFormatter));
			if (customFormatter != null)
			{
				string text = customFormatter.Format(format, value, _provider);
				if (text != null)
				{
					AppendStringDirect(text);
				}
			}
		}

		private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)
		{
			int num = _pos - startingPos;
			bool flag = false;
			if (alignment < 0)
			{
				flag = true;
				alignment = -alignment;
			}
			int num2 = alignment - num;
			if (num2 > 0)
			{
				EnsureCapacityForAdditionalChars(num2);
				if (flag)
				{
					_chars.Slice(_pos, num2).Fill(' ');
				}
				else
				{
					_chars.Slice(startingPos, num).CopyTo(_chars.Slice(startingPos + num2));
					_chars.Slice(startingPos, num2).Fill(' ');
				}
				_pos += num2;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void EnsureCapacityForAdditionalChars(int additionalChars)
		{
			if (_chars.Length - _pos < additionalChars)
			{
				Grow(additionalChars);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowThenCopyString(string value)
		{
			Grow(value.Length);
			value.AsSpan().CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowThenCopySpan(ReadOnlySpan<char> value)
		{
			Grow(value.Length);
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalChars)
		{
			GrowCore((uint)(_pos + additionalChars));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow()
		{
			GrowCore((uint)(_chars.Length + 1));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void GrowCore(uint requiredMinCapacity)
		{
			int minimumLength = (int)MathEx.Clamp(Math.Max(requiredMinCapacity, Math.Min((uint)(_chars.Length * 2), uint.MaxValue)), 256u, 2147483647u);
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
	public sealed class DisableRuntimeMarshallingAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
	public sealed class InterpolatedStringHandlerAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	public sealed class InterpolatedStringHandlerArgumentAttribute : Attribute
	{
		public string[] Arguments { get; }

		public InterpolatedStringHandlerArgumentAttribute(string argument)
		{
			Arguments = new string[1] { argument };
		}

		public InterpolatedStringHandlerArgumentAttribute(params string[] arguments)
		{
			Arguments = arguments;
		}
	}
	internal interface ITuple
	{
		int Length { get; }

		object? this[int index] { get; }
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	public sealed class ModuleInitializerAttribute : Attribute
	{
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
	public static class ExtraDynamicallyAccessedMemberTypes
	{
		public const DynamicallyAccessedMemberTypes Interfaces = (DynamicallyAccessedMemberTypes)8192;
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	public sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	public enum DynamicallyAccessedMemberTypes
	{
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	public sealed class UnscopedRefAttribute : Attribute
	{
	}
}

Smushi_Archipelago\Newtonsoft.Json.dll

Decompiled 3 days ago
#define DEBUG
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")]
[assembly: AssemblyTrademark("")]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Newtonsoft")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("Copyright © James Newton-King 2008")]
[assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")]
[assembly: AssemblyFileVersion("11.0.1")]
[assembly: AssemblyInformationalVersion("11.0.1-beta2+8931bf49300e016eeb846932030e0445944db3bf")]
[assembly: AssemblyProduct("Json.NET")]
[assembly: AssemblyTitle("Json.NET .NET Standard 2.0")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ArchipelagoMW/Archipelago.MultiClient.Net.git")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("11.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[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;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
}
namespace Newtonsoft.Json
{
	public enum ConstructorHandling
	{
		Default,
		AllowNonPublicDefaultConstructor
	}
	public enum DateFormatHandling
	{
		IsoDateFormat,
		MicrosoftDateFormat
	}
	public enum DateParseHandling
	{
		None,
		DateTime,
		DateTimeOffset
	}
	public enum DateTimeZoneHandling
	{
		Local,
		Utc,
		Unspecified,
		RoundtripKind
	}
	public class DefaultJsonNameTable : JsonNameTable
	{
		private class Entry
		{
			internal readonly string Value;

			internal readonly int HashCode;

			internal Entry Next;

			internal Entry(string value, int hashCode, Entry next)
			{
				Value = value;
				HashCode = hashCode;
				Next = next;
			}
		}

		private static readonly int HashCodeRandomizer;

		private int _count;

		private Entry[] _entries;

		private int _mask = 31;

		static DefaultJsonNameTable()
		{
			HashCodeRandomizer = Environment.TickCount;
		}

		public DefaultJsonNameTable()
		{
			_entries = new Entry[_mask + 1];
		}

		public override string? Get(char[] key, int start, int length)
		{
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			num += (num << 7) ^ key[start];
			int num2 = start + length;
			for (int i = start + 1; i < num2; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			int num3 = num & _mask;
			Entry[] entries = _entries;
			for (Entry entry = entries[num3]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && TextEquals(entry.Value, key, start, length))
				{
					return entry.Value;
				}
			}
			return null;
		}

		public string Add(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			int length = key.Length;
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			for (int i = 0; i < key.Length; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal))
				{
					return entry.Value;
				}
			}
			return AddEntry(key, num);
		}

		private string AddEntry(string str, int hashCode)
		{
			int num = hashCode & _mask;
			Entry entry = new Entry(str, hashCode, _entries[num]);
			_entries[num] = entry;
			if (_count++ == _mask)
			{
				Grow();
			}
			return entry.Value;
		}

		private void Grow()
		{
			Entry[] entries = _entries;
			int num = _mask * 2 + 1;
			Entry[] array = new Entry[num + 1];
			for (int i = 0; i < entries.Length; i++)
			{
				Entry entry = entries[i];
				while (entry != null)
				{
					int num2 = entry.HashCode & num;
					Entry next = entry.Next;
					entry.Next = array[num2];
					array[num2] = entry;
					entry = next;
				}
			}
			_entries = array;
			_mask = num;
		}

		private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)
		{
			if (str1.Length != str2Length)
			{
				return false;
			}
			for (int i = 0; i < str1.Length; i++)
			{
				if (str1[i] != str2[str2Start + i])
				{
					return false;
				}
			}
			return true;
		}
	}
	[Flags]
	public enum DefaultValueHandling
	{
		Include = 0,
		Ignore = 1,
		Populate = 2,
		IgnoreAndPopulate = 3
	}
	public enum FloatFormatHandling
	{
		String,
		Symbol,
		DefaultValue
	}
	public enum FloatParseHandling
	{
		Double,
		Decimal
	}
	public enum Formatting
	{
		None,
		Indented
	}
	public interface IArrayPool<T>
	{
		T[] Rent(int minimumLength);

		void Return(T[]? array);
	}
	public interface IJsonLineInfo
	{
		int LineNumber { get; }

		int LinePosition { get; }

		bool HasLineInfo();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonArrayAttribute : JsonContainerAttribute
	{
		private bool _allowNullItems;

		public bool AllowNullItems
		{
			get
			{
				return _allowNullItems;
			}
			set
			{
				_allowNullItems = value;
			}
		}

		public JsonArrayAttribute()
		{
		}

		public JsonArrayAttribute(bool allowNullItems)
		{
			_allowNullItems = allowNullItems;
		}

		public JsonArrayAttribute(string id)
			: base(id)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)]
	public sealed class JsonConstructorAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public abstract class JsonContainerAttribute : Attribute
	{
		internal bool? _isReference;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		private Type? _namingStrategyType;

		private object[]? _namingStrategyParameters;

		public string? Id { get; set; }

		public string? Title { get; set; }

		public string? Description { get; set; }

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType
		{
			get
			{
				return _namingStrategyType;
			}
			set
			{
				_namingStrategyType = value;
				NamingStrategyInstance = null;
			}
		}

		public object[]? NamingStrategyParameters
		{
			get
			{
				return _namingStrategyParameters;
			}
			set
			{
				_namingStrategyParameters = value;
				NamingStrategyInstance = null;
			}
		}

		internal NamingStrategy? NamingStrategyInstance { get; set; }

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		protected JsonContainerAttribute()
		{
		}

		protected JsonContainerAttribute(string id)
		{
			Id = id;
		}
	}
	public static class JsonConvert
	{
		public static readonly string True = "true";

		public static readonly string False = "false";

		public static readonly string Null = "null";

		public static readonly string Undefined = "undefined";

		public static readonly string PositiveInfinity = "Infinity";

		public static readonly string NegativeInfinity = "-Infinity";

		public static readonly string NaN = "NaN";

		public static Func<JsonSerializerSettings>? DefaultSettings { get; set; }

		public static string ToString(DateTime value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
		}

		public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
		{
			DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(DateTimeOffset value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat);
		}

		public static string ToString(DateTimeOffset value, DateFormatHandling format)
		{
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(bool value)
		{
			return value ? True : False;
		}

		public static string ToString(char value)
		{
			return ToString(char.ToString(value));
		}

		public static string ToString(Enum value)
		{
			return value.ToString("D");
		}

		public static string ToString(int value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(short value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ushort value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(uint value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(long value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		private static string ToStringInternal(BigInteger value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ulong value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(float value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value)))
			{
				return text;
			}
			if (floatFormatHandling == FloatFormatHandling.DefaultValue)
			{
				return (!nullable) ? "0.0" : Null;
			}
			return quoteChar + text + quoteChar;
		}

		public static string ToString(double value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureDecimalPlace(double value, string text)
		{
			if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		private static string EnsureDecimalPlace(string text)
		{
			if (text.IndexOf('.') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		public static string ToString(byte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(sbyte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(decimal value)
		{
			return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
		}

		public static string ToString(Guid value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(Guid value, char quoteChar)
		{
			string text = value.ToString("D", CultureInfo.InvariantCulture);
			string text2 = quoteChar.ToString(CultureInfo.InvariantCulture);
			return text2 + text + text2;
		}

		public static string ToString(TimeSpan value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(TimeSpan value, char quoteChar)
		{
			return ToString(value.ToString(), quoteChar);
		}

		public static string ToString(Uri? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ToString(value, '"');
		}

		internal static string ToString(Uri value, char quoteChar)
		{
			return ToString(value.OriginalString, quoteChar);
		}

		public static string ToString(string? value)
		{
			return ToString(value, '"');
		}

		public static string ToString(string? value, char delimiter)
		{
			return ToString(value, delimiter, StringEscapeHandling.Default);
		}

		public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling)
		{
			if (delimiter != '"' && delimiter != '\'')
			{
				throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
			}
			return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling);
		}

		public static string ToString(object? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ConvertUtils.GetTypeCode(value.GetType()) switch
			{
				PrimitiveTypeCode.String => ToString((string)value), 
				PrimitiveTypeCode.Char => ToString((char)value), 
				PrimitiveTypeCode.Boolean => ToString((bool)value), 
				PrimitiveTypeCode.SByte => ToString((sbyte)value), 
				PrimitiveTypeCode.Int16 => ToString((short)value), 
				PrimitiveTypeCode.UInt16 => ToString((ushort)value), 
				PrimitiveTypeCode.Int32 => ToString((int)value), 
				PrimitiveTypeCode.Byte => ToString((byte)value), 
				PrimitiveTypeCode.UInt32 => ToString((uint)value), 
				PrimitiveTypeCode.Int64 => ToString((long)value), 
				PrimitiveTypeCode.UInt64 => ToString((ulong)value), 
				PrimitiveTypeCode.Single => ToString((float)value), 
				PrimitiveTypeCode.Double => ToString((double)value), 
				PrimitiveTypeCode.DateTime => ToString((DateTime)value), 
				PrimitiveTypeCode.Decimal => ToString((decimal)value), 
				PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), 
				PrimitiveTypeCode.Guid => ToString((Guid)value), 
				PrimitiveTypeCode.Uri => ToString((Uri)value), 
				PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), 
				PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), 
				_ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), 
			};
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value)
		{
			return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting)
		{
			return SerializeObject(value, formatting, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			jsonSerializer.Formatting = formatting;
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer)
		{
			StringBuilder sb = new StringBuilder(256);
			StringWriter stringWriter = new StringWriter(sb, CultureInfo.InvariantCulture);
			using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter))
			{
				jsonTextWriter.Formatting = jsonSerializer.Formatting;
				jsonSerializer.Serialize(jsonTextWriter, value, type);
			}
			return stringWriter.ToString();
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value)
		{
			return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, JsonSerializerSettings settings)
		{
			return DeserializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, Type type)
		{
			return DeserializeObject(value, type, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static T? DeserializeObject<T>(string value)
		{
			return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
		{
			return DeserializeObject<T>(value);
		}

		[DebuggerStepThrough]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
		{
			return DeserializeObject<T>(value, settings);
		}

		[DebuggerStepThrough]
		public static T? DeserializeObject<T>(string value, params JsonConverter[] converters)
		{
			return (T)DeserializeObject(value, typeof(T), converters);
		}

		[DebuggerStepThrough]
		public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings)
		{
			return (T)DeserializeObject(value, typeof(T), settings);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return DeserializeObject(value, type, settings);
		}

		public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings)
		{
			ValidationUtils.ArgumentNotNull(value, "value");
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			if (!jsonSerializer.IsCheckAdditionalContentSet())
			{
				jsonSerializer.CheckAdditionalContent = true;
			}
			using JsonTextReader reader = new JsonTextReader(new StringReader(value));
			return jsonSerializer.Deserialize(reader, type);
		}

		[DebuggerStepThrough]
		public static void PopulateObject(string value, object target)
		{
			PopulateObject(value, target, null);
		}

		public static void PopulateObject(string value, object target, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			using JsonReader jsonReader = new JsonTextReader(new StringReader(value));
			jsonSerializer.Populate(jsonReader, target);
			if (settings == null || !settings.CheckAdditionalContent)
			{
				return;
			}
			while (jsonReader.Read())
			{
				if (jsonReader.TokenType != JsonToken.Comment)
				{
					throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
				}
			}
		}
	}
	public abstract class JsonConverter
	{
		public virtual bool CanRead => true;

		public virtual bool CanWrite => true;

		public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer);

		public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer);

		public abstract bool CanConvert(Type objectType);
	}
	public abstract class JsonConverter<T> : JsonConverter
	{
		public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
		{
			if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T))))
			{
				throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			WriteJson(writer, (T)value, serializer);
		}

		public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer);

		public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
		{
			bool flag = existingValue == null;
			if (!flag && !(existingValue is T))
			{
				throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer);
		}

		public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer);

		public sealed override bool CanConvert(Type objectType)
		{
			return typeof(T).IsAssignableFrom(objectType);
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonConverterAttribute : Attribute
	{
		private readonly Type _converterType;

		public Type ConverterType => _converterType;

		public object[]? ConverterParameters { get; }

		public JsonConverterAttribute(Type converterType)
		{
			if (converterType == null)
			{
				throw new ArgumentNullException("converterType");
			}
			_converterType = converterType;
		}

		public JsonConverterAttribute(Type converterType, params object[] converterParameters)
			: this(converterType)
		{
			ConverterParameters = converterParameters;
		}
	}
	public class JsonConverterCollection : Collection<JsonConverter>
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonDictionaryAttribute : JsonContainerAttribute
	{
		public JsonDictionaryAttribute()
		{
		}

		public JsonDictionaryAttribute(string id)
			: base(id)
		{
		}
	}
	[Serializable]
	public class JsonException : Exception
	{
		public JsonException()
		{
		}

		public JsonException(string message)
			: base(message)
		{
		}

		public JsonException(string message, Exception? innerException)
			: base(message, innerException)
		{
		}

		public JsonException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			return new JsonException(message);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class JsonExtensionDataAttribute : Attribute
	{
		public bool WriteData { get; set; }

		public bool ReadData { get; set; }

		public JsonExtensionDataAttribute()
		{
			WriteData = true;
			ReadData = true;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonIgnoreAttribute : Attribute
	{
	}
	public abstract class JsonNameTable
	{
		public abstract string? Get(char[] key, int start, int length);
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonObjectAttribute : JsonContainerAttribute
	{
		private MemberSerialization _memberSerialization = MemberSerialization.OptOut;

		internal MissingMemberHandling? _missingMemberHandling;

		internal Required? _itemRequired;

		internal NullValueHandling? _itemNullValueHandling;

		public MemberSerialization MemberSerialization
		{
			get
			{
				return _memberSerialization;
			}
			set
			{
				_memberSerialization = value;
			}
		}

		public MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling.GetValueOrDefault();
			}
			set
			{
				_missingMemberHandling = value;
			}
		}

		public NullValueHandling ItemNullValueHandling
		{
			get
			{
				return _itemNullValueHandling.GetValueOrDefault();
			}
			set
			{
				_itemNullValueHandling = value;
			}
		}

		public Required ItemRequired
		{
			get
			{
				return _itemRequired.GetValueOrDefault();
			}
			set
			{
				_itemRequired = value;
			}
		}

		public JsonObjectAttribute()
		{
		}

		public JsonObjectAttribute(MemberSerialization memberSerialization)
		{
			MemberSerialization = memberSerialization;
		}

		public JsonObjectAttribute(string id)
			: base(id)
		{
		}
	}
	internal enum JsonContainerType
	{
		None,
		Object,
		Array,
		Constructor
	}
	internal struct JsonPosition
	{
		private static readonly char[] SpecialCharacters = new char[18]
		{
			'.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t',
			'\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029'
		};

		internal JsonContainerType Type;

		internal int Position;

		internal string? PropertyName;

		internal bool HasIndex;

		public JsonPosition(JsonContainerType type)
		{
			Type = type;
			HasIndex = TypeHasIndex(type);
			Position = -1;
			PropertyName = null;
		}

		internal int CalculateLength()
		{
			switch (Type)
			{
			case JsonContainerType.Object:
				return PropertyName.Length + 5;
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				return MathUtils.IntLength((ulong)Position) + 2;
			default:
				throw new ArgumentOutOfRangeException("Type");
			}
		}

		internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer)
		{
			switch (Type)
			{
			case JsonContainerType.Object:
			{
				string propertyName = PropertyName;
				if (propertyName.IndexOfAny(SpecialCharacters) != -1)
				{
					sb.Append("['");
					if (writer == null)
					{
						writer = new StringWriter(sb);
					}
					JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer);
					sb.Append("']");
				}
				else
				{
					if (sb.Length > 0)
					{
						sb.Append('.');
					}
					sb.Append(propertyName);
				}
				break;
			}
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				sb.Append('[');
				sb.Append(Position);
				sb.Append(']');
				break;
			}
		}

		internal static bool TypeHasIndex(JsonContainerType type)
		{
			return type == JsonContainerType.Array || type == JsonContainerType.Constructor;
		}

		internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition)
		{
			int num = 0;
			if (positions != null)
			{
				for (int i = 0; i < positions.Count; i++)
				{
					num += positions[i].CalculateLength();
				}
			}
			if (currentPosition.HasValue)
			{
				num += currentPosition.GetValueOrDefault().CalculateLength();
			}
			StringBuilder stringBuilder = new StringBuilder(num);
			StringWriter writer = null;
			char[] buffer = null;
			if (positions != null)
			{
				foreach (JsonPosition position in positions)
				{
					position.WriteTo(stringBuilder, ref writer, ref buffer);
				}
			}
			currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer);
			return stringBuilder.ToString();
		}

		internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message)
		{
			if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
			{
				message = message.Trim();
				if (!StringUtils.EndsWith(message, '.'))
				{
					message += ".";
				}
				message += " ";
			}
			message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
			}
			message += ".";
			return message;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonPropertyAttribute : Attribute
	{
		internal NullValueHandling? _nullValueHandling;

		internal DefaultValueHandling? _defaultValueHandling;

		internal ReferenceLoopHandling? _referenceLoopHandling;

		internal ObjectCreationHandling? _objectCreationHandling;

		internal TypeNameHandling? _typeNameHandling;

		internal bool? _isReference;

		internal int? _order;

		internal Required? _required;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType { get; set; }

		public object[]? NamingStrategyParameters { get; set; }

		public NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling.GetValueOrDefault();
			}
			set
			{
				_nullValueHandling = value;
			}
		}

		public DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling.GetValueOrDefault();
			}
			set
			{
				_defaultValueHandling = value;
			}
		}

		public ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_referenceLoopHandling = value;
			}
		}

		public ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling.GetValueOrDefault();
			}
			set
			{
				_objectCreationHandling = value;
			}
		}

		public TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameHandling = value;
			}
		}

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public int Order
		{
			get
			{
				return _order.GetValueOrDefault();
			}
			set
			{
				_order = value;
			}
		}

		public Required Required
		{
			get
			{
				return _required.GetValueOrDefault();
			}
			set
			{
				_required = value;
			}
		}

		public string? PropertyName { get; set; }

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public JsonPropertyAttribute()
		{
		}

		public JsonPropertyAttribute(string propertyName)
		{
			PropertyName = propertyName;
		}
	}
	public abstract class JsonReader : IDisposable
	{
		protected internal enum State
		{
			Start,
			Complete,
			Property,
			ObjectStart,
			Object,
			ArrayStart,
			Array,
			Closed,
			PostValue,
			ConstructorStart,
			Constructor,
			Error,
			Finished
		}

		private JsonToken _tokenType;

		private object? _value;

		internal char _quoteChar;

		internal State _currentState;

		private JsonPosition _currentPosition;

		private CultureInfo? _culture;

		private DateTimeZoneHandling _dateTimeZoneHandling;

		private int? _maxDepth;

		private bool _hasExceededMaxDepth;

		internal DateParseHandling _dateParseHandling;

		internal FloatParseHandling _floatParseHandling;

		private string? _dateFormatString;

		private List<JsonPosition>? _stack;

		protected State CurrentState => _currentState;

		public bool CloseInput { get; set; }

		public bool SupportMultipleContent { get; set; }

		public virtual char QuoteChar
		{
			get
			{
				return _quoteChar;
			}
			protected internal set
			{
				_quoteChar = value;
			}
		}

		public DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling;
			}
			set
			{
				if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateTimeZoneHandling = value;
			}
		}

		public DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling;
			}
			set
			{
				if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateParseHandling = value;
			}
		}

		public FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling;
			}
			set
			{
				if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_floatParseHandling = value;
			}
		}

		public string? DateFormatString
		{
			get
			{
				return _dateFormatString;
			}
			set
			{
				_dateFormatString = value;
			}
		}

		public int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
			}
		}

		public virtual JsonToken TokenType => _tokenType;

		public virtual object? Value => _value;

		public virtual Type? ValueType => _value?.GetType();

		public virtual int Depth
		{
			get
			{
				int num = _stack?.Count ?? 0;
				if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
				{
					return num;
				}
				return num + 1;
			}
		}

		public virtual string Path
		{
			get
			{
				if (_currentPosition.Type == JsonContainerType.None)
				{
					return string.Empty;
				}
				JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null);
				return JsonPosition.BuildPath(_stack, currentPosition);
			}
		}

		public CultureInfo Culture
		{
			get
			{
				return _culture ?? CultureInfo.InvariantCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync();
		}

		public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (TokenType == JsonToken.PropertyName)
			{
				await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth)
				{
				}
			}
		}

		internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken)
		{
			if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
			{
				throw CreateUnexpectedEndException();
			}
		}

		public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean());
		}

		public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes());
		}

		internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken)
		{
			List<byte> buffer = new List<byte>();
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(buffer));
			byte[] d = buffer.ToArray();
			SetToken(JsonToken.Bytes, d, updateIndex: false);
			return d;
		}

		public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime());
		}

		public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset());
		}

		public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal());
		}

		public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return Task.FromResult(ReadAsDouble());
		}

		public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32());
		}

		public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString());
		}

		internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken)
		{
			bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (flag)
			{
				flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			return flag;
		}

		internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType = TokenType;
			JsonToken jsonToken = tokenType;
			if (jsonToken == JsonToken.None || jsonToken == JsonToken.Comment)
			{
				return MoveToContentFromNonContentAsync(cancellationToken);
			}
			return AsyncUtils.True;
		}

		private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken)
		{
			JsonToken jsonToken2;
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					return false;
				}
				JsonToken tokenType = TokenType;
				JsonToken jsonToken = tokenType;
				jsonToken2 = jsonToken;
			}
			while (jsonToken2 == JsonToken.None || jsonToken2 == JsonToken.Comment);
			return true;
		}

		internal JsonPosition GetPosition(int depth)
		{
			if (_stack != null && depth < _stack.Count)
			{
				return _stack[depth];
			}
			return _currentPosition;
		}

		protected JsonReader()
		{
			_currentState = State.Start;
			_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
			_dateParseHandling = DateParseHandling.DateTime;
			_floatParseHandling = FloatParseHandling.Double;
			_maxDepth = 64;
			CloseInput = true;
		}

		private void Push(JsonContainerType value)
		{
			UpdateScopeWithFinishedValue();
			if (_currentPosition.Type == JsonContainerType.None)
			{
				_currentPosition = new JsonPosition(value);
				return;
			}
			if (_stack == null)
			{
				_stack = new List<JsonPosition>();
			}
			_stack.Add(_currentPosition);
			_currentPosition = new JsonPosition(value);
			if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth)
			{
				return;
			}
			_hasExceededMaxDepth = true;
			throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
		}

		private JsonContainerType Pop()
		{
			JsonPosition currentPosition;
			if (_stack != null && _stack.Count > 0)
			{
				currentPosition = _currentPosition;
				_currentPosition = _stack[_stack.Count - 1];
				_stack.RemoveAt(_stack.Count - 1);
			}
			else
			{
				currentPosition = _currentPosition;
				_currentPosition = default(JsonPosition);
			}
			if (_maxDepth.HasValue && Depth <= _maxDepth)
			{
				_hasExceededMaxDepth = false;
			}
			return currentPosition.Type;
		}

		private JsonContainerType Peek()
		{
			return _currentPosition.Type;
		}

		public abstract bool Read();

		public virtual int? ReadAsInt32()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is int value2)
				{
					return value2;
				}
				int num;
				if (value is BigInteger bigInteger)
				{
					num = (int)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToInt32(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Integer, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadInt32String(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal int? ReadInt32String(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (int.TryParse(s, NumberStyles.Integer, Culture, out var result))
			{
				SetToken(JsonToken.Integer, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual string? ReadAsString()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.String:
				return (string)Value;
			default:
				if (JsonTokenUtils.IsPrimitiveToken(contentToken))
				{
					object value = Value;
					if (value != null)
					{
						string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture));
						SetToken(JsonToken.String, text, updateIndex: false);
						return text;
					}
				}
				throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		public virtual byte[]? ReadAsBytes()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.StartObject:
			{
				ReadIntoWrappedTypeObject();
				byte[] array3 = ReadAsBytes();
				ReaderReadAndAssert();
				if (TokenType != JsonToken.EndObject)
				{
					throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
				}
				SetToken(JsonToken.Bytes, array3, updateIndex: false);
				return array3;
			}
			case JsonToken.String:
			{
				string text = (string)Value;
				Guid g;
				byte[] array2 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray()));
				SetToken(JsonToken.Bytes, array2, updateIndex: false);
				return array2;
			}
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Bytes:
				if (Value is Guid guid)
				{
					byte[] array = guid.ToByteArray();
					SetToken(JsonToken.Bytes, array, updateIndex: false);
					return array;
				}
				return (byte[])Value;
			case JsonToken.StartArray:
				return ReadArrayIntoByteArray();
			default:
				throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal byte[] ReadArrayIntoByteArray()
		{
			List<byte> list = new List<byte>();
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(list));
			byte[] array = list.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer)
		{
			switch (TokenType)
			{
			case JsonToken.None:
				throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
			case JsonToken.Integer:
				buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
				return false;
			case JsonToken.EndArray:
				return true;
			case JsonToken.Comment:
				return false;
			default:
				throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		public virtual double? ReadAsDouble()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is double value2)
				{
					return value2;
				}
				double num = ((!(value is BigInteger bigInteger) || 1 == 0) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger));
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDoubleString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal double? ReadDoubleString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual bool? ReadAsBoolean()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				bool flag = ((!(Value is BigInteger bigInteger) || 1 == 0) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L));
				SetToken(JsonToken.Boolean, flag, updateIndex: false);
				return flag;
			}
			case JsonToken.String:
				return ReadBooleanString((string)Value);
			case JsonToken.Boolean:
				return (bool)Value;
			default:
				throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal bool? ReadBooleanString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (bool.TryParse(s, out var result))
			{
				SetToken(JsonToken.Boolean, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual decimal? ReadAsDecimal()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is decimal value2)
				{
					return value2;
				}
				decimal num;
				if (value is BigInteger bigInteger)
				{
					num = (decimal)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDecimalString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal decimal? ReadDecimalString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success)
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTime? ReadAsDateTime()
		{
			switch (GetContentToken())
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTimeOffset dateTimeOffset)
				{
					SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false);
				}
				return (DateTime)Value;
			case JsonToken.String:
				return ReadDateTimeString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		internal DateTime? ReadDateTimeString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTimeOffset? ReadAsDateTimeOffset()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTime dateTime)
				{
					SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false);
				}
				return (DateTimeOffset)Value;
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadDateTimeOffsetString(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal DateTimeOffset? ReadDateTimeOffsetString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		internal void ReaderReadAndAssert()
		{
			if (!Read())
			{
				throw CreateUnexpectedEndException();
			}
		}

		internal JsonReaderException CreateUnexpectedEndException()
		{
			return JsonReaderException.Create(this, "Unexpected end when reading JSON.");
		}

		internal void ReadIntoWrappedTypeObject()
		{
			ReaderReadAndAssert();
			if (Value != null && Value.ToString() == "$type")
			{
				ReaderReadAndAssert();
				if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
				{
					ReaderReadAndAssert();
					if (Value.ToString() == "$value")
					{
						return;
					}
				}
			}
			throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
		}

		public void Skip()
		{
			if (TokenType == JsonToken.PropertyName)
			{
				Read();
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (Read() && depth < Depth)
				{
				}
			}
		}

		protected void SetToken(JsonToken newToken)
		{
			SetToken(newToken, null, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value)
		{
			SetToken(newToken, value, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value, bool updateIndex)
		{
			_tokenType = newToken;
			_value = value;
			switch (newToken)
			{
			case JsonToken.StartObject:
				_currentState = State.ObjectStart;
				Push(JsonContainerType.Object);
				break;
			case JsonToken.StartArray:
				_currentState = State.ArrayStart;
				Push(JsonContainerType.Array);
				break;
			case JsonToken.StartConstructor:
				_currentState = State.ConstructorStart;
				Push(JsonContainerType.Constructor);
				break;
			case JsonToken.EndObject:
				ValidateEnd(JsonToken.EndObject);
				break;
			case JsonToken.EndArray:
				ValidateEnd(JsonToken.EndArray);
				break;
			case JsonToken.EndConstructor:
				ValidateEnd(JsonToken.EndConstructor);
				break;
			case JsonToken.PropertyName:
				_currentState = State.Property;
				_currentPosition.PropertyName = (string)value;
				break;
			case JsonToken.Raw:
			case JsonToken.Integer:
			case JsonToken.Float:
			case JsonToken.String:
			case JsonToken.Boolean:
			case JsonToken.Null:
			case JsonToken.Undefined:
			case JsonToken.Date:
			case JsonToken.Bytes:
				SetPostValueState(updateIndex);
				break;
			case JsonToken.Comment:
				break;
			}
		}

		internal void SetPostValueState(bool updateIndex)
		{
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
			if (updateIndex)
			{
				UpdateScopeWithFinishedValue();
			}
		}

		private void UpdateScopeWithFinishedValue()
		{
			if (_currentPosition.HasIndex)
			{
				_currentPosition.Position++;
			}
		}

		private void ValidateEnd(JsonToken endToken)
		{
			JsonContainerType jsonContainerType = Pop();
			if (GetTypeForCloseToken(endToken) != jsonContainerType)
			{
				throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType));
			}
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
		}

		protected void SetStateBasedOnCurrent()
		{
			JsonContainerType jsonContainerType = Peek();
			switch (jsonContainerType)
			{
			case JsonContainerType.Object:
				_currentState = State.Object;
				break;
			case JsonContainerType.Array:
				_currentState = State.Array;
				break;
			case JsonContainerType.Constructor:
				_currentState = State.Constructor;
				break;
			case JsonContainerType.None:
				SetFinished();
				break;
			default:
				throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType));
			}
		}

		private void SetFinished()
		{
			_currentState = ((!SupportMultipleContent) ? State.Finished : State.Start);
		}

		private JsonContainerType GetTypeForCloseToken(JsonToken token)
		{
			return token switch
			{
				JsonToken.EndObject => JsonContainerType.Object, 
				JsonToken.EndArray => JsonContainerType.Array, 
				JsonToken.EndConstructor => JsonContainerType.Constructor, 
				_ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), 
			};
		}

		void IDisposable.Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (_currentState != State.Closed && disposing)
			{
				Close();
			}
		}

		public virtual void Close()
		{
			_currentState = State.Closed;
			_tokenType = JsonToken.None;
			_value = null;
		}

		internal void ReadAndAssert()
		{
			if (!Read())
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter)
		{
			if (!ReadForType(contract, hasConverter))
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal bool ReadForType(JsonContract? contract, bool hasConverter)
		{
			if (hasConverter)
			{
				return Read();
			}
			switch (contract?.InternalReadType ?? ReadType.Read)
			{
			case ReadType.Read:
				return ReadAndMoveToContent();
			case ReadType.ReadAsInt32:
				ReadAsInt32();
				break;
			case ReadType.ReadAsInt64:
			{
				bool result = ReadAndMoveToContent();
				if (TokenType == JsonToken.Undefined)
				{
					throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long)));
				}
				return result;
			}
			case ReadType.ReadAsDecimal:
				ReadAsDecimal();
				break;
			case ReadType.ReadAsDouble:
				ReadAsDouble();
				break;
			case ReadType.ReadAsBytes:
				ReadAsBytes();
				break;
			case ReadType.ReadAsBoolean:
				ReadAsBoolean();
				break;
			case ReadType.ReadAsString:
				ReadAsString();
				break;
			case ReadType.ReadAsDateTime:
				ReadAsDateTime();
				break;
			case ReadType.ReadAsDateTimeOffset:
				ReadAsDateTimeOffset();
				break;
			default:
				throw new ArgumentOutOfRangeException();
			}
			return TokenType != JsonToken.None;
		}

		internal bool ReadAndMoveToContent()
		{
			return Read() && MoveToContent();
		}

		internal bool MoveToContent()
		{
			JsonToken tokenType = TokenType;
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				if (!Read())
				{
					return false;
				}
				tokenType = TokenType;
			}
			return true;
		}

		private JsonToken GetContentToken()
		{
			JsonToken tokenType;
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
					return JsonToken.None;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.Comment);
			return tokenType;
		}
	}
	[Serializable]
	public class JsonReaderException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonReaderException()
		{
		}

		public JsonReaderException(string message)
			: base(message)
		{
		}

		public JsonReaderException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public JsonReaderException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonReaderException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonReaderException(message, path, lineNumber, linePosition, ex);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonRequiredAttribute : Attribute
	{
	}
	[Serializable]
	public class JsonSerializationException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonSerializationException()
		{
		}

		public JsonSerializationException(string message)
			: base(message)
		{
		}

		public JsonSerializationException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public JsonSerializationException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonSerializationException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonSerializationException(message, path, lineNumber, linePosition, ex);
		}
	}
	public class JsonSerializer
	{
		internal TypeNameHandling _typeNameHandling;

		internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling;

		internal PreserveReferencesHandling _preserveReferencesHandling;

		internal ReferenceLoopHandling _referenceLoopHandling;

		internal MissingMemberHandling _missingMemberHandling;

		internal ObjectCreationHandling _objectCreationHandling;

		internal NullValueHandling _nullValueHandling;

		internal DefaultValueHandling _defaultValueHandling;

		internal ConstructorHandling _constructorHandling;

		internal MetadataPropertyHandling _metadataPropertyHandling;

		internal JsonConverterCollection? _converters;

		internal IContractResolver _contractResolver;

		internal ITraceWriter? _traceWriter;

		internal IEqualityComparer? _equalityComparer;

		internal ISerializationBinder _serializationBinder;

		internal StreamingContext _context;

		private IReferenceResolver? _referenceResolver;

		private Formatting? _formatting;

		private DateFormatHandling? _dateFormatHandling;

		private DateTimeZoneHandling? _dateTimeZoneHandling;

		private DateParseHandling? _dateParseHandling;

		private FloatFormatHandling? _floatFormatHandling;

		private FloatParseHandling? _floatParseHandling;

		private StringEscapeHandling? _stringEscapeHandling;

		private CultureInfo _culture;

		private int? _maxDepth;

		private bool _maxDepthSet;

		private bool? _checkAdditionalContent;

		private string? _dateFormatString;

		private bool _dateFormatStringSet;

		public virtual IReferenceResolver? ReferenceResolver
		{
			get
			{
				return GetReferenceResolver();
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Reference resolver cannot be null.");
				}
				_referenceResolver = value;
			}
		}

		[Obsolete("Binder is obsolete. Use SerializationBinder instead.")]
		public virtual SerializationBinder Binder
		{
			get
			{
				if (_serializationBinder is SerializationBinder result)
				{
					return result;
				}
				if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter)
				{
					return serializationBinderAdapter.SerializationBinder;
				}
				throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set.");
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value);
			}
		}

		public virtual ISerializationBinder SerializationBinder
		{
			get
			{
				return _serializationBinder;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = value;
			}
		}

		public virtual ITraceWriter? TraceWriter
		{
			get
			{
				return _traceWriter;
			}
			set
			{
				_traceWriter = value;
			}
		}

		public virtual IEqualityComparer? EqualityComparer
		{
			get
			{
				return _equalityComparer;
			}
			set
			{
				_equalityComparer = value;
			}
		}

		public virtual TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling;
			}
			set
			{
				if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameHandling = value;
			}
		}

		[Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")]
		public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
		{
			get
			{
				return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value;
			}
		}

		public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling
		{
			get
			{
				return _typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = value;
			}
		}

		public virtual PreserveReferencesHandling PreserveReferencesHandling
		{
			get
			{
				return _preserveReferencesHandling;
			}
			set
			{
				if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_preserveReferencesHandling = value;
			}
		}

		public virtual ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling;
			}
			set
			{
				if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_referenceLoopHandling = value;
			}
		}

		public virtual MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling;
			}
			set
			{
				if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_missingMemberHandling = value;
			}
		}

		public virtual NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling;
			}
			set
			{
				if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_nullValueHandling = value;
			}
		}

		public virtual DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling;
			}
			set
			{
				if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_defaultValueHandling = value;
			}
		}

		public virtual ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling;
			}
			set
			{
				if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_objectCreationHandling = value;
			}
		}

		public virtual ConstructorHandling ConstructorHandling
		{
			get
			{
				return _constructorHandling;
			}
			set
			{
				if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_constructorHandling = value;
			}
		}

		public virtual MetadataPropertyHandling MetadataPropertyHandling
		{
			get
			{
				return _metadataPropertyHandling;
			}
			set
			{
				if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_metadataPropertyHandling = value;
			}
		}

		public virtual JsonConverterCollection Converters
		{
			get
			{
				if (_converters == null)
				{
					_converters = new JsonConverterCollection();
				}
				return _converters;
			}
		}

		public virtual IContractResolver ContractResolver
		{
			get
			{
				return _contractResolver;
			}
			set
			{
				_contractResolver = value ?? DefaultContractResolver.Instance;
			}
		}

		public virtual StreamingContext Context
		{
			get
			{
				return _context;
			}
			set
			{
				_context = value;
			}
		}

		public virtual Formatting Formatting
		{
			get
			{
				return _formatting.GetValueOrDefault();
			}
			set
			{
				_formatting = value;
			}
		}

		public virtual DateFormatHandling DateFormatHandling
		{
			get
			{
				return _dateFormatHandling.GetValueOrDefault();
			}
			set
			{
				_dateFormatHandling = value;
			}
		}

		public virtual DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind;
			}
			set
			{
				_dateTimeZoneHandling = value;
			}
		}

		public virtual DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling ?? DateParseHandling.DateTime;
			}
			set
			{
				_dateParseHandling = value;
			}
		}

		public virtual FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling.GetValueOrDefault();
			}
			set
			{
				_floatParseHandling = value;
			}
		}

		public virtual FloatFormatHandling FloatFormatHandling
		{
			get
			{
				return _floatFormatHandling.GetValueOrDefault();
			}
			set
			{
				_floatFormatHandling = value;
			}
		}

		public virtual StringEscapeHandling StringEscapeHandling
		{
			get
			{
				return _stringEscapeHandling.GetValueOrDefault();
			}
			set
			{
				_stringEscapeHandling = value;
			}
		}

		public virtual string DateFormatString
		{
			get
			{
				return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
			}
			set
			{
				_dateFormatString = value;
				_dateFormatStringSet = true;
			}
		}

		public virtual CultureInfo Culture
		{
			get
			{
				return _culture ?? JsonSerializerSettings.DefaultCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
				_maxDepthSet = true;
			}
		}

		public virtual bool CheckAdditionalContent
		{
			get
			{
				return _checkAdditionalContent.GetValueOrDefault();
			}
			set
			{
				_checkAdditionalContent = value;
			}
		}

		public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error;

		internal bool IsCheckAdditionalContentSet()
		{
			return _checkAdditionalContent.HasValue;
		}

		public JsonSerializer()
		{
			_referenceLoopHandling = ReferenceLoopHandling.Error;
			_missingMemberHandling = MissingMemberHandling.Ignore;
			_nullValueHandling = NullValueHandling.Include;
			_defaultValueHandling = DefaultValueHandling.Include;
			_objectCreationHandling = ObjectCreationHandling.Auto;
			_preserveReferencesHandling = PreserveReferencesHandling.None;
			_constructorHandling = ConstructorHandling.Default;
			_typeNameHandling = TypeNameHandling.None;
			_metadataPropertyHandling = MetadataPropertyHandling.Default;
			_context = JsonSerializerSettings.DefaultContext;
			_serializationBinder = DefaultSerializationBinder.Instance;
			_culture = JsonSerializerSettings.DefaultCulture;
			_contractResolver = DefaultContractResolver.Instance;
		}

		public static JsonSerializer Create()
		{
			return new JsonSerializer();
		}

		public static JsonSerializer Create(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = Create();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		public static JsonSerializer CreateDefault()
		{
			JsonSerializerSettings settings = JsonConvert.DefaultSettings?.Invoke();
			return Create(settings);
		}

		public static JsonSerializer CreateDefault(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = CreateDefault();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings)
		{
			if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
			{
				for (int i = 0; i < settings.Converters.Count; i++)
				{
					serializer.Converters.Insert(i, settings.Converters[i]);
				}
			}
			if (settings._typeNameHandling.HasValue)
			{
				serializer.TypeNameHandling = settings.TypeNameHandling;
			}
			if (settings._metadataPropertyHandling.HasValue)
			{
				serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling;
			}
			if (settings._typeNameAssemblyFormatHandling.HasValue)
			{
				serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling;
			}
			if (settings._preserveReferencesHandling.HasValue)
			{
				serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
			}
			if (settings._referenceLoopHandling.HasValue)
			{
				serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
			}
			if (settings._missingMemberHandling.HasValue)
			{
				serializer.MissingMemberHandling = settings.MissingMemberHandling;
			}
			if (settings._objectCreationHandling.HasValue)
			{
				serializer.ObjectCreationHandling = settings.ObjectCreationHandling;
			}
			if (settings._nullValueHandling.HasValue)
			{
				serializer.NullValueHandling = settings.NullValueHandling;
			}
			if (settings._defaultValueHandling.HasValue)
			{
				serializer.DefaultValueHandling = settings.DefaultValueHandling;
			}
			if (settings._constructorHandling.HasValue)
			{
				serializer.ConstructorHandling = settings.ConstructorHandling;
			}
			if (settings._context.HasValue)
			{
				serializer.Context = settings.Context;
			}
			if (settings._checkAdditionalContent.HasValue)
			{
				serializer._checkAdditionalContent = settings._checkAdditionalContent;
			}
			if (settings.Error != null)
			{
				serializer.Error += settings.Error;
			}
			if (settings.ContractResolver != null)
			{
				serializer.ContractResolver = settings.ContractResolver;
			}
			if (settings.ReferenceResolverProvider != null)
			{
				serializer.ReferenceResolver = settings.ReferenceResolverProvider();
			}
			if (settings.TraceWriter != null)
			{
				serializer.TraceWriter = settings.TraceWriter;
			}
			if (settings.EqualityComparer != null)
			{
				serializer.EqualityComparer = settings.EqualityComparer;
			}
			if (settings.SerializationBinder != null)
			{
				serializer.SerializationBinder = settings.SerializationBinder;
			}
			if (settings._formatting.HasValue)
			{
				serializer._formatting = settings._formatting;
			}
			if (settings._dateFormatHandling.HasValue)
			{
				serializer._dateFormatHandling = settings._dateFormatHandling;
			}
			if (settings._dateTimeZoneHandling.HasValue)
			{
				serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling;
			}
			if (settings._dateParseHandling.HasValue)
			{
				serializer._dateParseHandling = settings._dateParseHandling;
			}
			if (settings._dateFormatStringSet)
			{
				serializer._dateFormatString = settings._dateFormatString;
				serializer._dateFormatStringSet = settings._dateFormatStringSet;
			}
			if (settings._floatFormatHandling.HasValue)
			{
				serializer._floatFormatHandling = settings._floatFormatHandling;
			}
			if (settings._floatParseHandling.HasValue)
			{
				serializer._floatParseHandling = settings._floatParseHandling;
			}
			if (settings._stringEscapeHandling.HasValue)
			{
				serializer._stringEscapeHandling = settings._stringEscapeHandling;
			}
			if (settings._culture != null)
			{
				serializer._culture = settings._culture;
			}
			if (settings._maxDepthSet)
			{
				serializer._maxDepth = settings._maxDepth;
				serializer._maxDepthSet = settings._maxDepthSet;
			}
		}

		[DebuggerStepThrough]
		public void Populate(TextReader reader, object target)
		{
			Populate(new JsonTextReader(reader), target);
		}

		[DebuggerStepThrough]
		public void Populate(JsonReader reader, object target)
		{
			PopulateInternal(reader, target);
		}

		internal virtual void PopulateInternal(JsonReader reader, object target)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			ValidationUtils.ArgumentNotNull(target, "target");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			JsonSerializerInternalReader jsonSerializerInternalReader = new JsonSerializerInternalReader(this);
			jsonSerializerInternalReader.Populate(traceJsonReader ?? reader, target);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader)
		{
			return Deserialize(reader, null);
		}

		[DebuggerStepThrough]
		public object? Deserialize(TextReader reader, Type objectType)
		{
			return Deserialize(new JsonTextReader(reader), objectType);
		}

		[DebuggerStepThrough]
		public T? Deserialize<T>(JsonReader reader)
		{
			return (T)Deserialize(reader, typeof(T));
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader, Type? objectType)
		{
			return DeserializeInternal(reader, objectType);
		}

		internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			JsonSerializerInternalReader jsonSerializerInternalReader = new JsonSerializerInternalReader(this);
			object result = jsonSerializerInternalReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
			return result;
		}

		internal void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString)
		{
			if (_culture != null && !_culture.Equals(reader.Culture))
			{
				previousCulture = reader.Culture;
				reader.Culture = _culture;
			}
			else
			{
				previousCulture = null;
			}
			if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling)
			{
				previousDateTimeZoneHandling = reader.DateTimeZoneHandling;
				reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault();
			}
			else
			{
				previousDateTimeZoneHandling = null;
			}
			if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling)
			{
				previousDateParseHandling = reader.DateParseHandling;
				reader.DateParseHandling = _dateParseHandling.GetValueOrDefault();
			}
			else
			{
				previousDateParseHandling = null;
			}
			if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling)
			{
				previousFloatParseHandling = reader.FloatParseHandling;
				reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault();
			}
			else
			{
				previousFloatParseHandling = null;
			}
			if (_maxDepthSet && reader.MaxDepth != _maxDepth)
			{
				previousMaxDepth = reader.MaxDepth;
				reader.MaxDepth = _maxDepth;
			}
			else
			{
				previousMaxDepth = null;
			}
			if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString)
			{
				previousDateFormatString = reader.DateFormatString;
				reader.DateFormatString = _dateFormatString;
			}
			else
			{
				previousDateFormatString = null;
			}
			if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver)
			{
				jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable();
			}
		}

		private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString)
		{
			if (previousCulture != null)
			{
				reader.Culture = previousCulture;
			}
			if (previousDateTimeZoneHandling.HasValue)
			{
				reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault();
			}
			if (previousDateParseHandling.HasValue)
			{
				reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault();
			}
			if (previousFloatParseHandling.HasValue)
			{
				reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault();
			}
			if (_maxDepthSet)
			{
				reader.MaxDepth = previousMaxDepth;
			}
			if (_dateFormatStringSet)
			{
				reader.DateFormatString = previousDateFormatString;
			}
			if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable())
			{
				jsonTextReader.PropertyNameTable = null;
			}
		}

		public void Serialize(TextWriter textWriter, object? value)
		{
			Serialize(new JsonTextWriter(textWriter), value);
		}

		public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType)
		{
			SerializeInternal(jsonWriter, value, objectType);
		}

		public void Serialize(TextWriter textWriter, object? value, Type objectType)
		{
			Serialize(new JsonTextWriter(textWriter), value, objectType);
		}

		public void Serialize(JsonWriter jsonWriter, object? value)
		{
			SerializeInternal(jsonWriter, value, null);
		}

		private TraceJsonReader CreateTraceJsonReader(JsonReader reader)
		{
			TraceJsonReader traceJsonReader = new TraceJsonReader(reader);
			if (reader.TokenType != 0)
			{
				traceJsonReader.WriteCurrentToken();
			}
			return traceJsonReader;
		}

		internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType)
		{
			ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter");
			Formatting? formatting = null;
			if (_formatting.HasValue && jsonWriter.Formatting != _formatting)
			{
				formatting = jsonWriter.Formatting;
				jsonWriter.Formatting = _formatting.GetValueOrDefault();
			}
			DateFormatHandling? dateFormatHandling = null;
			if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling)
			{
				dateFormatHandling = jsonWriter.DateFormatHandling;
				jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault();
			}
			DateTimeZoneHandling? dateTimeZoneHandling = null;
			if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling)
			{
				dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling;
				jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault();
			}
			FloatFormatHandling? floatFormatHandling = null;
			if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling)
			{
				floatFormatHandling = jsonWriter.FloatFormatHandling;
				jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault();
			}
			StringEscapeHandling? stringEscapeHandling = null;
			if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling)
			{
				stringEscapeHandling = jsonWriter.StringEscapeHandling;
				jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault();
			}
			CultureInfo cultureInfo = null;
			if (_culture != null && !_culture.Equals(jsonWriter.Culture))
			{
				cultureInfo = jsonWriter.Culture;
				jsonWriter.Culture = _culture;
			}
			string dateFormatString = null;
			if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString)
			{
				dateFormatString = jsonWriter.DateFormatString;
				jsonWriter.DateFormatString = _dateFormatString;
			}
			TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null);
			JsonSerializerInternalWriter jsonSerializerInternalWriter = new JsonSerializerInternalWriter(this);
			jsonSerializerInternalWriter.Serialize(traceJsonWriter ?? jsonWriter, value, objectType);
			if (traceJsonWriter != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null);
			}
			if (formatting.HasValue)
			{
				jsonWriter.Formatting = formatting.GetValueOrDefault();
			}
			if (dateFormatHandling.HasValue)
			{
				jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault();
			}
			if (dateTimeZoneHandling.HasValue)
			{
				jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault();
			}
			if (floatFormatHandling.HasValue)
			{
				jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault();
			}
			if (stringEscapeHandling.HasValue)
			{
				jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault();
			}
			if (_dateFormatStringSet)
			{
				jsonWriter.DateFormatString = dateFormatString;
			}
			if (cultureInfo != null)
			{
				jsonWriter.Culture = cultureInfo;
			}
		}

		internal IReferenceResolver GetReferenceResolver()
		{
			if (_referenceResolver == null)
			{
				_referenceResolver = new DefaultReferenceResolver();
			}
			return _referenceResolver;
		}

		internal JsonConverter? GetMatchingConverter(Type type)
		{
			return GetMatchingConverter(_converters, type);
		}

		internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType)
		{
			ValidationUtils.ArgumentNotNull(objectType, "objectType");
			if (converters != null)
			{
				for (int i = 0; i < converters.Count; i++)
				{
					JsonConverter jsonConverter = converters[i];
					if (jsonConverter.CanConvert(objectType))
					{
						return jsonConverter;
					}
				}
			}
			return null;
		}

		internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e)
		{
			this.Error?.Invoke(this, e);
		}
	}
	public class JsonSerializerSettings
	{
		internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error;

		internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore;

		internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include;

		internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include;

		internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto;

		internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None;

		internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default;

		internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None;

		internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default;

		internal static readonly StreamingContext DefaultContext;

		internal const Formatting DefaultFormatting = Formatting.None;

		internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat;

		internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;

		internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime;

		internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double;

		internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String;

		internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default;

		internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple;

		internal static readonly CultureInfo DefaultCulture;

		internal const bool DefaultCheckAdditionalContent = false;

		internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";

		internal const int DefaultMaxDepth = 64;

		internal Formatting? _formatting;

		internal DateFormatHandling? _dateFormatHandling;

		internal DateTimeZoneHandling? _dateTimeZoneHandling;

		internal DateParseHandling? _dateParseHandling;

		internal FloatFormatHandling? _floatFormatHandling;

		internal FloatParseHandling? _floatParseHandling;

		internal StringEscapeHandling? _stringEscapeHandling;

		internal CultureInfo? _culture;

		internal bool? _checkAdditionalContent;

		internal int? _maxDepth;

		internal bool _maxDepthSet;

		internal string? _dateFormatString;

		internal bool _dateFormatStringSet;

		internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling;

		internal DefaultValueHandling? _defaultValueHandling;

		internal PreserveReferencesHandling? _preserveReferencesHandling;

		internal NullValueHandling? _nullValueHandling;

		internal ObjectCreationHandling? _objectCreationHandling;

		internal MissingMemberHandling? _missingMemberHandling;

		internal ReferenceLoopHandling? _referenceLoopHandling;

		internal StreamingContext? _context;

		internal ConstructorHandling? _constructorHandling;

		internal TypeNameHandling? _typeNameHandling;

		internal MetadataPropertyHandling? _metadataPropertyHandling;

		public ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_referenceLoopHandling = value;
			}
		}

		public MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling.GetValueOrDefault();
			}
			set
			{
				_missingMemberHandling = value;
			}
		}

		public ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling.GetValueOrDefault();
			}
			set
			{
				_objectCreationHandling = value;
			}
		}

		public NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling.GetValueOrDefault();
			}
			set
			{
				_nullValueHandling = value;
			}
		}

		public DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling.GetValueOrDefault();
			}
			set
			{
				_defaultValueHandling = value;
			}
		}

		public IList<JsonConverter> Converters { get; set; }

		public PreserveReferencesHandling PreserveReferencesHandling
		{
			get
			{
				return _preserveReferencesHandling.GetValueOrDefault();
			}
			set
			{
				_preserveReferencesHandling = value;
			}
		}

		public TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameHandling = value;
			}
		}

		public MetadataPropertyHandling MetadataPropertyHandling
		{
			get
			{
				return _metadataPropertyHandling.GetValueOrDefault();
			}
			set
			{
				_metadataPropertyHandling = value;
			}
		}

		[Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")]
		public FormatterAssemblyStyle TypeNameAssemblyFormat
		{
			get
			{
				return (FormatterAssemblyStyle)TypeNameAssemblyFormatHandling;
			}
			set
			{
				TypeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value;
			}
		}

		public TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling
		{
			get
			{
				return _typeNameAssemblyFormatHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameAssemblyFormatHandling = value;
			}
		}

		public ConstructorHandling ConstructorHandling
		{
			get
			{
				return _constructorHandling.GetValueOrDefault();
			}
			set
			{
				_constructorHandling = value;
			}
		}

		public IContractResolver? ContractResolver { get; set; }

		public IEqualityComparer? EqualityComparer { get; set; }

		[Obsolete("ReferenceResolver property is obsolete. Use the ReferenceResolverProvider property to set the IReferenceResolver: settings.ReferenceResolverProvider = () => resolver")]
		public IReferenceResolver? ReferenceResolver
		{
			get
			{
				return ReferenceResolverProvider?.Invoke();
			}
			set
			{
				IReferenceResolver value2 = value;
				ReferenceResolverProvider = ((value2 != null) ? ((Func<IReferenceResolver>)(() => value2)) : null);
			}
		}

		public Func<IReferenceResolver?>? ReferenceResolverProvider { get; set; }

		public ITraceWriter? TraceWriter { get; set; }

		[Obsolete("Binder is obsolete. Use SerializationBinder instead.")]
		public SerializationBinder? Binder
		{
			get
			{
				if (SerializationBinder == null)
				{
					return null;
				}
				if (SerializationBinder is SerializationBinderAdapter serializationBinderAdapter)
				{
					return serializationBinderAdapter.SerializationBinder;
				}
				throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set.");
			}
			set
			{
				SerializationBinder = ((value == null) ? null : new SerializationBinderAdapter(value));
			}
		}

		public ISerializationBinder? SerializationBinder { get; set; }

		public EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error { get; set; }

		public StreamingContext Context
		{
			get
			{
				return _context ?? DefaultContext;
			}
			set
			{
				_context = value;
			}
		}

		public string DateFormatString
		{
			get
			{
				return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
			}
			set
			{
				_dateFormatString = value;
				_dateFormatStringSet = true;
			}
		}

		public int? MaxDepth
		{
			get
			{
				return _maxDepthSet ? _maxDepth : new int?(64);
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
				_maxDepthSet = true;
			}
		}

		public Formatting Formatting
		{
			get
			{
				return _formatting.GetValueOrDefault();
			}
			set
			{
				_formatting = value;
			}
		}

		public DateFormatHandling DateFormatHandling
		{
			get
			{
				return _dateFormatHandling.GetValueOrDefault();
			}
			set
			{
				_dateFormatHandling = value;
			}
		}

		public DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind;
			}
			set
			{
				_dateTimeZoneHandling = value;
			}
		}

		public DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling ?? DateParseHandling.DateT

Smushi_Archipelago\Smushi-AP-Client.dll

Decompiled 3 days 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.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Archipelago.MultiClient.Net;
using Archipelago.MultiClient.Net.Converters;
using Archipelago.MultiClient.Net.Enums;
using Archipelago.MultiClient.Net.Helpers;
using Archipelago.MultiClient.Net.MessageLog.Messages;
using Archipelago.MultiClient.Net.Models;
using Archipelago.MultiClient.Net.Packets;
using BepInEx;
using CMF;
using FMODUnity;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Rewired.Integration.UnityUI;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Playables;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("Smushi-AP-Client")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+9604eb7a027837d50560c55d50a42fac86228318")]
[assembly: AssemblyProduct("Smushi-AP-Client")]
[assembly: AssemblyTitle("Smushi-AP-Client")]
[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 Smushi_AP_Client
{
	public class APConsole : MonoBehaviour
	{
		[Serializable]
		public class LogEntry
		{
			public enum State
			{
				SlideIn,
				Hold,
				FadeOut
			}

			public State state;

			public float stateTimer;

			public float offsetY;

			public float baseY;

			public float animatedY;

			public TextMeshProUGUI text;

			public Image background;

			public string message;

			public string colorizedMessage;

			public float height = 28f;

			public LogEntry(string msg)
			{
				message = msg;
			}
		}

		private const float MessageHeight = 28f;

		private const float ConsoleHeight = 280f;

		private const float SlideInTime = 0.25f;

		private const float HoldTime = 3f;

		private const float FadeOutTime = 0.5f;

		private const float SlideInOffset = -50f;

		private const float FadeUpOffset = 20f;

		private const float PaddingX = 25f;

		private const float PaddingY = 25f;

		private const float MessageSpacing = 6f;

		public static TMP_FontAsset shumiFont;

		private static readonly Dictionary<string, string> KeywordColors = new Dictionary<string, string>
		{
			{ "red", "#fb0000" },
			{ "blue", "#205aff" },
			{ "green", "#35ff1c" },
			{ "orange", "#ff8224" },
			{ "purple", "#bd32ff" },
			{ "cyan", "#33feb1" },
			{ "white", "#ffffff" },
			{ "black", "#48507a" },
			{ "grey", "#898989" },
			{ "gray", "#898989" },
			{ "yellow", "#fff42b" },
			{ "pink", "#ff5cfc" },
			{ "archipelago", "#e597bd" },
			{ "energy spore", "#ceff15" },
			{ "wind essence", "#b679fa" },
			{ "leaf glider", "#28b123" },
			{ "essence of water", "#5590db" },
			{ "Firestarter kit", "#f96136" },
			{ "headlamp", "#f2ee5e" },
			{ "container of light", "#dbdca5" },
			{ "blade of power", "#ff1e7a" },
			{ "garden", "#78dc75" },
			{ "forest", "#ddb276" },
			{ "lake", "#87d0e4" },
			{ "grove", "#bca2e8" },
			{ "garden of spring", "#78dc75" },
			{ "forest of fall", "#ddb276" },
			{ "lake of bloom", "#87d0e4" },
			{ "grove of life", "#bca2e8" },
			{ "elder's home", "#bca2e8" },
			{ "snowy forest", "#cfddc7" },
			{ "smushi's home", "#f3c2c2" },
			{ "map", "#f3da9b" },
			{ "mycology journal", "#f3da9b" },
			{ "band of elasticity", "#ff8080" },
			{ "ancient relic", "#957556" },
			{ "tool of mining", "#8bb090" },
			{ "tool of writing", "#d1c450" },
			{ "hooks", "#b49285" },
			{ "blueberry", "#583de9" },
			{ "secret password", "#e00000" },
			{ "secret opener", "#d3a94c" },
			{ "old string", "#90775b" },
			{ "screwdriver", "#a7bfd1" },
			{ "band aid", "#fbc8b3" },
			{ "ring of love", "#ace2ff" },
			{ "ring of youth", "#7de54c" },
			{ "ring of truth", "#3049f0" },
			{ "ring of prosperity", "#e19a38" },
			{ "ring of spirit", "#973ff1" },
			{ "conch shell", "#d39c5e" },
			{ "sacred streamer", "#eeeadf" },
			{ "super spore", "#b5ff43" },
			{ "super essence", "#be7ffe" },
			{ "lotus flower", "#ffd7ec" },
			{ "amethyst shroomie", "#d586ff" },
			{ "strawberry shroomie", "#ff4e83" },
			{ "flower shroomie", "#f5ed91" },
			{ "sho bowl shroomie", "#f83737" },
			{ "verdant shroomie", "#3ed851" },
			{ "pelagic shroomie", "#55c6f5" },
			{ "honey shroomie", "#ffdf4f" },
			{ "sparkle shroomie", "#a5d0ea" },
			{ "clavaria shroomie", "#414fed" },
			{ "inkcap shroomie", "#60697e" },
			{ "sharp shroomie", "#fdf3de" },
			{ "precious shroomie", "#edd2d2" },
			{ "veiled shroomie", "#faa853" },
			{ "sacred shroomie", "#edc74a" },
			{ "purple augmenter", "#d586ff" },
			{ "strawberry augmenter", "#ff4e83" },
			{ "flower augmenter", "#f5ed91" },
			{ "secret augmenter", "#f83737" },
			{ "verdant augmenter", "#3ed851" },
			{ "pelagic augmenter", "#55c6f5" },
			{ "honey augmenter", "#ffdf4f" },
			{ "sparkle augmenter", "#a5d0ea" },
			{ "clavaria augmenter", "#414fed" },
			{ "ink augmenter", "#60697e" },
			{ "sharp augmenter", "#fdf3de" },
			{ "precious augmenter", "#edd2d2" },
			{ "veiled augmenter", "#faa853" },
			{ "sacred augmenter", "#edc74a" },
			{ "mustache", "#ba4f00" },
			{ "purple crystal", "#a88ded" },
			{ "smushi", "#ff95b5" },
			{ "chungy", "#d09efe" },
			{ "capybara", "#f8af64" }
		};

		private readonly Queue<Image> _backgroundPool = new Queue<Image>();

		private readonly Queue<LogEntry> _cachedEntries = new Queue<LogEntry>();

		private readonly Queue<TextMeshProUGUI> _textPool = new Queue<TextMeshProUGUI>();

		private readonly List<LogEntry> _visibleEntries = new List<LogEntry>();

		private readonly List<LogEntry> _historyEntries = new List<LogEntry>();

		private GameObject _historyPanel;

		private RectTransform _historyContent;

		private bool _showHistory;

		private ScrollRect _historyScrollRect;

		private RectTransform _historyViewport;

		private bool _rebuildHistoryDirty;

		private int _historyBuiltCount;

		private Transform _messageParent;

		private bool _showConsole = true;

		public static APConsole Instance { get; private set; }

		private void Update()
		{
			UpdateMessages(Time.deltaTime);
			TryAddNewMessages();
			if (Input.GetKeyDown((KeyCode)288))
			{
				ToggleConsole();
			}
			if (Input.GetKeyDown((KeyCode)289))
			{
				ToggleHistory();
			}
			if (_showHistory)
			{
				Cursor.lockState = (CursorLockMode)0;
				Cursor.visible = true;
			}
			if (_showHistory && _rebuildHistoryDirty)
			{
				_rebuildHistoryDirty = false;
				RebuildHistory();
			}
		}

		public static void Create()
		{
			//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
			if (!((Object)(object)Instance != (Object)null))
			{
				shumiFont = Resources.FindObjectsOfTypeAll<TMP_FontAsset>().First((TMP_FontAsset x) => ((Object)x).name == "Shumi Font Final");
				GameObject val = new GameObject("ArchipelagoConsoleUI");
				Object.DontDestroyOnLoad((Object)val);
				Instance = val.AddComponent<APConsole>();
				Instance.BuildUI();
				Instance.Log("Welcome to Smushi Come Home");
			}
		}

		private void UpdateMessages(float delta)
		{
			for (int num = _visibleEntries.Count - 1; num >= 0; num--)
			{
				LogEntry entry = _visibleEntries[num];
				if (AnimateEntry(entry, delta))
				{
					RecycleEntry(entry);
					_visibleEntries.RemoveAt(num);
					RecalculateBaseY();
				}
				else
				{
					UpdateEntryVisual(entry);
				}
			}
		}

		private void RecalculateBaseY()
		{
			float num = 0f;
			for (int num2 = _visibleEntries.Count - 1; num2 >= 0; num2--)
			{
				LogEntry logEntry = _visibleEntries[num2];
				logEntry.baseY = num;
				num += logEntry.height + 6f;
			}
		}

		private bool AnimateEntry(LogEntry entry, float delta)
		{
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			entry.stateTimer += delta;
			switch (entry.state)
			{
			case LogEntry.State.SlideIn:
			{
				float num3 = Mathf.Clamp01(entry.stateTimer / 0.25f);
				entry.offsetY = Mathf.Lerp(-50f, 0f, EaseOutQuad(num3));
				if (num3 >= 1f)
				{
					entry.state = LogEntry.State.Hold;
					entry.stateTimer = 0f;
				}
				break;
			}
			case LogEntry.State.Hold:
				entry.offsetY = 0f;
				if (entry.stateTimer >= 3f)
				{
					entry.state = LogEntry.State.FadeOut;
					entry.stateTimer = 0f;
				}
				break;
			case LogEntry.State.FadeOut:
			{
				float num = Mathf.Clamp01(entry.stateTimer / 0.5f);
				entry.offsetY = Mathf.Lerp(0f, 20f, num);
				float num2 = 1f - num;
				((Graphic)entry.text).color = new Color(1f, 1f, 1f, num2);
				((Graphic)entry.background).color = new Color(0f, 0f, 0f, 0.8f * num2);
				if (num >= 1f)
				{
					return true;
				}
				break;
			}
			}
			return false;
		}

		private static float EaseOutQuad(float x)
		{
			return 1f - (1f - x) * (1f - x);
		}

		private void TryAddNewMessages()
		{
			if (!_showHistory && _cachedEntries.Any())
			{
				int num = Mathf.FloorToInt(10f);
				if (_visibleEntries.Count < num)
				{
					LogEntry logEntry = _cachedEntries.Dequeue();
					logEntry.state = LogEntry.State.SlideIn;
					logEntry.stateTimer = 0f;
					logEntry.offsetY = -50f;
					logEntry.animatedY = logEntry.baseY + logEntry.offsetY;
					CreateEntryVisual(logEntry);
					_visibleEntries.Add(logEntry);
					RecalculateBaseY();
					logEntry.animatedY = logEntry.baseY + logEntry.offsetY;
				}
			}
		}

		private void AddHistoryEntryVisual(LogEntry entry)
		{
			//IL_002a: 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_0054: 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_0073: 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_00b7: 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_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: 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_012d: Unknown result type (might be due to invalid IL or missing references)
			Image background = GetBackground();
			((Component)background).transform.SetParent((Transform)(object)_historyContent, false);
			RectTransform rectTransform = ((Graphic)background).rectTransform;
			rectTransform.anchorMin = new Vector2(0f, 1f);
			rectTransform.anchorMax = new Vector2(1f, 1f);
			rectTransform.pivot = new Vector2(0.5f, 1f);
			rectTransform.anchoredPosition = Vector2.zero;
			rectTransform.sizeDelta = new Vector2(600f, 28f);
			TextMeshProUGUI text = GetText();
			RectTransform rectTransform2 = ((TMP_Text)text).rectTransform;
			((Transform)rectTransform2).SetParent(((Component)background).transform, false);
			rectTransform2.anchorMin = new Vector2(0f, 0f);
			rectTransform2.anchorMax = new Vector2(1f, 1f);
			rectTransform2.pivot = new Vector2(0f, 0.5f);
			rectTransform2.offsetMin = new Vector2(8f, 4f);
			rectTransform2.offsetMax = new Vector2(-8f, -4f);
			entry.text = text;
			entry.background = background;
			((Graphic)text).color = Color.white;
			((Graphic)background).color = new Color(0f, 0f, 0f, 0.8f);
			((TMP_Text)text).text = entry.colorizedMessage;
			Canvas.ForceUpdateCanvases();
			LayoutRebuilder.ForceRebuildLayoutImmediate(((TMP_Text)text).rectTransform);
			float preferredHeight = Mathf.Max(28f, ((TMP_Text)text).preferredHeight + 8f);
			LayoutElement val = ((Component)background).GetComponent<LayoutElement>();
			if (!Object.op_Implicit((Object)(object)val))
			{
				val = ((Component)background).gameObject.AddComponent<LayoutElement>();
			}
			val.preferredHeight = preferredHeight;
		}

		private void CreateEntryVisual(LogEntry entry)
		{
			//IL_002a: 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_0054: 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_0097: 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_00c1: 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)
			//IL_00ea: 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_0136: Unknown result type (might be due to invalid IL or missing references)
			Image background = GetBackground();
			((Component)background).transform.SetParent(_messageParent, false);
			RectTransform rectTransform = ((Graphic)background).rectTransform;
			rectTransform.anchorMin = new Vector2(0f, 0f);
			rectTransform.anchorMax = new Vector2(0f, 0f);
			rectTransform.pivot = new Vector2(0f, 0f);
			rectTransform.sizeDelta = new Vector2(600f, 28f);
			TextMeshProUGUI text = GetText();
			RectTransform rectTransform2 = ((TMP_Text)text).rectTransform;
			((Transform)rectTransform2).SetParent(((Component)background).transform, false);
			rectTransform2.anchorMin = new Vector2(0f, 0f);
			rectTransform2.anchorMax = new Vector2(1f, 1f);
			rectTransform2.pivot = new Vector2(0f, 0.5f);
			rectTransform2.offsetMin = new Vector2(8f, 4f);
			rectTransform2.offsetMax = new Vector2(-8f, -4f);
			entry.text = text;
			entry.background = background;
			((Graphic)text).color = new Color(1f, 1f, 1f, 1f);
			((Graphic)background).color = new Color(0f, 0f, 0f, 0.8f);
			UpdateEntryVisual(entry);
		}

		private void UpdateEntryVisual(LogEntry entry)
		{
			//IL_0040: 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)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			((TMP_Text)entry.text).text = entry.colorizedMessage;
			RectTransform rectTransform = ((Graphic)entry.background).rectTransform;
			float preferredHeight = ((TMP_Text)entry.text).preferredHeight;
			entry.height = Mathf.Max(28f, preferredHeight + 8f);
			rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, entry.height);
			float num = entry.baseY + entry.offsetY;
			entry.animatedY = Mathf.Lerp(entry.animatedY, num, Time.deltaTime * 12f);
			((Graphic)entry.background).rectTransform.anchoredPosition = new Vector2(0f, entry.animatedY);
		}

		private TextMeshProUGUI GetText()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			if (_textPool.Count > 0)
			{
				TextMeshProUGUI obj = _textPool.Dequeue();
				((Component)obj).gameObject.SetActive(true);
				return obj;
			}
			TextMeshProUGUI component = new GameObject("LogText", new Type[3]
			{
				typeof(RectTransform),
				typeof(CanvasRenderer),
				typeof(TextMeshProUGUI)
			}).GetComponent<TextMeshProUGUI>();
			((TMP_Text)component).fontSize = 19f;
			((Graphic)component).color = Color.white;
			((TMP_Text)component).font = shumiFont;
			((TMP_Text)component).wordSpacing = 20f;
			((TMP_Text)component).alignment = (TextAlignmentOptions)4097;
			return component;
		}

		private Image GetBackground()
		{
			//IL_002b: 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 (_backgroundPool.Count > 0)
			{
				Image obj = _backgroundPool.Dequeue();
				((Component)obj).gameObject.SetActive(true);
				return obj;
			}
			Image obj2 = new GameObject("LogBG").AddComponent<Image>();
			((Graphic)obj2).color = new Color(0f, 0f, 0f, 0.8f);
			obj2.type = (Type)1;
			return obj2;
		}

		private void RecycleEntry(LogEntry entry)
		{
			((Component)entry.text).gameObject.SetActive(false);
			((Component)entry.background).gameObject.SetActive(false);
			_textPool.Enqueue(entry.text);
			_backgroundPool.Enqueue(entry.background);
			entry.text = null;
			entry.background = null;
		}

		private string Colorize(string input)
		{
			if (string.IsNullOrEmpty(input))
			{
				return input;
			}
			List<string> list = Tokenize(input);
			ApplyMultiWordColoring(list);
			ApplySingleWordColoring(list);
			return string.Concat(list);
		}

		private List<string> Tokenize(string input)
		{
			List<string> list = new List<string>();
			StringBuilder stringBuilder = new StringBuilder();
			if (string.IsNullOrEmpty(input))
			{
				return list;
			}
			bool flag = IsWordChar(input[0]);
			foreach (char c2 in input)
			{
				bool num = IsWordChar(c2);
				if (num != flag)
				{
					list.Add(stringBuilder.ToString());
					stringBuilder.Clear();
				}
				stringBuilder.Append(c2);
				flag = num;
			}
			if (stringBuilder.Length > 0)
			{
				list.Add(stringBuilder.ToString());
			}
			return list;
			static bool IsWordChar(char c)
			{
				if (!char.IsLetterOrDigit(c))
				{
					return c == '\'';
				}
				return true;
			}
		}

		private void ApplySingleWordColoring(List<string> tokens)
		{
			Dictionary<string, string> dictionary = KeywordColors.Where((KeyValuePair<string, string> kvp) => !kvp.Key.Contains(" ")).ToDictionary((KeyValuePair<string, string> kvp) => kvp.Key, (KeyValuePair<string, string> kvp) => kvp.Value);
			for (int i = 0; i < tokens.Count; i++)
			{
				string text = tokens[i];
				if (IsWord(text))
				{
					string key = text.ToLowerInvariant();
					if (dictionary.TryGetValue(key, out var value))
					{
						tokens[i] = "<color=" + value + ">" + text + "</color>";
					}
				}
			}
		}

		private void ApplyMultiWordColoring(List<string> tokens)
		{
			var list = (from kvp in KeywordColors
				where kvp.Key.Contains(" ")
				select new
				{
					Words = kvp.Key.Split(new char[1] { ' ' }),
					Color = kvp.Value
				} into kvp
				orderby kvp.Words.Length descending
				select kvp).ToList();
			if (list.Count == 0 || tokens.Count == 0)
			{
				return;
			}
			List<int> list2 = new List<int>();
			for (int i = 0; i < tokens.Count; i++)
			{
				if (IsWord(tokens[i]))
				{
					list2.Add(i);
				}
			}
			int num = 0;
			while (num < list2.Count)
			{
				bool flag = false;
				foreach (var item in list)
				{
					int num2 = item.Words.Length;
					if (num + num2 > list2.Count)
					{
						continue;
					}
					bool flag2 = true;
					for (int j = 0; j < num2; j++)
					{
						if (!tokens[list2[num + j]].Equals(item.Words[j], StringComparison.InvariantCultureIgnoreCase))
						{
							flag2 = false;
							break;
						}
					}
					if (flag2)
					{
						int num3 = list2[num];
						int num4 = list2[num + num2 - 1];
						string text = string.Concat(tokens.Skip(num3).Take(num4 - num3 + 1));
						tokens[num3] = "<color=" + item.Color + ">" + text + "</color>";
						for (int k = num3 + 1; k <= num4; k++)
						{
							tokens[k] = string.Empty;
						}
						num += num2;
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					num++;
				}
			}
		}

		private bool IsWord(string token)
		{
			if (string.IsNullOrEmpty(token))
			{
				return false;
			}
			bool result = false;
			for (int i = 0; i < token.Length; i++)
			{
				char c = token[i];
				if (char.IsLetterOrDigit(c))
				{
					result = true;
					continue;
				}
				if (c != '\'' || i <= 0 || i >= token.Length - 1)
				{
					return false;
				}
				if (!char.IsLetterOrDigit(token[i - 1]) || !char.IsLetterOrDigit(token[i + 1]))
				{
					return false;
				}
			}
			return result;
		}

		public void Log(string text)
		{
			LogEntry logEntry = new LogEntry(text);
			logEntry.colorizedMessage = Colorize(text);
			if (_showHistory)
			{
				_historyEntries.Add(new LogEntry(text)
				{
					colorizedMessage = logEntry.colorizedMessage
				});
				_rebuildHistoryDirty = true;
			}
			else
			{
				_cachedEntries.Enqueue(logEntry);
				_historyEntries.Add(new LogEntry(text)
				{
					colorizedMessage = logEntry.colorizedMessage
				});
			}
		}

		private void ToggleHistory()
		{
			_showHistory = !_showHistory;
			((Component)_messageParent).gameObject.SetActive(!_showHistory);
			_historyPanel.SetActive(_showHistory);
			if (_showHistory)
			{
				foreach (LogEntry visibleEntry in _visibleEntries)
				{
					if ((Object)(object)visibleEntry.text != (Object)null)
					{
						((Component)visibleEntry.text).gameObject.SetActive(false);
					}
					if ((Object)(object)visibleEntry.background != (Object)null)
					{
						((Component)visibleEntry.background).gameObject.SetActive(false);
					}
					_textPool.Enqueue(visibleEntry.text);
					_backgroundPool.Enqueue(visibleEntry.background);
					visibleEntry.text = null;
					visibleEntry.background = null;
				}
				_visibleEntries.Clear();
				_cachedEntries.Clear();
				RebuildHistory();
			}
			else
			{
				Cursor.lockState = (CursorLockMode)1;
				Cursor.visible = false;
				((Component)_messageParent).gameObject.SetActive(_showConsole);
			}
		}

		private void ToggleConsole()
		{
			_showConsole = !_showConsole;
			foreach (LogEntry visibleEntry in _visibleEntries)
			{
				if ((Object)(object)visibleEntry.background != (Object)null)
				{
					((Component)visibleEntry.background).gameObject.SetActive(_showConsole);
				}
				if ((Object)(object)visibleEntry.text != (Object)null)
				{
					((Component)visibleEntry.text).gameObject.SetActive(_showConsole);
				}
			}
			((Component)_messageParent).gameObject.SetActive(_showConsole);
			if (!_showConsole)
			{
				_showHistory = false;
				_historyPanel.SetActive(false);
			}
		}

		private void BuildUI()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0077: 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_009f: Expected O, but got Unknown
			//IL_00c6: 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_00cf: 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_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: 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
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: 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_0183: 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)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Expected O, but got Unknown
			//IL_0253: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: 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_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fa: 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_031e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0333: Unknown result type (might be due to invalid IL or missing references)
			//IL_0348: 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_0368: 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)
			GameObject val = new GameObject("APConsoleCanvas", new Type[3]
			{
				typeof(Canvas),
				typeof(CanvasScaler),
				typeof(GraphicRaycaster)
			});
			val.transform.SetParent(((Component)this).transform);
			Canvas component = val.GetComponent<Canvas>();
			component.renderMode = (RenderMode)0;
			component.sortingOrder = 2000;
			CanvasScaler component2 = val.GetComponent<CanvasScaler>();
			component2.uiScaleMode = (ScaleMode)1;
			component2.referenceResolution = new Vector2(1920f, 1080f);
			GameObject val2 = new GameObject("Messages", new Type[1] { typeof(RectTransform) });
			RectTransform component3 = val2.GetComponent<RectTransform>();
			((Transform)component3).SetParent(val.transform, false);
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(0f, 0f);
			component3.pivot = val3;
			Vector2 anchorMin = (component3.anchorMax = val3);
			component3.anchorMin = anchorMin;
			component3.anchoredPosition = new Vector2(25f, 25f);
			_messageParent = val2.transform;
			_historyPanel = new GameObject("HistoryPanel", new Type[1] { typeof(RectTransform) });
			RectTransform component4 = _historyPanel.GetComponent<RectTransform>();
			((Transform)component4).SetParent(val.transform, false);
			component4.anchorMin = new Vector2(0f, 0f);
			component4.anchorMax = new Vector2(0f, 0f);
			component4.pivot = new Vector2(0f, 0f);
			component4.anchoredPosition = new Vector2(25f, 25f);
			component4.sizeDelta = new Vector2(600f, 280f);
			_historyPanel.SetActive(false);
			_historyScrollRect = _historyPanel.AddComponent<ScrollRect>();
			_historyScrollRect.horizontal = false;
			_historyScrollRect.vertical = true;
			_historyScrollRect.scrollSensitivity = 10f;
			_historyScrollRect.movementType = (MovementType)2;
			GameObject val5 = new GameObject("Viewport", new Type[3]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(Mask)
			});
			_historyViewport = val5.GetComponent<RectTransform>();
			val5.transform.SetParent(_historyPanel.transform, false);
			_historyViewport.anchorMin = Vector2.zero;
			_historyViewport.anchorMax = Vector2.one;
			_historyViewport.offsetMin = Vector2.zero;
			_historyViewport.offsetMax = Vector2.zero;
			Image component5 = val5.GetComponent<Image>();
			((Graphic)component5).color = Color.white;
			component5.type = (Type)0;
			((Graphic)component5).raycastTarget = true;
			val5.GetComponent<Mask>().showMaskGraphic = false;
			_historyScrollRect.viewport = _historyViewport;
			GameObject val6 = new GameObject("Content", new Type[3]
			{
				typeof(RectTransform),
				typeof(VerticalLayoutGroup),
				typeof(ContentSizeFitter)
			});
			RectTransform component6 = val6.GetComponent<RectTransform>();
			((Transform)component6).SetParent(val5.transform, false);
			component6.anchorMin = new Vector2(0f, 1f);
			component6.anchorMax = new Vector2(1f, 1f);
			component6.pivot = new Vector2(0.5f, 1f);
			component6.anchoredPosition = Vector2.zero;
			component6.sizeDelta = new Vector2(0f, 0f);
			VerticalLayoutGroup component7 = val6.GetComponent<VerticalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)component7).childForceExpandHeight = false;
			((HorizontalOrVerticalLayoutGroup)component7).childForceExpandWidth = true;
			((HorizontalOrVerticalLayoutGroup)component7).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)component7).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)component7).spacing = 8f;
			((LayoutGroup)component7).childAlignment = (TextAnchor)0;
			ContentSizeFitter component8 = val6.GetComponent<ContentSizeFitter>();
			component8.verticalFit = (FitMode)2;
			component8.horizontalFit = (FitMode)0;
			_historyScrollRect.content = component6;
			_historyContent = component6;
		}

		private void RebuildHistory()
		{
			if (!((Object)(object)_historyContent == (Object)null))
			{
				for (int i = _historyBuiltCount; i < _historyEntries.Count; i++)
				{
					AddHistoryEntryVisual(_historyEntries[i]);
				}
				_historyBuiltCount = _historyEntries.Count;
				Canvas.ForceUpdateCanvases();
				LayoutRebuilder.ForceRebuildLayoutImmediate(_historyContent);
				Canvas.ForceUpdateCanvases();
				_historyScrollRect.verticalNormalizedPosition = 0f;
			}
		}
	}
	public class ArchipelagoHandler
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static MessageReceivedHandler <0>__OnMessageReceived;
		}

		private const string GameName = "Smushi Come Home";

		public static bool IsConnected;

		public static bool IsConnecting;

		public Action<string, string> OnConnect;

		private readonly ConcurrentQueue<long> _locationsToCheck = new ConcurrentQueue<long>();

		private readonly Random _random = new Random();

		private string _lastDeath;

		private LoginSuccessful _loginSuccessful;

		private ArchipelagoSession _session;

		public SlotData SlotData;

		public string Server { get; }

		public int Port { get; }

		public string Slot { get; }

		public string Password { get; }

		public string Seed { get; set; }

		private double SlotInstance { get; set; }

		public ArchipelagoHandler(string server, int port, string slot, string password)
		{
			Server = server;
			Port = port;
			Slot = slot;
			Password = password;
		}

		private void CreateSession()
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected O, but got Unknown
			//IL_0042: 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_004d: Expected O, but got Unknown
			SlotInstance = UnixTimeConverter.ToUnixTimeStamp(DateTime.Now);
			_session = ArchipelagoSessionFactory.CreateSession(Server, Port);
			IMessageLogHelper messageLog = _session.MessageLog;
			object obj = <>O.<0>__OnMessageReceived;
			if (obj == null)
			{
				MessageReceivedHandler val = OnMessageReceived;
				<>O.<0>__OnMessageReceived = val;
				obj = (object)val;
			}
			messageLog.OnMessageReceived += (MessageReceivedHandler)obj;
			_session.Socket.SocketClosed += new SocketClosedHandler(OnSocketClosed);
			_session.Items.ItemReceived += new ItemReceivedHandler(ItemReceived);
		}

		private void OnSocketClosed(string reason)
		{
			APConsole.Instance.Log("Connection closed (" + reason + ") Attempting reconnect...");
			IsConnected = false;
		}

		public void InitConnect()
		{
			IsConnecting = true;
			CreateSession();
			IsConnected = Connect();
			IsConnecting = false;
		}

		private bool Connect()
		{
			//IL_00e7: 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_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			Task<RoomInfoPacket> task = _session.ConnectAsync();
			object seed;
			if (task == null)
			{
				seed = null;
			}
			else
			{
				RoomInfoPacket result = task.Result;
				seed = ((result != null) ? result.SeedName : null);
			}
			Seed = (string)seed;
			LoginResult result2 = _session.LoginAsync("Smushi Come Home", Slot, (ItemsHandlingFlags)7, new Version(1, 0, 0), Array.Empty<string>(), (string)null, Password, true).Result;
			if (result2.Successful)
			{
				_loginSuccessful = (LoginSuccessful)result2;
				SlotData = new SlotData(_loginSuccessful.SlotData);
				PluginMain.GameHandler.InitOnConnect();
				ConnectionInfoHandler.Save(Server, Port.ToString(), Slot, Password);
				new Thread(RunCheckLocationsFromList).Start();
				OnConnect(Seed, Slot);
				return true;
			}
			LoginFailure val = (LoginFailure)result2;
			string text = Enumerable.Aggregate(seed: Enumerable.Aggregate(seed: $"Failed to Connect to {Server}:{Port} as {Slot}:", source: val.Errors, func: (string current, string error) => current + "\n    " + error), source: val.ErrorCodes, func: (string current, ConnectionRefusedError error) => current + $"\n    {error}");
			APConsole.Instance.Log(text);
			APConsole.Instance.Log("Attempting reconnect...");
			return false;
		}

		private void ItemReceived(ReceivedItemsHelper helper)
		{
			try
			{
				while (helper.Any())
				{
					int index = helper.Index;
					ItemInfo item = helper.DequeueItem();
					PluginMain.ItemHandler.HandleItem(index, item);
				}
			}
			catch (Exception arg)
			{
				APConsole.Instance.Log($"[ItemReceived ERROR] {arg}");
				throw;
			}
		}

		public void Release()
		{
			_session.SetGoalAchieved();
			_session.SetClientState((ArchipelagoClientState)30);
		}

		public void CheckLocations(long[] ids)
		{
			ids.ToList().ForEach(delegate(long id)
			{
				_locationsToCheck.Enqueue(id);
			});
		}

		public void CheckLocation(long id)
		{
			_locationsToCheck.Enqueue(id);
		}

		private void RunCheckLocationsFromList()
		{
			while (true)
			{
				if (_locationsToCheck.TryDequeue(out var result))
				{
					_session.Locations.CompleteLocationChecks(new long[1] { result });
				}
				else
				{
					Thread.Sleep(100);
				}
			}
		}

		public void Hint(long id)
		{
			_session.Hints.CreateHints((HintStatus)0, new long[1] { id });
		}

		public bool IsLocationChecked(long id)
		{
			return _session.Locations.AllLocationsChecked.Contains(id);
		}

		public int CountLocationsCheckedInRange(long start, long end)
		{
			return _session.Locations.AllLocationsChecked.Count((long loc) => loc >= start && loc < end);
		}

		public void UpdateTags(List<string> tags)
		{
			//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_001e: Expected O, but got Unknown
			ConnectUpdatePacket val = new ConnectUpdatePacket
			{
				Tags = tags.ToArray(),
				ItemsHandling = (ItemsHandlingFlags)7
			};
			_session.Socket.SendPacket((ArchipelagoPacketBase)(object)val);
		}

		private static void OnMessageReceived(LogMessage message)
		{
			APConsole.Instance.Log(((object)message).ToString() ?? string.Empty);
		}
	}
	public class ConnectionInfo
	{
		public string Server { get; set; }

		public string Port { get; set; }

		public string Slot { get; set; }

		public string Password { get; set; }
	}
	public class ConnectionInfoHandler
	{
		private static readonly string fileName = "connection_info.json";

		public static void Save(string server, string port, string slot, string password)
		{
			string contents = JsonConvert.SerializeObject((object)new ConnectionInfo
			{
				Server = server,
				Port = port,
				Slot = slot,
				Password = password
			});
			File.WriteAllText(Application.persistentDataPath + fileName, contents);
		}

		public static void Load(ref string server, ref string port, ref string slotName, ref string password)
		{
			if (!File.Exists(Application.persistentDataPath + fileName))
			{
				Save("archipelago.gg", "65535", "Player1", "");
			}
			ConnectionInfo connectionInfo = JsonConvert.DeserializeObject<ConnectionInfo>(File.ReadAllText(Application.persistentDataPath + fileName));
			server = connectionInfo.Server;
			port = connectionInfo.Port;
			slotName = connectionInfo.Slot;
			password = connectionInfo.Password;
		}
	}
	public class Data
	{
	}
	public class GameHandler : MonoBehaviour
	{
		[HarmonyPatch(typeof(HomeLevelSetup))]
		public class HomeLevelSetup_Patch
		{
			[HarmonyPatch("SetHomeOutro")]
			[HarmonyPostfix]
			public static void OnSetHomeOutro(HomeLevelSetup __instance)
			{
				if (PluginMain.ArchipelagoHandler.SlotData.Goal == Goal.SmushiGoHome)
				{
					PluginMain.ArchipelagoHandler.Release();
				}
				__instance.pd.hasBeatGame = false;
			}
		}

		[HarmonyPatch(typeof(ForestHeartCutscene))]
		public class ForestHeartCutscene_Patch
		{
			[HarmonyPatch("StartCutscene")]
			[HarmonyPrefix]
			public static bool StartCutscene(ForestHeartCutscene __instance)
			{
				((MonoBehaviour)__instance).StartCoroutine(SkipCutsceneSpeedrunner(__instance));
				return false;
			}

			public static IEnumerator SkipCutsceneSpeedrunner(ForestHeartCutscene __instance)
			{
				__instance.fade.FadeIn();
				yield return (object)new WaitForSeconds(2f);
				__instance.aug.SetActive(true);
				__instance.myceliumPostgame.SetActive(true);
				__instance.rosieAnim.SetBool("idleChange", true);
				__instance.heartAnim.Play("HealIdle");
				__instance.heartMat.color = __instance.heartColors[5];
				GameObject[] heartEffects = __instance.heartEffects;
				for (int i = 0; i < heartEffects.Length; i++)
				{
					heartEffects[i].SetActive(true);
				}
				__instance.ogElderNPC.SetActive(false);
				__instance.elderNPCs.SetActive(true);
				__instance.elderCutsceneModel.SetActive(false);
				__instance.playerCutsceneMode.SetActive(false);
				__instance.zone4Elder.SetActive(false);
				__instance.pd.solvedPuzzles.Add("forestHeartDone", value: false);
				__instance.player.position = __instance.playerPosTarget.position;
				__instance.playerModel.SetActive(true);
				__instance.fade.FadeOut();
				__instance.pd.dialogBools["heartHealed"] = true;
				yield return (object)new WaitForSeconds(1f);
				__instance.dtb.ResetDialogue();
				__instance.dialogueControls.SetActive(true);
				__instance.rosieAnim.SetBool("idleChange", true);
				__instance.achievementHandler.UnlockAchievement("forestHeart", 24);
				if (PluginMain.ArchipelagoHandler.SlotData.Goal == Goal.SmushiSaveTree)
				{
					PluginMain.ArchipelagoHandler.Release();
				}
			}
		}

		[HarmonyPatch(typeof(CapyActivator))]
		public class CapyActivator_Patch
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			public static void OnStart(CapyActivator __instance)
			{
				__instance.SetBoxTrigger(true);
			}
		}

		[HarmonyPatch(typeof(Capy1Manager))]
		public class Capy1Manager_Patch
		{
			[HarmonyPatch("MoveCapyToTarget")]
			[HarmonyPrefix]
			public static bool OnMoveCapyToTarget(Capy1Manager __instance, int index)
			{
				((MonoBehaviour)__instance).StartCoroutine(MoveCo(__instance, index));
				return false;
			}

			private static IEnumerator MoveCo(Capy1Manager manager, int index)
			{
				manager.capyRB.isKinematic = true;
				manager.activeIndex = index;
				yield return (object)new WaitForSeconds(0.2f);
				manager.capyTransform.position = manager.targetPositions[index].position;
				manager.capyRotation.rotation = manager.targetPositions[index].rotation;
			}
		}

		[HarmonyPatch(typeof(IslandDialogueTrigger))]
		public class IslandDialogueTrigger_Patch
		{
			private static IEnumerator CapyHijack1(IslandDialogueTrigger island)
			{
				island.SetStateWaitingForOrb();
				island.fader.FadeIn();
				yield return (object)new WaitForSeconds(1f);
				island.capyManager.MoveCapyToTarget(1);
				island.capySiblingDTB.ResetDialogue();
				yield return (object)new WaitForSeconds(0.3f);
				island.fader.FadeOut();
				island.capyManager.isTrackingCapy = false;
			}

			private static IEnumerator DismountHijack(IslandDialogueTrigger island)
			{
				yield return (object)new WaitForSeconds(2f);
				island.capyActivator.DisableUnmounting();
			}

			[HarmonyPatch("TriggerIslandIntroDialogue")]
			[HarmonyPostfix]
			private static void TriggerIslandIntroDialogue(IslandDialogueTrigger __instance)
			{
				((MonoBehaviour)__instance).StartCoroutine(DismountHijack(__instance));
			}

			[HarmonyPatch("EndIslandIntroCutscene")]
			[HarmonyPrefix]
			private static bool OnEndIslandIntroCutscene(IslandDialogueTrigger __instance)
			{
				if (__instance.coroutine2 != null)
				{
					((MonoBehaviour)__instance).StopCoroutine(__instance.coroutine2);
				}
				__instance.coroutine2 = ((MonoBehaviour)__instance).StartCoroutine(CapyHijack1(__instance));
				return false;
			}

			[HarmonyPatch("Start")]
			[HarmonyPrefix]
			private static bool OnStart(IslandDialogueTrigger __instance)
			{
				//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_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_0051: Expected I4, but got Unknown
				//IL_0073: 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_00f9: 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_009d: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_0120: 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_00cd: Unknown result type (might be due to invalid IL or missing references)
				//IL_014d: Unknown result type (might be due to invalid IL or missing references)
				__instance.hasTriggeredHint = __instance.pd.dialogBools["hasTriggeredHint"];
				__instance.hasTriggeredBeach = __instance.pd.dialogBools["hasTriggeredBeach"];
				SandIslandState currentIslandState = __instance.currentIslandState;
				switch (currentIslandState - 1)
				{
				case 0:
					__instance.capySiblingDTB.ResetDialogue();
					__instance.mountingTrigger.displayUI = true;
					if ((double)Vector3.Distance(__instance.player.position, __instance.targetPosition.position) > 1213.0 && (double)Vector3.Distance(__instance.player.position, __instance.targetPosition.position) < 1444.0)
					{
						__instance.player.position = __instance.targetPosition.position;
					}
					break;
				case 1:
					__instance.islandHandler.ActivateTier2Castles();
					__instance.mountingTrigger.displayUI = true;
					if ((double)Vector3.Distance(__instance.player.position, __instance.targetPosition.position) > 1213.0 && (double)Vector3.Distance(__instance.player.position, __instance.targetPosition.position) < 1444.0)
					{
						__instance.player.position = __instance.targetPosition.position;
					}
					break;
				case 2:
					__instance.capy3.SetActive(false);
					__instance.mountingTrigger.displayUI = true;
					__instance.islandHandler.SetupNPCs();
					break;
				}
				__instance.capySiblingDTB.TriggerDialogueAnim("build");
				__instance.mountingTrigger.displayUI = true;
				return false;
			}
		}

		[HarmonyPatch(typeof(IslandDockingZone))]
		public class IslandDockingZone_Patch
		{
			[HarmonyPatch("OnTriggerEnter")]
			[HarmonyPrefix]
			public static bool OnTriggerEnter(IslandDockingZone __instance, Collider other)
			{
				if (!((Component)other).CompareTag("capy") || !__instance.capyActivator.isActivated)
				{
					return false;
				}
				__instance.capyActivator.currentIslandIndex = __instance.islandIndex;
				__instance.capyActivator.EnableUnmounting();
				return false;
			}
		}

		[HarmonyPatch(typeof(IslandCaveDialogueTrigger))]
		public class IslandCaveDialogueTrigger_Patch
		{
			private static IEnumerator CapyHijack2(IslandCaveDialogueTrigger island)
			{
				island.currentIslandState = (CaveIslandState)3;
				island.fader.FadeIn();
				yield return (object)new WaitForSeconds(1f);
				island.capyManager.MoveCapyToTarget(3);
				island.capySiblingDTB.ResetDialogue();
				yield return (object)new WaitForSeconds(0.3f);
				island.fader.FadeOut();
				island.capyManager.isTrackingCapy = false;
			}

			private static IEnumerator DismountHijack(IslandCaveDialogueTrigger island)
			{
				yield return (object)new WaitForSeconds(2f);
				island.capyActivator.DisableUnmounting();
			}

			[HarmonyPatch("TriggerIslandIntroDialogue")]
			[HarmonyPostfix]
			private static void TriggerIslandIntroDialogue(IslandCaveDialogueTrigger __instance)
			{
				((MonoBehaviour)__instance).StartCoroutine(DismountHijack(__instance));
			}

			[HarmonyPatch("EndIslandIntroCutscene")]
			[HarmonyPrefix]
			private static bool OnEndIslandIntroCutscene(IslandCaveDialogueTrigger __instance)
			{
				if (__instance.coroutine2 != null)
				{
					((MonoBehaviour)__instance).StopCoroutine(__instance.coroutine2);
				}
				__instance.coroutine2 = ((MonoBehaviour)__instance).StartCoroutine(CapyHijack2(__instance));
				return false;
			}

			[HarmonyPatch("Start")]
			[HarmonyPrefix]
			private static bool OnStart(IslandCaveDialogueTrigger __instance)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Invalid comparison between Unknown and I4
				//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: Invalid comparison between Unknown and I4
				//IL_0051: 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_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_015b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0161: Invalid comparison between Unknown and I4
				//IL_00f8: 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_0078: 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_018a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0190: Invalid comparison between Unknown and I4
				//IL_011f: 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_00a7: 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 (__instance.pd.dialogBools["rescuedChungy"] && (int)__instance.currentIslandState != 5)
				{
					__instance.currentIslandState = (CaveIslandState)4;
				}
				if ((int)__instance.currentIslandState == 3)
				{
					((Collider)__instance.capyDTBCollider).enabled = true;
					__instance.mountTrigger.SetUnderwaterAssets(true);
					if ((double)Vector3.Distance(__instance.player.position, __instance.targetPosition.position) <= 140.0 || (double)Vector3.Distance(__instance.player.position, __instance.targetPosition.position) >= 1000.0)
					{
						return false;
					}
					__instance.player.position = __instance.targetPosition.position;
				}
				else if ((int)__instance.currentIslandState == 4)
				{
					__instance.melons.SetActive(true);
					__instance.chungy.SetActive(true);
					((Collider)__instance.capyDTBCollider).enabled = true;
					__instance.mountTrigger.SetUnderwaterAssets(true);
					if ((double)Vector3.Distance(__instance.player.position, __instance.targetPosition.position) <= 140.0 || (double)Vector3.Distance(__instance.player.position, __instance.targetPosition.position) >= 1000.0)
					{
						return false;
					}
					__instance.player.position = __instance.targetPosition.position;
				}
				else if ((int)__instance.currentIslandState == 5)
				{
					__instance.chungy.SetActive(false);
					__instance.capySiblingObject.SetActive(false);
					__instance.mountTrigger.displayUI = true;
				}
				else
				{
					if ((int)__instance.currentIslandState != 1)
					{
						return false;
					}
					__instance.capySiblingDTB.StartNodeName = "Capy2ChatNoDive";
					__instance.mountTrigger.displayUI = true;
				}
				return false;
			}

			[HarmonyPatch("SetIslandHasDiveNow")]
			[HarmonyPrefix]
			public static bool OnSetIslandHasDiveNow(IslandCaveDialogueTrigger __instance)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				__instance.currentIslandState = (CaveIslandState)2;
				__instance.mountTrigger.displayUI = true;
				((Collider)__instance.capyDTBCollider).enabled = false;
				__instance.capySiblingDTB.StartNodeName = "Capy2Chat";
				return false;
			}
		}

		[HarmonyPatch(typeof(InventoryManager))]
		public class InventoryManager_Patch
		{
			[HarmonyPatch("ListItems")]
			[HarmonyPrefix]
			public static bool OnListItems(InventoryManager __instance)
			{
				//IL_0014: 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_005a: Expected O, but got Unknown
				foreach (Component item in __instance.ItemContent)
				{
					Object.Destroy((Object)(object)item.gameObject);
				}
				int num = 0;
				foreach (Transform item2 in __instance.skinContent)
				{
					Transform val = item2;
					num++;
					if (num <= 1)
					{
						Debug.Log((object)"nothing");
					}
					else
					{
						Object.Destroy((Object)(object)((Component)val).gameObject);
					}
				}
				if (PluginMain.SaveDataHandler.CustomPlayerData.HasConch)
				{
					GameObject obj = Object.Instantiate<GameObject>(__instance.conchButton, __instance.ItemContent);
					((Component)obj.transform.Find("ItemIcon")).GetComponent<Image>();
					obj.SetActive(true);
				}
				foreach (Item item3 in __instance.Items)
				{
					GameObject obj2 = Object.Instantiate<GameObject>(__instance.InventoryItem, __instance.ItemContent);
					((Component)obj2.transform.Find("ItemIcon")).GetComponent<Image>().sprite = item3.icon;
					obj2.GetComponent<InventoryButtonBehavior>().itemType = item3;
				}
				__instance.ListSkins();
				__instance.ListPlayerTasks();
				return false;
			}
		}

		[HarmonyPatch(typeof(FlowerCollectingZone3))]
		public class FlowerCollectingZone3_Patch
		{
			[HarmonyPatch("Start")]
			[HarmonyPrefix]
			private static bool OnStart(FlowerCollectingZone3 __instance)
			{
				//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)
				__instance.islandTrigger = ((Component)__instance).GetComponent<SphereCollider>();
				__instance.rollingSFX = RuntimeManager.CreateInstance("event:/Island_Summon");
				__instance.islandObjects.SetActive(true);
				__instance.lotusPickups.SetActive(false);
				((Collider)__instance.islandTrigger).enabled = true;
				if (__instance.pd.solvedPuzzles.ContainsKey("lotusFlowerCapy"))
				{
					__instance.island.SetActive(true);
					__instance.islandAnim.Play("LotusCaveUP");
					__instance.mapIcon.SetActive(true);
					__instance.islandDocking.displayUI = true;
					__instance.lotusPickups.SetActive(false);
					GameObject[] flowerModels = __instance.flowerModels;
					for (int i = 0; i < flowerModels.Length; i++)
					{
						flowerModels[i].SetActive(true);
					}
				}
				else
				{
					CustomPlayerData customPlayerData = PluginMain.SaveDataHandler.CustomPlayerData;
					for (int j = 0; j < customPlayerData.LotusCount - customPlayerData.LotusCountCurrent; j++)
					{
						__instance.flowerModels[j].SetActive(true);
						__instance.flowerCountTotal++;
					}
				}
				return false;
			}

			[HarmonyPatch("OnTriggerEnter")]
			[HarmonyPrefix]
			private static bool OnTriggerEnter(FlowerCollectingZone3 __instance, Collider other)
			{
				if (!((Component)other).CompareTag("capy") || !__instance.capyActivator.isActivated || !__instance.isReset || PluginMain.SaveDataHandler.CustomPlayerData.LotusCountCurrent == 0)
				{
					return false;
				}
				__instance.isReset = false;
				__instance.AddFlowers();
				return false;
			}

			[HarmonyPatch("AddFlowers")]
			[HarmonyPrefix]
			public static bool AddFlowers(FlowerCollectingZone3 __instance)
			{
				//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)
				//IL_005c: Unknown result type (might be due to invalid IL or missing references)
				while (PluginMain.SaveDataHandler.CustomPlayerData.LotusCountCurrent > 0)
				{
					__instance.flowerModels[__instance.flowerCountTotal].SetActive(true);
					CustomPlayerData customPlayerData = PluginMain.SaveDataHandler.CustomPlayerData;
					int lotusCountCurrent = customPlayerData.LotusCountCurrent - 1;
					customPlayerData.LotusCountCurrent = lotusCountCurrent;
					__instance.flowerCountTotal++;
				}
				RuntimeManager.PlayOneShot(__instance.placeFX, default(Vector3));
				__instance.isReset = true;
				if (__instance.flowerCountTotal != 5)
				{
					return false;
				}
				((MonoBehaviour)__instance).StartCoroutine(__instance.SolveActivity());
				return false;
			}
		}

		[HarmonyPatch(typeof(InventoryUIManager))]
		public class InventoryUIManager_Patch
		{
			[HarmonyPatch("OpenConchUI")]
			[HarmonyPostfix]
			public static void OpenConchUI(InventoryUIManager __instance)
			{
				Button[] componentsInChildren = ((Component)__instance.conchUI.transform.Find("Level Buttons/Buttons")).GetComponentsInChildren<Button>();
				foreach (Button val in componentsInChildren)
				{
					switch (((Object)((Component)val).gameObject).name)
					{
					case "Home":
						((Component)val).gameObject.SetActive(PluginMain.SaveDataHandler.CustomPlayerData.HasGoneHome);
						break;
					case "Level 1":
						EventSystem.current.SetSelectedGameObject(((Component)val).gameObject);
						break;
					case "Level 2":
						((Component)val).gameObject.SetActive(PluginMain.SaveDataHandler.CustomPlayerData.HasGoneFall);
						break;
					case "Level 3":
						((Component)val).gameObject.SetActive(PluginMain.SaveDataHandler.CustomPlayerData.HasGoneLake);
						break;
					case "Level 5":
						((Component)val).gameObject.SetActive(PluginMain.SaveDataHandler.CustomPlayerData.HasGoneGrove);
						break;
					}
				}
			}
		}

		[HarmonyPatch(typeof(PlayerData))]
		public class PlayerData_Patch
		{
			[HarmonyPatch("Awake")]
			[HarmonyPostfix]
			public static void OnAwake(PlayerData __instance)
			{
				if (PluginMain.SaveDataHandler.CustomPlayerData.HasFaceThing)
				{
					((Component)((Component)__instance).transform.Find("ModelRoot/shroom player/Armature/Hip/LowerSpine/UpperSpine/Head/mustache")).gameObject.SetActive(true);
				}
			}

			[HarmonyPatch("AddShide")]
			[HarmonyPrefix]
			public static bool AddShide(PlayerData __instance)
			{
				return false;
			}

			[HarmonyPatch("AddRockCount")]
			[HarmonyPrefix]
			public static bool AddRockCount(PlayerData __instance)
			{
				__instance.rockCount += 2;
				__instance.achievements.UpdateCrystalCount();
				return false;
			}
		}

		[HarmonyPatch(typeof(PickupController))]
		public class PickupController_Patch
		{
			[HarmonyPatch("DropItem")]
			[HarmonyPostfix]
			public static void OnDropItem(PickupController __instance)
			{
				__instance.tpc.gliderEnabled = PluginMain.SaveDataHandler.CustomPlayerData.HasLeaf;
				((Behaviour)__instance.hook).enabled = PluginMain.SaveDataHandler.CustomPlayerData.HasHooks;
			}

			[HarmonyPatch("UnsetObjectOnPlayer")]
			[HarmonyPostfix]
			public static void UnsetObjectOnPlayer(PickupController __instance)
			{
				__instance.tpc.gliderEnabled = PluginMain.SaveDataHandler.CustomPlayerData.HasLeaf;
				((Behaviour)__instance.hook).enabled = PluginMain.SaveDataHandler.CustomPlayerData.HasHooks;
			}

			[HarmonyPatch("TeleportObjectOutOfPlayer")]
			[HarmonyPostfix]
			public static void TeleportObjectOutOfPlayer(PickupController __instance, Vector3 pos)
			{
				__instance.tpc.gliderEnabled = PluginMain.SaveDataHandler.CustomPlayerData.HasLeaf;
				((Behaviour)__instance.hook).enabled = PluginMain.SaveDataHandler.CustomPlayerData.HasHooks;
			}
		}

		[HarmonyPatch(typeof(WaterShrine))]
		public class WaterShrine_Patch
		{
			[HarmonyPatch("OnTriggerStay")]
			[HarmonyPrefix]
			private static bool OnTriggerStay(WaterShrine __instance, Collider other)
			{
				if ((((LayerMask)(ref __instance.playerLayer)).value & (1 << ((Component)other).gameObject.layer)) <= 0)
				{
					return false;
				}
				if (!__instance.UIPoppedUp && __instance.playerNearby)
				{
					__instance.UIPoppedUp = true;
					__instance.SetDialoguePopup(true);
				}
				if (((CharacterInput)__instance.tpcControls).IsNPCInteractPressed())
				{
					if (__instance.pd.hasWaterEssence && __instance.isSolved)
					{
						__instance.isSolved = true;
						__instance.ActivateWaterShrine();
					}
					else if (__instance.isHoldingShell && !__instance.isSolved)
					{
						__instance.pickupController.PlaceItem();
						__instance.shellModel.SetActive(true);
						__instance.isSolved = true;
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(__instance.RunHintDialogue());
					}
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(RingTradeInteraction))]
		public class RingTradeInteraction_Patch
		{
			[HarmonyPatch("AddRing")]
			[HarmonyPrefix]
			public static bool AddRing(string ringType)
			{
				return false;
			}
		}

		[HarmonyPatch(typeof(PlayerDialogue))]
		public class PlayerDialogue_Patch
		{
			[HarmonyPatch("ResetDialogue")]
			[HarmonyPrefix]
			public static bool ResetDialogue(PlayerDialogue __instance)
			{
				((MonoBehaviour)__instance).StartCoroutine(DelayedEnd(__instance));
				Debug.Log((object)"Dialogue reset");
				return false;
			}

			private static IEnumerator DelayedEnd(PlayerDialogue __instance)
			{
				yield return (object)new WaitForSeconds(0.3f);
				__instance.pauser.ResumePlayer();
				if (!__instance.tpc.IsHookEnabled())
				{
					__instance.tpc.SetHookComponent(true);
				}
				if (!__instance.tpc.gliderEnabled)
				{
					__instance.tpc.gliderEnabled = PluginMain.SaveDataHandler.CustomPlayerData.HasLeaf;
				}
			}
		}

		public void InitOnConnect()
		{
			SceneManager.sceneLoaded += SceneChanged;
		}

		public void SceneChanged(Scene scene, LoadSceneMode loadSceneMode)
		{
			switch (((Scene)(ref scene)).name)
			{
			case "Zone 2_F":
				PluginMain.SaveDataHandler.CustomPlayerData.HasGoneFall = true;
				break;
			case "Zone 3":
			{
				LevelTransition[] array = Object.FindObjectsOfType<LevelTransition>();
				foreach (LevelTransition val2 in array)
				{
					if (val2.SceneName == "Zone3 Cave")
					{
						val2.isCave = true;
					}
				}
				PluginMain.SaveDataHandler.CustomPlayerData.HasGoneLake = true;
				break;
			}
			case "Zone 4":
			{
				LevelTransition[] array = Object.FindObjectsOfType<LevelTransition>();
				foreach (LevelTransition val in array)
				{
					if (val.SceneName == "Zone4 Cave")
					{
						val.isCave = true;
					}
				}
				break;
			}
			case "Zone 5":
				PluginMain.SaveDataHandler.CustomPlayerData.HasGoneGrove = true;
				break;
			case "Home":
				PluginMain.SaveDataHandler.CustomPlayerData.HasGoneHome = true;
				break;
			}
			SaveLoadManager val3 = Object.FindObjectOfType<SaveLoadManager>();
			if (!((Object)(object)val3 == (Object)null))
			{
				SaveSystem._instance.SaveAllData(val3, true);
			}
		}
	}
	public class HintHandler
	{
		[HarmonyPatch(typeof(DialogueControls))]
		public class DialogueControls_Patch
		{
			[HarmonyPatch("SelectOption")]
			[HarmonyPrefix]
			public static void SelectOption(DialogueControls __instance)
			{
				GameObject currentSelectedGameObject = EventSystem.current.currentSelectedGameObject;
				if (!((Object)(object)currentSelectedGameObject == (Object)null))
				{
					TMP_Text componentInChildren = currentSelectedGameObject.GetComponentInChildren<TMP_Text>();
					string text = ((componentInChildren != null) ? componentInChildren.text : null);
					if (text != null && _validHints.TryGetValue(text, out var value))
					{
						PluginMain.ArchipelagoHandler.Hint(1792 + value);
					}
				}
			}
		}

		public static Dictionary<string, long> _validHints = new Dictionary<string, long>
		{
			{ "purple augmenter", 0L },
			{ "strawberry augmenter", 1L },
			{ "flower augmenter", 2L },
			{ "secret augmenter", 3L },
			{ "verdant augmenter", 4L },
			{ "pelagic augmenter", 5L },
			{ "honey augmenter", 6L },
			{ "sparkle augmenter", 7L },
			{ "clavaria augmenter", 8L },
			{ "ink augmenter", 9L },
			{ "sharp augmenter", 10L },
			{ "precious augmenter", 11L },
			{ "rainbow augmenter", 12L },
			{ "veiled augmenter", 13L },
			{ "sacred augmenter", 14L }
		};
	}
	public enum SCHItem
	{
		EnergySpore = 1,
		WindEssence = 2,
		LeafGlider = 3,
		ProgressiveHooks = 4,
		ToolOfMining = 5,
		ToolOfWriting = 6,
		BandOfElasticity = 7,
		BladeOfPower = 8,
		AncientRelic = 9,
		Blueberry = 10,
		MycologyJournal = 11,
		FirestarterKit = 12,
		SecretPassword = 13,
		ExplosivePowder = 14,
		ContainerOfLight = 15,
		Headlamp = 16,
		EssenceOfWater = 17,
		SecretOpener = 19,
		OldString = 20,
		Screwdriver = 21,
		BandAid = 22,
		RingOfLove = 23,
		RingOfYouth = 24,
		RingOfTruth = 25,
		RingOfProsperity = 26,
		RingOfSpirit = 27,
		ConchShell = 28,
		SacredStreamer = 29,
		SuperSpore = 30,
		SuperEssence = 31,
		LotusFlower = 32,
		AmethystShroomie = 257,
		StrawberryShroomie = 258,
		FlowerShroomie = 259,
		SHOBowlShroomie = 260,
		VerdantShroomie = 261,
		PelagicShroomie = 262,
		HoneyShroomie = 263,
		SparkleShroomie = 264,
		ClavariaShroomie = 265,
		InkcapShroomie = 266,
		SharpShroomie = 267,
		PreciousShroomie = 268,
		RainbowShroomie = 269,
		VeiledShroomie = 270,
		SacredShroomie = 271,
		PurpleCrystal = 512,
		SuperSecretFaceThing = 513
	}
	public class ItemHandler : MonoBehaviour
	{
		private Queue<(int, ItemInfo)> cachedItems;

		private bool TryGetHandlers(out SaveLoadManager manager, out PlayerData pd, out AdvancedWalkerController tpc, out InventoryManager inv)
		{
			manager = Object.FindObjectOfType<SaveLoadManager>();
			inv = Object.FindObjectOfType<InventoryManager>();
			if ((Object)(object)manager == (Object)null)
			{
				pd = null;
				tpc = null;
				return false;
			}
			pd = manager.pd;
			tpc = manager.tpc;
			if ((Object)(object)pd != (Object)null && (Object)(object)inv != (Object)null)
			{
				return (Object)(object)tpc != (Object)null;
			}
			return false;
		}

		private void Awake()
		{
			cachedItems = new Queue<(int, ItemInfo)>();
		}

		public void HandleItem(int index, ItemInfo item)
		{
			try
			{
				if (index < PluginMain.SaveDataHandler.CustomPlayerData.ItemIndex)
				{
					return;
				}
				if (!TryGetHandlers(out var manager, out var pd, out var tpc, out var inv))
				{
					cachedItems.Enqueue((index, item));
					return;
				}
				if (cachedItems.Count > 0)
				{
					FlushQueue(manager, pd, tpc, inv);
				}
				HandleItem(index, item, manager, pd, tpc, inv);
			}
			catch (Exception arg)
			{
				APConsole.Instance.Log($"[HandleItem ERROR] {arg}");
				throw;
			}
		}

		private void Update()
		{
			if (Input.GetKeyDown((KeyCode)286))
			{
				FlushQueue();
			}
		}

		private void FlushQueue()
		{
			if (TryGetHandlers(out var manager, out var pd, out var tpc, out var inv))
			{
				FlushQueue(manager, pd, tpc, inv);
			}
		}

		private void FlushQueue(SaveLoadManager manager, PlayerData playerData, AdvancedWalkerController movement, InventoryManager inventory)
		{
			while (cachedItems.Count > 0)
			{
				var (index, item) = cachedItems.Dequeue();
				HandleItem(index, item, manager, playerData, movement, inventory);
			}
		}

		private void HandleItem(int index, ItemInfo item, SaveLoadManager manager, PlayerData playerData, AdvancedWalkerController movement, InventoryManager inventory)
		{
			//IL_04c7: Unknown result type (might be due to invalid IL or missing references)
			CustomPlayerData customPlayerData = PluginMain.SaveDataHandler.CustomPlayerData;
			if (index < customPlayerData.ItemIndex)
			{
				return;
			}
			PluginMain.SaveDataHandler.CustomPlayerData.ItemIndex++;
			switch ((SCHItem)item.ItemId)
			{
			case SCHItem.EnergySpore:
			{
				playerData.AddSpore();
				movement.sprinterController.CheckSporeCount();
				Item val16 = Resources.Load<Item>("items/Spore");
				inventory.AddItem(val16);
				if (playerData.sporeCount >= 2 && playerData.sporeCount >= 2 && !playerData.hasSprint)
				{
					playerData.hasSprint = true;
				}
				break;
			}
			case SCHItem.WindEssence:
			{
				playerData.gliderStage++;
				Item val35 = Resources.Load<Item>("items/WindEssence");
				playerData.UpdateGliderStamina();
				inventory.AddItem(val35);
				break;
			}
			case SCHItem.LeafGlider:
			{
				customPlayerData.HasLeaf = true;
				movement.gliderEnabled = true;
				Item val20 = Resources.Load<Item>("items/Leaf");
				inventory.AddItem(val20);
				break;
			}
			case SCHItem.ProgressiveHooks:
				if (!customPlayerData.HasHooks)
				{
					customPlayerData.HasHooks = true;
					movement.hookEnabled = true;
					((Behaviour)movement.hookClimber).enabled = true;
					Item val36 = Resources.Load<Item>("items/Hooks");
					inventory.AddItem(val36);
				}
				else
				{
					playerData.climbStamina = 1f;
					movement.hookClimber.savedStamina = 1f;
					movement.hookClimber.stamina = 1f;
					movement.hookClimber.hasHookUpgrade = true;
					Item val37 = Resources.Load<Item>("items/Hooks2");
					inventory.AddItem(val37);
				}
				break;
			case SCHItem.ToolOfMining:
			{
				customPlayerData.HasHexKey = true;
				playerData.hasHexkey = true;
				Item val33 = Resources.Load<Item>("items/19_HexKey");
				inventory.AddItem(val33);
				break;
			}
			case SCHItem.ToolOfWriting:
			{
				playerData.dialogBools["hasPencil"] = true;
				Item val34 = Resources.Load<Item>("items/Pencil");
				inventory.AddItem(val34);
				break;
			}
			case SCHItem.BandOfElasticity:
			{
				playerData.dialogBools["rubberBand"] = true;
				Item val21 = Resources.Load<Item>("items/RubberBand");
				inventory.AddItem(val21);
				break;
			}
			case SCHItem.BladeOfPower:
			{
				playerData.hasNeedle = true;
				Item val22 = Resources.Load<Item>("items/Needle");
				inventory.AddItem(val22);
				break;
			}
			case SCHItem.AncientRelic:
				if (playerData.dialogBools["coin1"])
				{
					playerData.dialogBools["coin1"] = true;
					Item val44 = Resources.Load<Item>("items/Relic1");
					inventory.AddItem(val44);
				}
				else
				{
					playerData.dialogBools["coin2"] = true;
					Item val45 = Resources.Load<Item>("items/Relic2");
					inventory.AddItem(val45);
				}
				break;
			case SCHItem.Blueberry:
			{
				playerData.berryCount++;
				Item val43 = Resources.Load<Item>("items/Blueberry");
				inventory.AddItem(val43);
				break;
			}
			case SCHItem.MycologyJournal:
				playerData.hasJournal = true;
				break;
			case SCHItem.FirestarterKit:
			{
				playerData.hasFlint = true;
				Item val42 = Resources.Load<Item>("items/FlintSteel");
				inventory.AddItem(val42);
				break;
			}
			case SCHItem.SecretPassword:
			{
				playerData.dialogBools["knowsPass"] = true;
				Item val41 = Resources.Load<Item>("items/Password");
				inventory.AddItem(val41);
				break;
			}
			case SCHItem.ExplosivePowder:
			{
				playerData.AddPowderCount();
				Item val40 = Resources.Load<Item>("items/ExplosivePowder");
				inventory.AddItem(val40);
				break;
			}
			case SCHItem.ContainerOfLight:
			{
				playerData.dialogBools["lightbulb"] = true;
				Item val39 = Resources.Load<Item>("items/ChristmasLight");
				inventory.AddItem(val39);
				break;
			}
			case SCHItem.Headlamp:
			{
				playerData.hasHeadlamp = true;
				Item val38 = Resources.Load<Item>("items/Headlamp");
				inventory.AddItem(val38);
				break;
			}
			case SCHItem.EssenceOfWater:
			{
				playerData.hasWaterEssence = true;
				playerData.dialogBools["hasDiving"] = true;
				if (playerData.currentSceneName == "Zone 3")
				{
					Object.FindObjectOfType<IslandCaveDialogueTrigger>().SetIslandHasDiveNow();
				}
				if ((Object)(object)manager.caveIsland != (Object)null)
				{
					manager.caveIsland.currentIslandState = (CaveIslandState)2;
				}
				Item val32 = Resources.Load<Item>("items/WaterEssence");
				inventory.AddItem(val32);
				break;
			}
			case SCHItem.SecretOpener:
			{
				playerData.dialogBools["secretKey"] = true;
				Item val31 = Resources.Load<Item>("items/Key");
				inventory.AddItem(val31);
				break;
			}
			case SCHItem.OldString:
			{
				playerData.dialogBools["hasString"] = true;
				Item val30 = Resources.Load<Item>("items/21_String");
				inventory.AddItem(val30);
				break;
			}
			case SCHItem.Screwdriver:
			{
				playerData.hasScrewdriver = true;
				Item val29 = Resources.Load<Item>("items/forestheartitems/Screwdriver");
				inventory.AddItem(val29);
				break;
			}
			case SCHItem.BandAid:
			{
				playerData.dialogBools["hasBandaid"] = true;
				Item val28 = Resources.Load<Item>("items/forestheartitems/Bandaid");
				inventory.AddItem(val28);
				break;
			}
			case SCHItem.RingOfLove:
			{
				playerData.rings.Add("diamond", value: false);
				Item val27 = Resources.Load<Item>("items/forestheartitems/Ring_Diamond");
				inventory.AddItem(val27);
				break;
			}
			case SCHItem.RingOfYouth:
			{
				playerData.rings.Add("emerald", value: false);
				Item val26 = Resources.Load<Item>("items/forestheartitems/Ring_Emerald");
				inventory.AddItem(val26);
				break;
			}
			case SCHItem.RingOfTruth:
			{
				playerData.rings.Add("sapphire", value: false);
				Item val25 = Resources.Load<Item>("items/forestheartitems/Ring_Sapphire");
				inventory.AddItem(val25);
				break;
			}
			case SCHItem.RingOfProsperity:
			{
				playerData.rings.Add("citrine", value: false);
				Item val24 = Resources.Load<Item>("items/forestheartitems/Ring_Citrine");
				inventory.AddItem(val24);
				break;
			}
			case SCHItem.RingOfSpirit:
			{
				playerData.rings.Add("amethyst", value: false);
				Item val23 = Resources.Load<Item>("items/forestheartitems/Ring_Amethyst");
				inventory.AddItem(val23);
				break;
			}
			case SCHItem.ConchShell:
				customPlayerData.HasConch = true;
				break;
			case SCHItem.SacredStreamer:
				if (playerData.shideCountTotal < 4)
				{
					playerData.shideCount++;
					playerData.shideCountTotal++;
					ForestHeartCutscene forestHeart = playerData.forestHeart;
					if (forestHeart != null)
					{
						forestHeart.SetHeartState();
					}
					Item val19 = Resources.Load<Item>("items/forestheartitems/Shide");
					inventory.AddItem(val19);
				}
				break;
			case SCHItem.SuperSpore:
			{
				movement.sprinterController.hasSprintBoost = true;
				playerData.hasSprintBoost = true;
				Item val18 = Resources.Load<Item>("items/forestheartitems/SuperSpore");
				inventory.AddItem(val18);
				break;
			}
			case SCHItem.SuperEssence:
			{
				movement.hasGlideBoost = true;
				playerData.hasGlideBoost = true;
				Item val17 = Resources.Load<Item>("items/SuperEssence");
				inventory.AddItem(val17);
				break;
			}
			case SCHItem.LotusFlower:
				if (customPlayerData.LotusCount != 5)
				{
					int lotusCount = Math.Min(5, customPlayerData.LotusCount + 1);
					customPlayerData.LotusCount = lotusCount;
					customPlayerData.LotusCountCurrent = Math.Min(5, customPlayerData.LotusCountCurrent + 1);
				}
				break;
			case SCHItem.AmethystShroomie:
			{
				Skins val15 = Resources.Load<Skins>("skins/PurpleAugmenter");
				inventory.AddSkin(val15);
				inventory.CraftSkin(val15, val15.craftableSkin);
				break;
			}
			case SCHItem.StrawberryShroomie:
			{
				Skins val14 = Resources.Load<Skins>("skins/StrawberryAugmenter");
				inventory.AddSkin(val14);
				inventory.CraftSkin(val14, val14.craftableSkin);
				break;
			}
			case SCHItem.FlowerShroomie:
			{
				Skins val13 = Resources.Load<Skins>("skins/FlowerAugm");
				inventory.AddSkin(val13);
				inventory.CraftSkin(val13, val13.craftableSkin);
				break;
			}
			case SCHItem.SHOBowlShroomie:
			{
				Skins val12 = Resources.Load<Skins>("skins/OnionAugm");
				inventory.AddSkin(val12);
				inventory.CraftSkin(val12, val12.craftableSkin);
				break;
			}
			case SCHItem.VerdantShroomie:
			{
				Skins val11 = Resources.Load<Skins>("skins/GreenAugmenter");
				inventory.AddSkin(val11);
				inventory.CraftSkin(val11, val11.craftableSkin);
				break;
			}
			case SCHItem.PelagicShroomie:
			{
				Skins val10 = Resources.Load<Skins>("skins/BlueAugmenter");
				inventory.AddSkin(val10);
				inventory.CraftSkin(val10, val10.craftableSkin);
				break;
			}
			case SCHItem.HoneyShroomie:
			{
				Skins val9 = Resources.Load<Skins>("skins/HoneyAugmenter");
				inventory.AddSkin(val9);
				inventory.CraftSkin(val9, val9.craftableSkin);
				break;
			}
			case SCHItem.SparkleShroomie:
			{
				Skins val8 = Resources.Load<Skins>("skins/SparkleAug");
				inventory.AddSkin(val8);
				inventory.CraftSkin(val8, val8.craftableSkin);
				break;
			}
			case SCHItem.ClavariaShroomie:
			{
				Skins val7 = Resources.Load<Skins>("skins/SpikeyAug");
				inventory.AddSkin(val7);
				inventory.CraftSkin(val7, val7.craftableSkin);
				break;
			}
			case SCHItem.InkcapShroomie:
			{
				Skins val6 = Resources.Load<Skins>("skins/InkcapAugmenter");
				inventory.AddSkin(val6);
				inventory.CraftSkin(val6, val6.craftableSkin);
				break;
			}
			case SCHItem.SharpShroomie:
			{
				Skins val5 = Resources.Load<Skins>("skins/forestheartskins/SharpAug");
				inventory.AddSkin(val5);
				inventory.CraftSkin(val5, val5.craftableSkin);
				break;
			}
			case SCHItem.PreciousShroomie:
			{
				Skins val4 = Resources.Load<Skins>("skins/forestheartskins/CrystalAug");
				inventory.AddSkin(val4);
				inventory.CraftSkin(val4, val4.craftableSkin);
				break;
			}
			case SCHItem.RainbowShroomie:
			{
				Skins val3 = Resources.Load<Skins>("skins/forestheartskins/RainbowAug");
				inventory.AddSkin(val3);
				inventory.CraftSkin(val3, val3.craftableSkin);
				break;
			}
			case SCHItem.VeiledShroomie:
			{
				Skins val2 = Resources.Load<Skins>("skins/forestheartskins/VeilAug");
				inventory.AddSkin(val2);
				inventory.CraftSkin(val2, val2.craftableSkin);
				break;
			}
			case SCHItem.SacredShroomie:
			{
				Skins val = Resources.Load<Skins>("skins/forestheartskins/SacredAug");
				inventory.AddSkin(val);
				inventory.CraftSkin(val, val.craftableSkin);
				break;
			}
			case SCHItem.PurpleCrystal:
				playerData.AddSkin1Rock();
				break;
			case SCHItem.SuperSecretFaceThing:
				customPlayerData.HasFaceThing = true;
				((Component)((Component)playerData).transform.Find("ModelRoot/shroom player/Armature/Hip/LowerSpine/UpperSpine/Head/mustache")).gameObject.SetActive(true);
				break;
			default:
				throw new ArgumentOutOfRangeException();
			}
			SaveSystem._instance.SaveAllData(manager, true);
		}
	}
	public class ItemPreventionHandler
	{
		[HarmonyPatch(typeof(CoinPuzzleHandler))]
		public class CoinPuzzleHandler_Patch
		{
			[HarmonyPatch("SetCoinTrue")]
			[HarmonyPrefix]
			public static bool SetCoinTrue(int index)
			{
				return false;
			}
		}
	}
	public class LocationHandler
	{
		[HarmonyPatch(typeof(ExplorerDialogue))]
		public class ExplorerDialogue_Patch
		{
			[HarmonyPatch("GiveTools")]
			[HarmonyPrefix]
			public static bool OnGiveTools(ExplorerDialogue __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(256L);
				__instance.tools.SetActive(false);
				__instance.objectUI.SetText(__instance.item[0]);
				__instance.objectUI.SetUI(true, 0);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}
		}

		[HarmonyPatch(typeof(HexkeyPickup))]
		public class HexkeyPickup_Patch
		{
			[HarmonyPatch("Start")]
			[HarmonyPrefix]
			private static bool OnStart(HexkeyPickup __instance)
			{
				//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)
				__instance.playerMask = LayerMask.op_Implicit(1 << __instance.layer);
				return false;
			}

			[HarmonyPatch("OnTriggerStay")]
			[HarmonyPrefix]
			public static bool OnOnTriggerStay(HexkeyPickup __instance, Collider other)
			{
				if ((((LayerMask)(ref __instance.playerMask)).value & (1 << ((Component)other).gameObject.layer)) <= 0 || !((CharacterInput)__instance.tpcControls).IsObjInteractButtonPressed() || __instance.isPickedUp || __instance.pauseMenu.isOpen)
				{
					return false;
				}
				PluginMain.ArchipelagoHandler.CheckLocation(257L);
				__instance.isPickedUp = true;
				__instance.SetDialoguePopup(false);
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, __instance.itemIndex);
				((Component)__instance).gameObject.SetActive(false);
				return false;
			}
		}

		[HarmonyPatch(typeof(MapPickup))]
		public class MapPickup_Patch
		{
			[HarmonyPatch("TakeMap")]
			[HarmonyPrefix]
			public static bool OnTakeMap(MapPickup __instance)
			{
				switch (__instance.pd.currentSceneName)
				{
				case "Zone 1_F":
					PluginMain.ArchipelagoHandler.CheckLocation(512L);
					break;
				case "Zone 2_F":
					PluginMain.ArchipelagoHandler.CheckLocation(768L);
					break;
				case "Zone 3":
					PluginMain.ArchipelagoHandler.CheckLocation(1024L);
					break;
				case "Zone 5":
					PluginMain.ArchipelagoHandler.CheckLocation(1280L);
					break;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(SporePickup))]
		public class SporePickup_Patch
		{
			[HarmonyPatch("PickupObject")]
			[HarmonyPrefix]
			public static bool OnPickupObject(SporePickup __instance)
			{
				if (__instance.isPuzzleReward)
				{
					switch (__instance.puzzleName)
					{
					case "yellow":
						PluginMain.ArchipelagoHandler.CheckLocation(513L);
						break;
					case "pink":
						PluginMain.ArchipelagoHandler.CheckLocation(514L);
						break;
					case "green":
						PluginMain.ArchipelagoHandler.CheckLocation(515L);
						break;
					case "sporeIncense":
						PluginMain.ArchipelagoHandler.CheckLocation(776L);
						break;
					case "acorn":
						PluginMain.ArchipelagoHandler.CheckLocation(779L);
						break;
					}
				}
				__instance.isPickedUp = true;
				__instance.SetDialoguePopup(false);
				if (__instance.isPuzzleReward)
				{
					__instance.pd.solvedPuzzles[__instance.puzzleName] = true;
				}
				__instance.model.SetActive(false);
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, __instance.objectIndex);
				return false;
			}
		}

		[HarmonyPatch(typeof(LostCaveInteraction))]
		public class LostCaveInteraction_Patch
		{
			[HarmonyPatch("GiveBlueMushroom")]
			[HarmonyPrefix]
			public static bool OnGiveBlueMushroom(LostCaveInteraction __instance)
			{
				if (__instance.pd.dialogBools["foundLost2"] && __instance.pd.dialogBools["foundLost1"])
				{
					PluginMain.ArchipelagoHandler.CheckLocation(1797L);
					__instance.pd.skinMats["pelagic"] = true;
					__instance.objectUI.SetTextAugmenter(__instance.augmenter);
					__instance.objectUI.SetUI(true, 3);
					((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				}
				else
				{
					PluginMain.ArchipelagoHandler.CheckLocation(782L);
					__instance.objectUI.SetText(__instance.item);
					__instance.objectUI.SetUI(true, 0);
					((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(OnionDialogue))]
		public class OnionDialogue_Patch
		{
			[HarmonyPatch("TradeBerry")]
			[HarmonyPostfix]
			public static void OnTradeBerry(OnionDialogue __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(1795L);
				__instance.objectUI.SetTextAugmenter(__instance.augmenter);
				__instance.objectUI.SetUI(true, 10);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
			}
		}

		[HarmonyPatch(typeof(Level3Shop))]
		public class Level3Shop_Patch
		{
			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			public static void OnStart(Level3Shop __instance)
			{
				__instance.signPost.SetActive(false);
				__instance.modelRoot.SetActive(true);
				((Collider)__instance.dtb).enabled = true;
			}

			[HarmonyPatch("TradeSpore")]
			[HarmonyPrefix]
			public static bool OnTradeSpore(Level3Shop __instance)
			{
				PlayerData pd = __instance.pd;
				pd.rockCount -= __instance.price;
				__instance.pd.dialogBools["boughtSpore"] = true;
				__instance.rockUI.UpdateCount();
				__instance.itemModels[0].SetActive(false);
				__instance.objectUI.SetText(__instance.sporeItem);
				__instance.objectUI.SetUI(true, 0);
				PluginMain.ArchipelagoHandler.CheckLocation(1029L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}

			[HarmonyPatch("TradeEssence")]
			[HarmonyPrefix]
			public static bool OnTradeEssence(Level3Shop __instance)
			{
				PlayerData pd = __instance.pd;
				pd.rockCount -= __instance.price;
				__instance.pd.dialogBools["boughtEssence"] = true;
				__instance.rockUI.UpdateCount();
				__instance.itemModels[1].SetActive(false);
				__instance.objectUI.SetText(__instance.essenceItem);
				__instance.objectUI.SetUI(true, 1);
				PluginMain.ArchipelagoHandler.CheckLocation(1030L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue2());
				return false;
			}
		}

		[HarmonyPatch(typeof(WispInteraction))]
		public class WispInteraction_Patch
		{
			[HarmonyPatch("UpgradeEssence")]
			[HarmonyPrefix]
			public static bool OnUpgradeEssence(WispInteraction __instance)
			{
				switch (__instance.nodeName)
				{
				case "Wisp1EssenceGained":
					PluginMain.ArchipelagoHandler.CheckLocation(520L);
					break;
				case "Wisp2EssenceGained":
					PluginMain.ArchipelagoHandler.CheckLocation(517L);
					break;
				case "Wisp3EssenceGained":
					PluginMain.ArchipelagoHandler.CheckLocation(777L);
					break;
				case "Wisp4EssenceGained":
					PluginMain.ArchipelagoHandler.CheckLocation(778L);
					break;
				}
				__instance.pd.dialogBools["spokenToWisp"] = true;
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, __instance.essenceObjectIndex);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}
		}

		[HarmonyPatch(typeof(HopperDialogue))]
		public class HopperDialogue_Patch
		{
			[HarmonyPatch("TradeNeedle")]
			[HarmonyPrefix]
			public static bool OnTradeNeedle(HopperDialogue __instance)
			{
				PlayerData pd = __instance.pd;
				pd.rockCount -= __instance.cost;
				__instance.rockUI.UpdateCount();
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 9);
				PluginMain.ArchipelagoHandler.CheckLocation(516L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				Debug.Log((object)"needle traded");
				return false;
			}
		}

		[HarmonyPatch(typeof(MycologistBehavior))]
		public class MycologistBehavior_Patch
		{
			[HarmonyPatch("EnableJournal")]
			[HarmonyPrefix]
			public static bool OnEnableJournal(MycologistBehavior __instance)
			{
				__instance.inv.RemoveItem(__instance.item);
				PluginMain.ArchipelagoHandler.CheckLocation(518L);
				return false;
			}

			[HarmonyPatch("DisplayInstructions")]
			[HarmonyPrefix]
			public static bool OnDisplayInstructions(MycologistBehavior __instance)
			{
				return false;
			}
		}

		[HarmonyPatch(typeof(ItemPickupGeneric))]
		public class ItemPickupGeneric_Patch
		{
			private static Dictionary<string, int> _genericIds = new Dictionary<string, int>
			{
				{ "rubberBand", 519 },
				{ "coin1", 522 },
				{ "coin2", 523 },
				{ "sapphire", 1283 },
				{ "emerald", 1284 },
				{ "diamond", 1285 },
				{ "citrine", 1286 },
				{ "amethyst", 1287 },
				{ "hasBandaid", 1282 },
				{ "clubhousePowder", 771 },
				{ "cavePowder", 772 },
				{ "lightbulb", 780 },
				{ "secretKey", 1031 },
				{ "statueShide", 1289 },
				{ "underwaterShide", 1290 },
				{ "hasPencil", 525 }
			};

			[HarmonyPatch("PickupObject")]
			[HarmonyPrefix]
			public static bool OnPickupObject(ItemPickupGeneric __instance)
			{
				if (!_genericIds.ContainsKey(__instance.dialogeBoolName))
				{
					return true;
				}
				__instance.isPickedUp = true;
				__instance.SetDialoguePopup(false);
				PluginMain.ArchipelagoHandler.CheckLocation(_genericIds[__instance.dialogeBoolName]);
				__instance.model.SetActive(false);
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, __instance.objectIndex);
				((Component)__instance).gameObject.SetActive(false);
				__instance.OnPickup.Invoke();
				return false;
			}

			[HarmonyPatch("Start")]
			[HarmonyPrefix]
			public static bool OnStart(ItemPickupGeneric __instance)
			{
				//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)
				__instance.tpc = Object.FindObjectOfType<AdvancedWalkerController>();
				__instance.pauseMenu = Object.FindObjectOfType<PauseMenuController>();
				__instance.playerMask = LayerMask.op_Implicit(1 << __instance.layer);
				return false;
			}
		}

		[HarmonyPatch(typeof(BlueberryTraderInteraction))]
		public class BlueberryTraderInteraction_Patch
		{
			[HarmonyPatch("TradeBerry")]
			[HarmonyPrefix]
			public static bool OnTradeBerry(BlueberryTraderInteraction __instance)
			{
				PlayerData pd = __instance.pd;
				pd.rockCount -= __instance.berryCost;
				__instance.pd.dialogBools["boughtBerry"] = true;
				__instance.rockUI.UpdateCount();
				__instance.berries[0].SetActive(false);
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 2);
				PluginMain.ArchipelagoHandler.CheckLocation(521L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				Debug.Log((object)"berry traded");
				return false;
			}
		}

		[HarmonyPatch(typeof(BlueberryPickup))]
		public class BlueberryPickup_Patch
		{
			[HarmonyPatch("PickupObject")]
			[HarmonyPrefix]
			public static bool OnPickupObject(BlueberryPickup __instance)
			{
				__instance.isPickedUp = true;
				__instance.SetDialoguePopup(false);
				__instance.model.SetActive(false);
				__instance.pd.dialogBools["caveBerry"] = true;
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, __instance.objectIndex);
				PluginMain.ArchipelagoHandler.CheckLocation(524L);
				((Component)__instance).gameObject.SetActive(false);
				return false;
			}
		}

		[HarmonyPatch(typeof(ClimberDialogue))]
		public class ClimberDialogue_Patch
		{
			[HarmonyPatch("TradeCrystals")]
			[HarmonyPrefix]
			public static bool OnTradeCrystals(ClimberDialogue __instance)
			{
				PlayerData pd = __instance.pd;
				pd.rockCount -= __instance.upgradeCost;
				__instance.rockUI.UpdateCount();
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 10);
				PluginMain.ArchipelagoHandler.CheckLocation(769L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				Debug.Log((object)"First Hook Upgrade");
				return false;
			}
		}

		[HarmonyPatch(typeof(NectarEventHandler))]
		public class NectarEventHandler_Patch
		{
			[HarmonyPatch("NectarReward")]
			[HarmonyPrefix]
			public static bool OnNectarReward(NectarEventHandler __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(770L);
				return true;
			}

			[HarmonyPatch("NectarSkinReward")]
			[HarmonyPrefix]
			public static bool NectarSkinReward(NectarEventHandler __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(1798L);
				__instance.objectUI.SetTextAugmenter(__instance.augmenter);
				__instance.objectUI.SetUI(true, 8);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}
		}

		[HarmonyPatch(typeof(ObstacleEventHandler))]
		public class ObstacleEventHandler_Patch
		{
			[HarmonyPatch("GiveGreenSkin")]
			[HarmonyPrefix]
			public static bool OnGiveGreenSkin(ObstacleEventHandler __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(1796L);
				__instance.objectUI.SetTextAugmenter(__instance.augmenter);
				__instance.objectUI.SetUI(true, 1);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue2());
				return false;
			}

			[HarmonyPatch("GivePassword")]
			[HarmonyPrefix]
			public static bool OnGivePassword(ObstacleEventHandler __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(773L);
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 5);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}

			[HarmonyPatch("Start")]
			[HarmonyPrefix]
			private static void Start(ObstacleEventHandler __instance)
			{
				if (SceneChangeVars.fromObstacleCourse)
				{
					__instance.pauser.PauseThePlayer();
					((MonoBehaviour)__instance).StartCoroutine(LoadsceneFromCourseCo(__instance, fromQuitting: false));
					SceneChangeVars.fromObstacleCourse = false;
				}
				else if (SceneChangeVars.fromQuittingObstacleCourse)
				{
					__instance.pauser.PauseThePlayer();
					((MonoBehaviour)__instance).StartCoroutine(LoadsceneFromCourseCo(__instance, fromQuitting: true));
					SceneChangeVars.fromQuittingObstacleCourse = false;
				}
				else if (Object.op_Implicit((Object)(object)__instance.col1) && (Object)(object)__instance.col2 != (Object)null)
				{
					((Collider)__instance.col1).enabled = true;
					((Collider)__instance.col2).enabled = true;
				}
			}

			private static IEnumerator LoadsceneFromCourseCo(ObstacleEventHandler obs, bool fromQuitting)
			{
				obs.exMember.position = obs.exPOS.position;
				obs.npcIK.SetAimTarget();
				yield return (object)new WaitForSeconds(1f);
				if (!fromQuitting)
				{
					if (!obs.pd.dialogBools["obstacle1_beaten"])
					{
						obs.dtb.StartDialogue("GivePassword");
						obs.pd.dialogBools["obstacle1_beaten"] = true;
					}
					else if (!obs.pd.dialogBools["obstacle2_beaten"])
					{
						obs.dtb.StartDialogue("GiveObstacle2Reward");
						obs.pd.dialogBools["obstacle2_beaten"] = true;
					}
					else
					{
						obs.dtb.StartDialogue("Obstacle2NoReward");
					}
				}
				else if (!obs.pd.dialogBools["knowsPass"])
				{
					obs.dtb.StartDialogue("QuitObstacle");
				}
				else
				{
					obs.dtb.StartDialogue("QuitObstacle2");
				}
			}
		}

		[HarmonyPatch(typeof(WindObstacle))]
		public class WindObstacle_Patch
		{
			[HarmonyPatch("RewardSuperEssence")]
			[HarmonyPrefix]
			public static bool OnRewardSuperEssence(WindObstacle __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(774L);
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 6);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}
		}

		[HarmonyPatch(typeof(FlintSteelPurchase))]
		public class FlintSteelPurchase_Patch
		{
			[HarmonyPatch("TradeFlint")]
			[HarmonyPrefix]
			public static bool OnTradeFlint(FlintSteelPurchase __instance)
			{
				PlayerData pd = __instance.pd;
				pd.rockCount -= __instance.flintCost;
				__instance.rockUI.UpdateCount();
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 9);
				PluginMain.ArchipelagoHandler.CheckLocation(775L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				Debug.Log((object)"flint traded");
				return false;
			}
		}

		[HarmonyPatch(typeof(RileyInteraction))]
		public class RileyInteraction_Patch
		{
			[HarmonyPatch("GiveHeadlamp")]
			[HarmonyPrefix]
			public static bool OnGiveHeadlamp(RileyInteraction __instance)
			{
				__instance.objectUI.SetText(__instance.headlampItem);
				__instance.objectUI.SetUI(true, 4);
				__instance.inv.RemoveItem(__instance.lightbulb);
				PluginMain.ArchipelagoHandler.CheckLocation(781L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}
		}

		[HarmonyPatch(typeof(DiverInteraction))]
		public class DiverInteraction_Patch
		{
			[HarmonyPatch("TradeWaterEssence")]
			[HarmonyPrefix]
			public static bool OnTradeWaterEssence(DiverInteraction __instance)
			{
				PlayerData pd = __instance.pd;
				pd.rockCount -= __instance.cost;
				__instance.rockUI.UpdateCount();
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 3);
				PluginMain.ArchipelagoHandler.CheckLocation(1025L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				Debug.Log((object)"Water traded");
				return false;
			}
		}

		[HarmonyPatch(typeof(WaterSporeCollecting))]
		public class WaterSporeCollecting_Patch
		{
			[HarmonyPatch("RopeReward")]
			[HarmonyPrefix]
			public static bool OnRopeReward(WaterSporeCollecting __instance)
			{
				__instance.pd.dialogBools["collectingSpores"] = false;
				__instance.pd.dialogBools["hasCollectedAllSpores"] = true;
				__instance.dialogue.StartNodeName = "ChojoStart";
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 5);
				__instance.thimblePickup.DropItem();
				((Component)__instance.thimblePickup).gameObject.SetActive(false);
				__instance.thimbleModel.SetActive(true);
				__instance.pickup.UnsetObjectOnPlayer();
				__instance.pickup.isNearItem = false;
				__instance.pickup.detectedObject = null;
				__instance.rope.SetActive(false);
				PluginMain.ArchipelagoHandler.CheckLocation(1026L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}

			[HarmonyPatch("Start")]
			[HarmonyPostfix]
			private static void OnStart(WaterSporeCollecting __instance)
			{
				__instance.rope.SetActive(true);
			}
		}

		[HarmonyPatch(typeof(StringEvent))]
		public class StringEvent_Patch
		{
			[HarmonyPatch("Start")]
			[HarmonyPrefix]
			public static bool OnStart(StringEvent __instance)
			{
				__instance.director = Object.FindObjectOfType<PlayableDirector>();
				__instance.rockTrigger = ((Component)__instance).GetComponent<BoxCollider>();
				if (__instance.pd.dialogBools["hasString"] && !__instance.pd.dialogBools["rescuedChungy"] && __instance.tpc.hookEnabled)
				{
					((Collider)__instance.rockTrigger).enabled = true;
				}
				if (!__instance.pd.dialogBools["rescuedChungy"])
				{
					return false;
				}
				((Component)__instance.chungyObject).gameObject.SetActive(false);
				__instance.stringModel.SetActive(true);
				return false;
			}

			[HarmonyPatch("GiveChungyHooksCo")]
			[HarmonyPrefix]
			public static void OnGiveChungyHooksCo(StringEvent __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(1027L);
			}
		}

		[HarmonyPatch(typeof(ScavengerInteraction))]
		public class ScavengerInteraction_Patch
		{
			[HarmonyPatch("Start")]
			[HarmonyPrefix]
			public static bool OnStart(ScavengerInteraction __instance)
			{
				return false;
			}

			[HarmonyPatch("TradeScrew")]
			[HarmonyPrefix]
			public static bool OnTradeScrew(ScavengerInteraction __instance)
			{
				PlayerData pd = __instance.pd;
				pd.rockCount -= __instance.cost;
				__instance.rockUI.UpdateCount();
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 0);
				__instance.screwModel.SetActive(false);
				PluginMain.ArchipelagoHandler.CheckLocation(1281L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				__instance.dialogue.StartNodeName = "ScavengerChat";
				return false;
			}
		}

		[HarmonyPatch(typeof(CoinNPCBehavior))]
		public class CoinNPCBehavior_Patch
		{
			[HarmonyPatch("CheckCoins")]
			[HarmonyPostfix]
			public static void CheckCoins(CoinNPCBehavior __instance, bool __result)
			{
				if (__result)
				{
					PluginMain.ArchipelagoHandler.CheckLocation(526L);
				}
			}
		}

		[HarmonyPatch(typeof(RicoInteraction))]
		public class RicoInteraction_Patch
		{
			[HarmonyPatch("TradeShide")]
			[HarmonyPrefix]
			public static bool OnTradeShide(RicoInteraction __instance)
			{
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 7);
				PluginMain.ArchipelagoHandler.CheckLocation(1288L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				__instance.dialogue.StartNodeName = "RicoPost";
				return false;
			}

			[HarmonyPatch("Start")]
			[HarmonyPrefix]
			public static bool Start(RicoInteraction __instance)
			{
				if (__instance.isZone0)
				{
					((Component)__instance).gameObject.SetActive(true);
					return false;
				}
				__instance.dialogue.StartNodeName = "RicoPost";
				return false;
			}

			[HarmonyPatch("GiveSuperSpore")]
			[HarmonyPrefix]
			public static bool GiveSuperSpore(RicoInteraction __instance)
			{
				__instance.objectUI.SetText(__instance.superSpore);
				__instance.objectUI.SetUI(true, 2);
				PluginMain.ArchipelagoHandler.CheckLocation(1026L);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue2());
				return false;
			}
		}

		[HarmonyPatch(typeof(RingTradeInteraction))]
		public class RingTradeInteraction_Patch
		{
			[HarmonyPatch("TriggerRingReward")]
			[HarmonyPrefix]
			public static bool OnTriggerRingReward(RingTradeInteraction __instance)
			{
				if (__instance.pd.ringCount < 3)
				{
					return false;
				}
				if (__instance.pd.ringCount == 3)
				{
					PluginMain.ArchipelagoHandler.CheckLocation(1291L);
					__instance.objectUI.SetText(__instance.shideItem);
					__instance.objectUI.SetUI(true, 7);
					((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				}
				else
				{
					PluginMain.ArchipelagoHandler.CheckLocation(1803L);
					__instance.dialogue.StartNodeName = "GweenyAllRingsPost";
					__instance.objectUI.SetTextAugmenter(__instance.aug);
					__instance.objectUI.SetUI(true, 8);
					((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(StrawberryActivityHandler))]
		public class StrawberryActivityHandler_Patch
		{
			[HarmonyPatch("StrawberryReward")]
			[HarmonyPrefix]
			public static bool OnStrawberryReward(StrawberryActivityHandler __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(1793L);
				__instance.objectUI.SetTextAugmenter(__instance.augmenter);
				__instance.objectUI.SetUI(true, 8);
				__instance.inv.RemoveItem(__instance.rubberBand);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}
		}

		[HarmonyPatch(typeof(DaisyInteraction))]
		public class DaisyInteraction_Patch
		{
			[HarmonyPatch("GiveGreenSkin")]
			[HarmonyPrefix]
			public static bool GiveGreenSkin(DaisyInteraction __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(1794L);
				__instance.objectUI.SetTextAugmenter(__instance.augmenter);
				__instance.objectUI.SetUI(true, 11);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue2());
				return false;
			}
		}

		[HarmonyPatch(typeof(ShimuHandler))]
		public class ShimuHandler_Patch
		{
			[HarmonyPatch("GiveConch")]
			[HarmonyPrefix]
			public static bool GiveConch(ShimuHandler __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(259L);
				__instance.objectUI.SetText(__instance.item);
				__instance.objectUI.SetUI(true, 0);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}
		}

		[HarmonyPatch(typeof(WaterRockActivity))]
		public class WaterRockActivity_Patch
		{
			[HarmonyPatch("SkinReward")]
			[HarmonyPrefix]
			public static bool SkinReward(WaterRockActivity __instance)
			{
				PluginMain.ArchipelagoHandler.CheckLocation(1800L);
				__instance.objectUI.SetTextAugmenter(__instance.augmenter);
				__instance.objectUI.SetUI(true, 4);
				((MonoBehaviour)__instance).StartCoroutine(__instance.ContinueDialogue());
				return false;
			}

			[HarmonyPatch("EndActivity")]
			[HarmonyPrefix]
			public static bool EndActivity(WaterRockActivity __instance)
			{
				((MonoBehaviour)__instance).StartCoroutine(EndRockActivity(__instance));
				return false;
			}

			private static IEnumerator EndRockActivity(WaterRockActivity __instance)
			{
				__instance.pauser.PauseThePlayer();
				((Component)__instance.counter).gameObject.SetActive(false);
				((Component)__instance.dtb).gameObject.SetActive(true);
				__ins