Decompiled source of Speedchoice v1.0.0

plugins/Newtonsoft.Json.dll

Decompiled 11 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
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.IgnoreSymbolStoreSequencePoints)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")]
[assembly: AssemblyCompany("Newtonsoft")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © James Newton-King 2008")]
[assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")]
[assembly: AssemblyFileVersion("13.0.4.30916")]
[assembly: AssemblyInformationalVersion("13.0.4+4e13299d4b0ec96bd4df9954ef646bd2d1b5bf2a")]
[assembly: AssemblyProduct("Json.NET")]
[assembly: AssemblyTitle("Json.NET .NET 4.5")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("13.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.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	internal 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,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class FeatureGuardAttribute : Attribute
	{
		public Type FeatureType { get; }

		public FeatureGuardAttribute(Type featureType)
		{
			FeatureType = featureType;
		}
	}
	[AttributeUsage(AttributeTargets.Property, Inherited = false)]
	internal sealed class FeatureSwitchDefinitionAttribute : Attribute
	{
		public string SwitchName { get; }

		public FeatureSwitchDefinitionAttribute(string switchName)
		{
			SwitchName = switchName;
		}
	}
	[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;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
}
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 = Volatile.Read(ref _mask);
			int num4 = num & num3;
			for (Entry entry = _entries[num4]; 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;
			Volatile.Write(ref _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)
		{
			if (!value)
			{
				return False;
			}
			return True;
		}

		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)
			{
				if (nullable)
				{
					return Null;
				}
				return "0.0";
			}
			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) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		private static string EnsureDecimalPlace(string text)
		{
			if (StringUtils.IndexOf(text, '.') != -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.DBNull => Null, 
				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]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value)
		{
			return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Formatting formatting)
		{
			return SerializeObject(value, formatting, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		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]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		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]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		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);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer)
		{
			StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture);
			using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter))
			{
				jsonTextWriter.Formatting = jsonSerializer.Formatting;
				jsonSerializer.Serialize(jsonTextWriter, value, type);
			}
			return stringWriter.ToString();
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value)
		{
			return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value, JsonSerializerSettings settings)
		{
			return DeserializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static object? DeserializeObject(string value, Type type)
		{
			return DeserializeObject(value, type, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeObject<T>(string value)
		{
			return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
		{
			return DeserializeObject<T>(value);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
		{
			return DeserializeObject<T>(value, settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeObject<T>(string value, params JsonConverter[] converters)
		{
			return (T)DeserializeObject(value, typeof(T), converters);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings)
		{
			return (T)DeserializeObject(value, typeof(T), settings);
		}

		[DebuggerStepThrough]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		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);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		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]
		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static void PopulateObject(string value, object target)
		{
			PopulateObject(value, target, null);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		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.");
				}
			}
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXmlNode(XmlNode? node)
		{
			return SerializeXmlNode(node, Formatting.None);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXmlNode(XmlNode? node, Formatting formatting)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value)
		{
			return DeserializeXmlNode(value, null);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXNode(XObject? node)
		{
			return SerializeXNode(node, Formatting.None);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXNode(XObject? node, Formatting formatting)
		{
			return SerializeXNode(node, formatting, omitRootObject: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value)
		{
			return DeserializeXNode(value, null);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
		[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter);
		}
	}
	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;

		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)
		{
			if (type != JsonContainerType.Array)
			{
				return type == JsonContainerType.Constructor;
			}
			return true;
		}

		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[] array = buffer.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		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;
			if (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				return MoveToContentFromNonContentAsync(cancellationToken);
			}
			return AsyncUtils.True;
		}

		private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType;
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					return false;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.None || tokenType == 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)
				{
					return (int)value;
				}
				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[] array2 = ReadAsBytes();
				ReaderReadAndAssert();
				if (TokenType != JsonToken.EndObject)
				{
					throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
				}
				SetToken(JsonToken.Bytes, array2, updateIndex: false);
				return array2;
			}
			case JsonToken.String:
			{
				string text = (string)Value;
				Guid g;
				byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray()));
				SetToken(JsonToken.Bytes, array3, updateIndex: false);
				return array3;
			}
			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)
				{
					return (double)value;
				}
				double num = ((!(value is BigInteger bigInteger)) ? 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)) ? 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)
				{
					return (decimal)value;
				}
				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()
		{
			if (Read())
			{
				return MoveToContent();
			}
			return false;
		}

		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);
		}
	}
	[RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")]
	[RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")]
	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.GetValueOrDefault(DateTimeZoneHandling.RoundtripKind);
			}
			set
			{
				_dateTimeZoneHandling = value;
			}
		}

		public virtual DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling.GetValueOrDefault(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()
		{
			return Create(JsonConvert.DefaultSettings?.Invoke());
		}

		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);
			new JsonSerializerInternalReader(this).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);
			object? result = new JsonSerializerInternalReader(this).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

plugins/Speedchoice.dll

Decompiled 11 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using HarmonyLib;
using Newtonsoft.Json;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Speedchoice")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Speedchoice")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("a1c0aac5-01e5-4957-99fe-6ae9edeafa78")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Speedchoice;

[BepInPlugin("com.lukkster.Speedchoice", "Speedchoice", "1.0.0")]
public class Speedchoice : BaseUnityPlugin
{
	private struct Settings
	{
		public float boatSpeed;

		public float timeToRest;

		public float trophyOdds;

		public bool bossReveals;

		public bool bossSkills;

		public bool cheatDeath;

		public bool dropMaterials;

		public bool fastCrops;

		public bool fastFermenters;

		public bool harmlessPieces;

		public bool increasedExp;

		public bool instantUpgrades;

		public bool lootlessBosses;

		public bool noBuildStations;

		public bool noCraftCost;

		public bool noCraftLevels;

		public bool showDeaths;

		public bool showLogouts;

		public bool showTimer;

		public bool structureLoot;

		public bool wherePortal;

		public bool alwaysRocky;

		public float runSpeed;

		public float jumpForce;

		public float sailForce;

		public float restOverride;

		public float trophyOverride;

		public bool unlockPieces;

		public bool unlockRecipes;

		public int time;

		public bool isTimerRunning;

		public Settings()
		{
			boatSpeed = 0f;
			timeToRest = 0f;
			trophyOdds = 0f;
			bossReveals = false;
			bossSkills = false;
			cheatDeath = false;
			dropMaterials = false;
			fastCrops = false;
			fastFermenters = false;
			harmlessPieces = false;
			increasedExp = false;
			instantUpgrades = false;
			lootlessBosses = false;
			noBuildStations = false;
			noCraftCost = false;
			noCraftLevels = false;
			showDeaths = false;
			showLogouts = false;
			showTimer = false;
			structureLoot = false;
			wherePortal = false;
			alwaysRocky = false;
			runSpeed = 1f;
			jumpForce = 1f;
			sailForce = 1f;
			restOverride = -1f;
			trophyOverride = -1f;
			unlockPieces = false;
			unlockRecipes = false;
			time = 0;
			isTimerRunning = false;
		}
	}

	private struct Profile
	{
		public List<string> keys;

		public string toolTip;

		public Dictionary<string, float> ranges;

		public Dictionary<string, bool> checkBoxes;

		public Profile(List<string> keys, string toolTip, Dictionary<string, float> ranges, Dictionary<string, bool> checkBoxes)
		{
			this.keys = keys;
			this.toolTip = toolTip;
			this.ranges = ranges;
			this.checkBoxes = checkBoxes;
		}
	}

	private struct RangeOption
	{
		public string name;

		public string toolTip;

		public RangeOption(string name, string toolTip)
		{
			this.name = name;
			this.toolTip = toolTip;
		}
	}

	private struct Range
	{
		public Func<float> Get;

		public Action<float> Set;

		public string toolTip;

		public List<RangeOption> rangeOptions;

		public Range(Func<float> getter, Action<float> setter, string toolTip, List<RangeOption> rangeOptions)
		{
			Get = getter;
			Set = setter;
			this.toolTip = toolTip;
			this.rangeOptions = rangeOptions;
		}
	}

	private struct CheckBox
	{
		public Func<bool> Get;

		public Action<bool> Set;

		public string toolTip;

		public CheckBox(Func<bool> getter, Action<bool> setter, string toolTip)
		{
			Get = getter;
			Set = setter;
			this.toolTip = toolTip;
		}
	}

	[HarmonyPatch(typeof(FejdStartup), "OnServerOptions")]
	private class FejdStartup_OnServerOptions
	{
		private static float profileSep;

		private static float rangeSep;

		private static float checkBoxSep;

		private static GameObject serverOptions;

		private static void Postfix(FejdStartup __instance)
		{
			if ((Object)(object)GameObject.Find(checkBoxes.Keys.First()) == (Object)null)
			{
				serverOptions = GameObject.Find("StartGui_ServerOptions");
				profileSep = GetSeperation("Presets/Easy", "Presets/Casual");
				rangeSep = GetSeperation("Modifiers/Combat", "Modifiers/Death");
				checkBoxSep = GetSeperation("Modifiers/NoBuildCost", "Modifiers/Passivemobs");
				int num = 1;
				int num2 = 0;
				foreach (KeyValuePair<string, Profile> profile in profiles)
				{
					num2++;
					if (num2 > 3)
					{
						num2 = 1;
						num++;
					}
					AddProfile(num, num2, profile);
				}
				float num3 = (float)num * profileSep;
				string[] array = new string[2] { "Presets/Default", "Modifiers" };
				for (int i = 0; i < array.Length; i++)
				{
					MoveDown(array[i], num3);
				}
				num = 0;
				foreach (KeyValuePair<string, Range> range in ranges)
				{
					num++;
					AddRange(num, range);
				}
				array = new string[5] { "Modifiers/NoBuildCost", "Modifiers/PlayerBasedEvents", "Modifiers/Fire", "Modifiers/Passivemobs", "Modifiers/Nomap" };
				for (int i = 0; i < array.Length; i++)
				{
					MoveDown(array[i], (float)num * rangeSep);
				}
				num3 += (float)num * rangeSep;
				num = 2;
				num2 = 0;
				foreach (KeyValuePair<string, CheckBox> checkBox in checkBoxes)
				{
					num2++;
					if (num2 > 3)
					{
						num2 = 1;
						num++;
					}
					AddCheckBox(num, num2, checkBox);
				}
				ExpandPanel(num3 + (float)(num - 1) * checkBoxSep);
			}
			Load(__instance.m_world);
			foreach (KeyValuePair<string, Range> range2 in ranges)
			{
				GameObject.Find(range2.Key).GetComponentInChildren<Slider>().value = range2.Value.Get();
			}
			foreach (KeyValuePair<string, CheckBox> checkBox2 in checkBoxes)
			{
				GameObject.Find(checkBox2.Key).GetComponentInChildren<Toggle>().isOn = checkBox2.Value.Get();
			}
		}

		private static float GetSeperation(string a, string b)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			Transform val = serverOptions.transform.Find("panel/" + a);
			Transform obj = serverOptions.transform.Find("panel/" + b);
			float y = ((Component)val).GetComponent<RectTransform>().anchoredPosition.y;
			float y2 = ((Component)obj).GetComponent<RectTransform>().anchoredPosition.y;
			return Math.Abs(y - y2);
		}

		private static void AddProfile(int row, int col, KeyValuePair<string, Profile> entry)
		{
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			Transform val = serverOptions.transform.Find("panel/Presets");
			GameObject obj = Object.Instantiate<GameObject>(((Component)(col switch
			{
				1 => ((Component)val).transform.Find("Casual"), 
				2 => ((Component)val).transform.Find("Hammer"), 
				_ => ((Component)val).transform.Find("Immersive"), 
			})).gameObject, val);
			Transform obj2 = obj.transform.Find("Text");
			((obj2 != null) ? ((Component)obj2).GetComponent<TMP_Text>() : null).text = entry.Key;
			((Object)obj).name = entry.Key;
			KeyButton obj3 = ((obj != null) ? obj.GetComponent<KeyButton>() : null);
			obj3.m_keys = entry.Value.keys;
			obj3.m_preset = (WorldPresets)0;
			obj3.m_toolTip = entry.Value.toolTip;
			MoveDown("Presets/" + entry.Key, profileSep * (float)row);
		}

		private static void AddRange(int row, KeyValuePair<string, Range> entry)
		{
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Expected O, but got Unknown
			Transform val = serverOptions.transform.Find("panel/Modifiers");
			GameObject obj = Object.Instantiate<GameObject>(((Component)((Component)val).transform.Find("Portals")).gameObject, val);
			Transform obj2 = obj.transform.Find("label");
			((TMP_Text)((obj2 != null) ? ((Component)obj2).GetComponent<TextMeshProUGUI>() : null)).text = entry.Key;
			((Object)obj).name = entry.Key;
			MoveDown("Modifiers/" + entry.Key, rangeSep * (float)row);
			Transform obj3 = obj.transform.Find("slider");
			Slider obj4 = ((obj3 != null) ? ((Component)obj3).GetComponent<Slider>() : null);
			obj4.maxValue = entry.Value.rangeOptions.Count() - 1;
			obj4.value = 0f;
			KeySlider val2 = ((obj3 != null) ? ((Component)obj3).GetComponent<KeySlider>() : null);
			val2.m_toolTip = entry.Value.toolTip;
			val2.m_settings = new List<SliderSetting>();
			foreach (RangeOption rangeOption in entry.Value.rangeOptions)
			{
				val2.m_settings.Add(new SliderSetting
				{
					m_name = rangeOption.name,
					m_toolTip = rangeOption.toolTip
				});
			}
		}

		private static void AddCheckBox(int row, int col, KeyValuePair<string, CheckBox> entry)
		{
			Transform val = serverOptions.transform.Find("panel/Modifiers");
			GameObject obj = Object.Instantiate<GameObject>(((Component)(col switch
			{
				1 => ((Component)val).transform.Find("NoBuildCost"), 
				2 => ((Component)val).transform.Find("PlayerBasedEvents"), 
				_ => ((Component)val).transform.Find("Fire"), 
			})).gameObject, val);
			Transform obj2 = obj.transform.Find("Label");
			((TMP_Text)((obj2 != null) ? ((Component)obj2).GetComponent<TextMeshProUGUI>() : null)).text = entry.Key;
			((Object)obj).name = entry.Key;
			MoveDown("Modifiers/" + entry.Key, checkBoxSep * (float)row);
			obj.GetComponent<KeyToggle>().m_toolTip = entry.Value.toolTip;
		}

		private static void MoveDown(string objectId, float distance)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = GameObject.Find("GuiRoot/GUI/StartGui/StartGame/StartGui_ServerOptions/panel/" + objectId).GetComponent<RectTransform>();
			component.anchoredPosition -= new Vector2(0f, distance);
		}

		private static void ExpandPanel(float distance, int max = -10, int min = -1070)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: 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_0052: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = ((Component)serverOptions.transform.Find("panel")).GetComponent<RectTransform>();
			component.offsetMax += new Vector2(0f, distance / 2f);
			float num = 0f;
			if (component.offsetMax.y > (float)max)
			{
				num = component.offsetMax.y - (float)max;
				component.offsetMax = new Vector2(component.offsetMax.x, (float)max);
			}
			component.offsetMin -= new Vector2(0f, distance / 2f + num);
			if (component.offsetMin.y < (float)min)
			{
				num = (float)min - component.offsetMin.y;
				component.offsetMin = new Vector2(component.offsetMin.x, (float)min);
			}
			MoveDown("Modifiers", -1f * distance - num / 2f);
		}
	}

	[HarmonyPatch(typeof(FejdStartup), "OnServerOptionsDone")]
	private class FejdStartup_OnServerOptionsDone
	{
		private static void Prefix(FejdStartup __instance)
		{
			bool isUpdated = false;
			foreach (KeyValuePair<string, Range> range in ranges)
			{
				Assign(range, ref isUpdated);
			}
			foreach (KeyValuePair<string, CheckBox> checkBox in checkBoxes)
			{
				Assign(checkBox, ref isUpdated);
			}
			if (isUpdated)
			{
				Save(__instance.m_world);
			}
		}

		private static void Assign(KeyValuePair<string, Range> entry, ref bool isUpdated)
		{
			float value = GameObject.Find(entry.Key).GetComponentInChildren<Slider>().value;
			isUpdated = isUpdated || value != entry.Value.Get();
			entry.Value.Set(value);
		}

		private static void Assign(KeyValuePair<string, CheckBox> entry, ref bool isUpdated)
		{
			bool isOn = GameObject.Find(entry.Key).GetComponentInChildren<Toggle>().isOn;
			isUpdated = isUpdated || isOn != entry.Value.Get();
			entry.Value.Set(isOn);
		}
	}

	[HarmonyPatch(typeof(ServerOptionsGUI), "OnPresetButton")]
	private class ServerOptionsGUI_OnPresetButton
	{
		private static void Postfix(KeyButton button)
		{
			foreach (KeyValuePair<string, Range> range in ranges)
			{
				GameObject.Find(range.Key).GetComponentInChildren<Slider>().value = 0f;
			}
			foreach (KeyValuePair<string, CheckBox> checkBox in checkBoxes)
			{
				GameObject.Find(checkBox.Key).GetComponentInChildren<Toggle>().isOn = false;
			}
			if (!profiles.TryGetValue(button.GetName(), out var value))
			{
				return;
			}
			foreach (KeyValuePair<string, float> range2 in value.ranges)
			{
				GameObject.Find(range2.Key).GetComponentInChildren<Slider>().value = range2.Value;
			}
			foreach (KeyValuePair<string, bool> checkBox2 in value.checkBoxes)
			{
				GameObject.Find(checkBox2.Key).GetComponentInChildren<Toggle>().isOn = checkBox2.Value;
			}
		}
	}

	[HarmonyPatch(typeof(FejdStartup), "UpdateWorldList")]
	private class FejdStartup_UpdateWorldList
	{
		private static void UpdateToolTip(UITooltip toolTip, string add)
		{
			toolTip.m_topic = "$menu_serveroptions";
			if (toolTip.m_text != "")
			{
				toolTip.m_text += "\n";
			}
			toolTip.m_text += add;
		}

		private static void Postfix(FejdStartup __instance)
		{
			for (int i = 0; i < __instance.m_worlds.Count; i++)
			{
				Load(__instance.m_worlds[i]);
				List<string> list = profiles.Keys.ToList();
				HashSet<string> hashSet = new HashSet<string>(__instance.m_worlds[i].m_startingGlobalKeys);
				hashSet.Remove("noworkbench");
				hashSet.RemoveWhere((string x) => x.StartsWith("preset "));
				for (int num = list.Count - 1; num >= 0; num--)
				{
					if (!profiles[list[num]].keys.ToHashSet().SetEquals(hashSet))
					{
						list.RemoveAt(num);
					}
				}
				bool flag = false;
				UITooltip component = __instance.m_worldListElements[i].GetComponent<UITooltip>();
				foreach (KeyValuePair<string, Range> range in ranges)
				{
					float num2 = range.Value.Get();
					for (int num3 = list.Count - 1; num3 >= 0; num3--)
					{
						if (profiles[list[num3]].ranges[range.Key] != num2)
						{
							list.RemoveAt(num3);
						}
					}
					if (num2 != 0f)
					{
						flag = true;
						UpdateToolTip(component, range.Key + ": " + range.Value.rangeOptions[(int)num2].name);
					}
				}
				foreach (KeyValuePair<string, CheckBox> checkBox in checkBoxes)
				{
					for (int num4 = list.Count - 1; num4 >= 0; num4--)
					{
						if (profiles[list[num4]].checkBoxes[checkBox.Key] != checkBox.Value.Get())
						{
							list.RemoveAt(num4);
						}
					}
					if (checkBox.Value.Get())
					{
						flag = true;
						UpdateToolTip(component, checkBox.Key);
					}
				}
				TextMeshProUGUI component2 = ((Component)__instance.m_worldListElements[i].transform.Find("modifiers")).GetComponent<TextMeshProUGUI>();
				if (list.Count > 0)
				{
					((TMP_Text)component2).text = list[0];
				}
				else if (flag)
				{
					((TMP_Text)component2).text = Localization.instance.Localize("$menu_modifier_custom");
				}
			}
		}
	}

	[HarmonyPatch(typeof(World), "RemoveWorld")]
	private class World_RemoveWorld
	{
		private static void Postfix(string name)
		{
			File.Delete(GetSavePath(name));
		}
	}

	private struct Prefab
	{
		public string name;

		public string aoe;

		public DamageTypes damage;

		public Prefab(string name, string aoe, DamageTypes damage)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			this.name = name;
			this.aoe = aoe;
			this.damage = damage;
		}
	}

	[HarmonyPatch(typeof(ZoneSystem), "Start")]
	private class ZoneSystem_Start
	{
		private static void Postfix(ZoneSystem __instance)
		{
			if (ZNet.instance.IsServer())
			{
				Load(ZNet.m_world);
				HarmlessPieces();
				if (settings.noBuildStations)
				{
					__instance.SetGlobalKey((GlobalKeys)22);
				}
				else
				{
					__instance.RemoveGlobalKey((GlobalKeys)22);
				}
				if (settings.unlockPieces)
				{
					__instance.SetGlobalKey((GlobalKeys)21);
				}
				else
				{
					__instance.RemoveGlobalKey((GlobalKeys)21);
				}
			}
			ZRoutedRpc.instance.Register<string>("FromServer", (Action<long, string>)FromServer);
			ZRoutedRpc.instance.Register<string>("StartTimer", (Action<long, string>)StartTimer);
			ZRoutedRpc.instance.Register<string>("GetTimer", (Action<long, string>)GetTimer);
			ZRoutedRpc.instance.Register<int>("SetTimer", (Action<long, int>)SetTimer);
			ZRoutedRpc.instance.Register<string>("RequestPois", (Action<long, string>)RequestPois);
			ZRoutedRpc.instance.Register<string>("RevealPois", (Action<long, string>)RevealPois);
			ZRoutedRpc.instance.Register<int>("LevelUp", (Action<long, int>)LevelUp);
			ZRoutedRpc.instance.Register<string>("PlacePortal", (Action<long, string>)PlacePortal);
		}

		private static void HarmlessPieces()
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			foreach (Prefab harmingPrefab in harmingPrefabs)
			{
				if (settings.harmlessPieces)
				{
					((Component)ZNetScene.instance.GetPrefab(harmingPrefab.name).transform.Find(harmingPrefab.aoe)).GetComponent<Aoe>().m_damage = default(DamageTypes);
				}
				else
				{
					((Component)ZNetScene.instance.GetPrefab(harmingPrefab.name).transform.Find(harmingPrefab.aoe)).GetComponent<Aoe>().m_damage = harmingPrefab.damage;
				}
			}
		}

		private static void FromServer(long sender, string json)
		{
			ToSettings(json);
			HarmlessPieces();
			if (settings.isTimerRunning)
			{
				((MonoBehaviour)speedchoice).StartCoroutine(TimerUpdate());
			}
		}

		private static void StartTimer(long sender, string json)
		{
			if (!settings.isTimerRunning)
			{
				settings.isTimerRunning = true;
				((MonoBehaviour)speedchoice).StartCoroutine(TimerUpdate());
			}
		}

		private static void GetTimer(long sender, string json)
		{
			ZRoutedRpc.instance.InvokeRoutedRPC(sender, "SetTimer", new object[1] { settings.time });
		}

		private static void SetTimer(long sender, int time)
		{
			settings.time = time;
		}

		private static void RequestPois(long sender, string json)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			List<Poi> list = JsonConvert.DeserializeObject<List<Poi>>(json);
			List<Poi> list2 = new List<Poi>();
			foreach (Poi item in list)
			{
				foreach (KeyValuePair<Vector2i, LocationInstance> locationInstance in ZoneSystem.instance.m_locationInstances)
				{
					if (locationInstance.Value.m_location.m_prefabName == item.prefabName)
					{
						list2.Add(new Poi(item, locationInstance.Value.m_position.x, locationInstance.Value.m_position.y, locationInstance.Value.m_position.z));
					}
				}
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "RevealPois", new object[1] { JsonConvert.SerializeObject((object)list2) });
		}

		private static void RevealPois(long sender, string json)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = default(Vector3);
			foreach (Poi item in JsonConvert.DeserializeObject<List<Poi>>(json))
			{
				((Vector3)(ref val))..ctor(item.x, item.y, item.z);
				Minimap.instance.DiscoverLocation(val, item.pinType, item.name, false);
				Minimap.instance.Explore(val, item.radius);
			}
		}

		private static void LevelUp(long sender, int level)
		{
			if (!((Object)(object)Player.m_localPlayer != (Object)null))
			{
				return;
			}
			foreach (KeyValuePair<SkillType, Skill> skillDatum in ((Character)Player.m_localPlayer).GetSkills().m_skillData)
			{
				if (skillDatum.Value.m_level < (float)level)
				{
					skillDatum.Value.m_level = level;
				}
			}
		}

		private static void PlacePortal(long sender, string json)
		{
			//IL_002d: 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_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			PortalPin portalPin = JsonConvert.DeserializeObject<PortalPin>(json);
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(portalPin.x, portalPin.y, portalPin.z);
			if (portalPin.remove)
			{
				Minimap.instance.RemovePin(val, 0.1f);
			}
			if (portalPin.add)
			{
				Minimap.instance.AddPin(val, (PinType)6, portalPin.text, true, false, 0L, default(PlatformUserID));
			}
		}
	}

	[HarmonyPatch(typeof(ZRoutedRpc), "AddPeer")]
	private class ZRoutedRpc_AddPeer
	{
		private static void Postfix(ZRoutedRpc __instance, ZNetPeer peer)
		{
			if (__instance.m_server)
			{
				__instance.InvokeRoutedRPC(peer.m_uid, "FromServer", new object[1] { FromSettings() });
			}
		}
	}

	[HarmonyPatch(typeof(ZRoutedRpc), "RemovePeer")]
	private class ZRoutedRpc_RemovePeer
	{
		private static void Postfix(ZRoutedRpc __instance)
		{
			if (__instance.m_server && ZNet.instance.IsDedicated() && __instance.m_peers.Count < 1)
			{
				((MonoBehaviour)speedchoice).StopAllCoroutines();
				settings.isTimerRunning = false;
			}
		}
	}

	[HarmonyPatch(typeof(Ship), "GetSailForce")]
	public class Ship_GetSailForce
	{
		private static void Postfix(ref Vector3 __result)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (boatSpeeds.TryGetValue(settings.boatSpeed, out var value))
			{
				__result *= value;
			}
			__result *= settings.sailForce;
		}
	}

	[HarmonyPatch(typeof(Ship), "Awake")]
	public class Ship_Awake
	{
		private static void Postfix(Ship __instance)
		{
			if (boatSpeeds.TryGetValue(settings.boatSpeed, out var value))
			{
				__instance.m_backwardForce *= value * 0.8f;
			}
			__instance.m_backwardForce *= settings.sailForce;
		}
	}

	[HarmonyPatch(typeof(SE_Cozy), "Setup", new Type[] { typeof(Character) })]
	public static class SE_Cozy_Setup
	{
		private static void Postfix(SE_Cozy __instance)
		{
			float value;
			if (settings.restOverride >= 0f)
			{
				__instance.m_delay = settings.restOverride;
			}
			else if (restDelays.TryGetValue(settings.timeToRest, out value))
			{
				__instance.m_delay = value;
			}
		}
	}

	[HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")]
	private class CharacterDrop_GenerateDropList
	{
		private static void Postfix(CharacterDrop __instance, ref List<KeyValuePair<GameObject, int>> __result)
		{
			float value;
			if (settings.lootlessBosses && levels.ContainsKey(((Component)__instance).GetComponent<Character>().m_name))
			{
				__result = new List<KeyValuePair<GameObject, int>>();
			}
			else if (settings.trophyOverride >= 0f)
			{
				AddTrophy(__instance, ref __result, settings.trophyOverride / 100f);
			}
			else if (trophyOdds.TryGetValue(settings.trophyOdds, out value))
			{
				AddTrophy(__instance, ref __result, value);
			}
		}

		private static void AddTrophy(CharacterDrop __instance, ref List<KeyValuePair<GameObject, int>> __result, float odds)
		{
			if (trophies.TryGetValue(((Component)__instance).GetComponent<Character>().m_name, out var trophy) && !GotTrophy(trophy, __result) && Random.value <= odds)
			{
				Drop val = __instance.m_drops.Find((Drop drop) => ((Object)drop.m_prefab).name == trophy);
				__result.Add(new KeyValuePair<GameObject, int>(val.m_prefab, 1));
			}
		}

		private static bool GotTrophy(string trophy, List<KeyValuePair<GameObject, int>> __result)
		{
			foreach (KeyValuePair<GameObject, int> item in __result)
			{
				if (trophy == ((Object)item.Key).name)
				{
					return true;
				}
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(Trader), "GetAvailableItems")]
	private class Trader_GetAvailableItems
	{
		private static bool Prefix(Trader __instance, ref List<TradeItem> __result)
		{
			if (settings.lootlessBosses)
			{
				__result = new List<TradeItem>();
				foreach (TradeItem item in __instance.m_items)
				{
					if (string.IsNullOrEmpty(item.m_requiredGlobalKey))
					{
						__result.Add(item);
					}
				}
				return false;
			}
			return true;
		}
	}

	private struct Poi
	{
		public string prefabName;

		public PinType pinType;

		public string name;

		public float radius;

		public float x;

		public float y;

		public float z;

		public Poi(string prefabName, PinType pinType, string name, float radius)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			this.prefabName = prefabName;
			this.pinType = pinType;
			this.name = name;
			this.radius = radius;
			x = 0f;
			y = 0f;
			z = 0f;
		}

		public Poi(Poi poi, float x, float y, float z)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			prefabName = poi.prefabName;
			pinType = poi.pinType;
			name = poi.name;
			radius = poi.radius;
			this.x = x;
			this.y = y;
			this.z = z;
		}
	}

	[HarmonyPatch(typeof(Character), "OnDeath")]
	private class Character_OnDeath
	{
		private static void Postfix(Character __instance)
		{
			if (settings.bossReveals && reveals.TryGetValue(__instance.m_name, out var value))
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "RequestPois", new object[1] { JsonConvert.SerializeObject((object)value) });
			}
			if (settings.bossSkills && levels.TryGetValue(__instance.m_name, out var value2))
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "LevelUp", new object[1] { value2 });
			}
		}
	}

	[HarmonyPatch(typeof(Skill), "Raise")]
	private class Skills_Skill_Raise
	{
		private static void Prefix(ref float factor)
		{
			if (settings.increasedExp)
			{
				factor *= 6f;
			}
		}

		private static void Postfix(Skill __instance, ref bool __result)
		{
			if (!settings.bossSkills)
			{
				return;
			}
			foreach (KeyValuePair<string, int> level in levels)
			{
				if (ZoneSystem.instance.GetGlobalKey("defeated_" + level.Key.Substring(7)))
				{
					if (__instance.m_level < (float)level.Value)
					{
						__instance.m_level = level.Value;
						__instance.m_accumulator = 0f;
						__result = true;
					}
					break;
				}
			}
		}
	}

	[HarmonyPatch(typeof(Game), "Shutdown")]
	private class Game_Shutdown
	{
		private static void Prefix(Game __instance)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				if (settings.cheatDeath && ((Character)Player.m_localPlayer).IsDead())
				{
					__instance.GetPlayerProfile().SetLogoutPoint(((Component)Player.m_localPlayer).transform.position);
				}
				Dictionary<string, string> customData = Player.m_localPlayer.m_customData;
				int result = 1;
				if (customData.TryGetValue(logoutsKey, out var value))
				{
					int.TryParse(value, out result);
					result++;
				}
				customData[logoutsKey] = result.ToString();
			}
			((MonoBehaviour)speedchoice).StopAllCoroutines();
			settings.isTimerRunning = false;
			rockyied = false;
			isSynced = false;
			if (ZNet.instance.IsServer())
			{
				Save(ZNet.m_world);
			}
		}
	}

	[HarmonyPatch(typeof(Humanoid), "Pickup")]
	private class Humanoid_Pickup
	{
		private static void Postfix(Humanoid __instance, GameObject go)
		{
			if (((Character)__instance).IsPlayer())
			{
				RemoveItem(__instance.m_inventory, go.GetComponent<ItemDrop>().m_itemData);
			}
		}
	}

	[HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })]
	private class Inventory_AddItem
	{
		private static void Postfix(Inventory __instance, ItemData item)
		{
			if ((Object)(object)Player.m_localPlayer != (Object)null && ((Humanoid)Player.m_localPlayer).GetInventory() == __instance)
			{
				RemoveItem(__instance, item);
			}
		}
	}

	[HarmonyPatch(typeof(Inventory), "AddItem", new Type[]
	{
		typeof(ItemData),
		typeof(Vector2i)
	})]
	private class Inventory_AddItem_2
	{
		private static void Postfix(Inventory __instance, ItemData item)
		{
			if ((Object)(object)Player.m_localPlayer != (Object)null && ((Humanoid)Player.m_localPlayer).GetInventory() == __instance)
			{
				RemoveItem(__instance, item);
			}
		}
	}

	[HarmonyPatch(typeof(Inventory), "AddItem", new Type[]
	{
		typeof(ItemData),
		typeof(int),
		typeof(int),
		typeof(int)
	})]
	private class Inventory_AddItem_4
	{
		private static void Postfix(Inventory __instance, ItemData item)
		{
			if ((Object)(object)Player.m_localPlayer != (Object)null && ((Humanoid)Player.m_localPlayer).GetInventory() == __instance)
			{
				RemoveItem(__instance, item);
			}
		}
	}

	[HarmonyPatch(typeof(Plant), "TimeSincePlanted")]
	private static class Plant_TimeSincePlanted
	{
		private static void Postfix(Plant __instance, ref double __result)
		{
			if (settings.fastCrops)
			{
				__result = (double)__instance.m_growTimeMax + 1.0;
			}
		}
	}

	[HarmonyPatch(typeof(Fermenter), "Awake")]
	private static class Fermenter_Awake
	{
		private static void Postfix(Fermenter __instance)
		{
			if (settings.fastFermenters)
			{
				__instance.m_fermentationDuration = 10f;
			}
		}
	}

	[HarmonyPatch(typeof(Fermenter), "DelayedTap")]
	private static class Fermenter_DelayedTap
	{
		private static void Prefix(Fermenter __instance)
		{
			if (settings.fastFermenters)
			{
				__instance.GetItemConversion(__instance.m_delayedTapItem).m_producedItems = 10;
			}
		}
	}

	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	private class ObjectDB_Awake
	{
		private static void Postfix()
		{
			upgradeAbles.Clear();
			foreach (Recipe recipe in ObjectDB.instance.m_recipes)
			{
				if ((Object)(object)recipe.m_item != (Object)null && recipe.m_item.m_itemData.m_shared.m_maxQuality > 1)
				{
					upgradeAbles.Add(recipe.m_item.m_itemData.m_shared.m_name, recipe);
				}
			}
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "SetupCrafting")]
	private class InventoryGui_SetupCrafting
	{
		private static void Prefix()
		{
			UpgradeInventory(Player.m_localPlayer);
		}
	}

	[HarmonyPatch(typeof(Hud), "SetupPieceInfo")]
	private class Hud_SetupPieceInfo
	{
		private static void Postfix(Hud __instance, Piece piece)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			if (settings.noBuildStations)
			{
				GameObject obj = __instance.m_requirementItems[piece.m_resources.Length];
				Image component = ((Component)obj.transform.Find("res_icon")).GetComponent<Image>();
				TMP_Text component2 = ((Component)obj.transform.Find("res_amount")).GetComponent<TMP_Text>();
				((Graphic)component).color = Color.white;
				component2.text = "";
				((Graphic)component2).color = Color.white;
			}
		}
	}

	[HarmonyPatch(typeof(Player), "HaveRequirementItems")]
	private class Player_HaveRequirementItems
	{
		private static void Postfix(bool discover, ref bool __result)
		{
			if (settings.noCraftCost && !discover)
			{
				__result = true;
			}
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "SetupRequirement")]
	private class InventoryGui_SetupRequirement
	{
		private static void Postfix(Transform elementRoot)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if (settings.noCraftCost)
			{
				((Graphic)((Component)((Component)elementRoot).transform.Find("res_amount")).GetComponent<TMP_Text>()).color = Color.white;
			}
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
	private class InventoryGui_DoCrafting
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo targetMethod = typeof(Player).GetMethod("NoCostCheat");
			MethodInfo replacementMethod = typeof(InventoryGui_DoCrafting).GetMethod("NoCostCheat");
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.Calls(instruction, targetMethod))
				{
					yield return new CodeInstruction(OpCodes.Call, (object)replacementMethod);
				}
				else
				{
					yield return instruction;
				}
			}
		}

		public bool NoCostCheat()
		{
			if (settings.noCraftCost)
			{
				return true;
			}
			return Player.m_localPlayer.m_noPlacementCost;
		}

		private static void Postfix(Player player)
		{
			UpgradeInventory(player);
		}
	}

	[HarmonyPatch(typeof(Player), "RequiredCraftingStation")]
	private class Player_RequiredCraftingStation
	{
		private static void Prefix(ref bool checkLevel)
		{
			if (settings.noCraftLevels)
			{
				checkLevel = false;
			}
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "UpdateRecipe")]
	private class InventoryGui_UpdateRecipe
	{
		private static void Postfix(InventoryGui __instance)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (settings.noCraftLevels)
			{
				((Graphic)__instance.m_minStationLevelText).color = __instance.m_minStationLevelBasecolor;
			}
		}
	}

	[HarmonyPatch(typeof(FejdStartup), "Start")]
	private class FejdStartup_Start
	{
		private static void Postfix()
		{
			GameObject obj = GameObject.Find("Topic");
			font = ((obj != null) ? ((TMP_Text)obj.GetComponent<TextMeshProUGUI>()).font : null);
		}
	}

	[HarmonyPatch(typeof(Player), "OnSpawned")]
	private class Player_OnSpawned
	{
		private static Transform healthpanel;

		private static GameObject LeftOf(string name, Transform parent, RectTransform from)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent);
			RectTransform obj = val.AddComponent<RectTransform>();
			obj.sizeDelta = from.sizeDelta;
			obj.anchoredPosition = from.anchoredPosition - new Vector2(from.sizeDelta.x + 1f, 0f);
			obj.anchorMax = from.anchorMax;
			obj.anchorMin = from.anchorMin;
			return val;
		}

		private static void DefaultFont(ref TextMeshProUGUI tmpGui, Color color, float ratio)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			((TMP_Text)tmpGui).font = font;
			((Graphic)tmpGui).material = ((TMP_Asset)font).material;
			((Graphic)tmpGui).color = color;
			((TMP_Text)tmpGui).alignment = (TextAlignmentOptions)514;
			((TMP_Text)tmpGui).fontMaterial.EnableKeyword("OUTLINE_ON");
			((TMP_Text)tmpGui).outlineColor = Color32.op_Implicit(Color.black);
			((TMP_Text)tmpGui).outlineWidth = 0.1f;
			((TMP_Text)tmpGui).fontStyle = (FontStyles)1;
			((TMP_Text)tmpGui).fontSize = ((Component)((Component)Hud.instance).transform.Find("hudroot/healthpanel/food0")).GetComponent<RectTransform>().sizeDelta.x * ratio;
		}

		private static TextMeshProUGUI AddCounter(string name, string item, int y)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			Transform val = ((Component)Hud.instance).transform.Find("hudroot/healthpanel");
			RectTransform component = ((Component)((Component)val).transform.Find("food" + y)).GetComponent<RectTransform>();
			GameObject val2 = LeftOf(name + "Bkg", val, component);
			JsonUtility.FromJsonOverwrite(JsonUtility.ToJson((object)((Component)component).GetComponent<Image>()), (object)val2.AddComponent<Image>());
			LeftOf(name + "Icon", val, component).AddComponent<Image>().sprite = GetItemIcon(item);
			TextMeshProUGUI tmpGui = LeftOf(name + "Text", val, component).AddComponent<TextMeshProUGUI>();
			DefaultFont(ref tmpGui, Color.white, 0.5f);
			((TMP_Text)tmpGui).alignment = (TextAlignmentOptions)1028;
			return tmpGui;
		}

		private static TextMeshProUGUI AddTimer()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: 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_00ce: Unknown result type (might be due to invalid IL or missing references)
			Transform val = ((Component)Hud.instance).transform.Find("hudroot");
			RectTransform component = ((Component)val.Find("healthpanel")).GetComponent<RectTransform>();
			GameObject val2 = new GameObject("timer");
			val2.transform.SetParent(val);
			RectTransform obj = val2.AddComponent<RectTransform>();
			obj.sizeDelta = new Vector2(1000f, 0f);
			obj.anchoredPosition = component.anchoredPosition + new Vector2(71f * component.sizeDelta.x / 100f, -112f * component.sizeDelta.y / 100f);
			obj.anchorMax = component.anchorMax;
			obj.anchorMin = component.anchorMin;
			TextMeshProUGUI tmpGui = val2.AddComponent<TextMeshProUGUI>();
			DefaultFont(ref tmpGui, new Color(1f, 0.717f, 0.36f, 1f), 2f / 3f);
			((TMP_Text)tmpGui).text = $"<mspace=0.5em>{TimeSpan.FromSeconds(settings.time)}</mspace>";
			return tmpGui;
		}

		private static void Postfix(Player __instance)
		{
			healthpanel = ((Component)Hud.instance).transform.Find("hudroot/healthpanel");
			int y = 0;
			if (settings.showDeaths && (Object)(object)deaths == (Object)null)
			{
				deaths = AddCounter("deaths", "Charredskull", y);
				UpdateDeaths();
				y = 1;
			}
			if (settings.showLogouts && (Object)(object)logouts == (Object)null)
			{
				logouts = AddCounter("logouts", "RoundLog", y);
				UpdateLogouts();
			}
			if (settings.showTimer && (Object)(object)timer == (Object)null)
			{
				timer = AddTimer();
			}
			if (settings.unlockRecipes && !unlockedRecipes)
			{
				unlockedRecipes = true;
				foreach (GameObject item in ObjectDB.instance.m_items)
				{
					ItemDrop component = item.GetComponent<ItemDrop>();
					if (!((Object)(object)component == (Object)null) && component.m_itemData != null)
					{
						string name = component.m_itemData.m_shared.m_name;
						if (!__instance.m_knownMaterial.Contains(name))
						{
							__instance.m_knownMaterial.Add(name);
						}
					}
				}
				__instance.UpdateKnownRecipesList();
				MessageHud.instance.m_unlockMsgQueue.Clear();
				MessageHud.instance.m_unlockMsgCount = 0;
			}
			((Character)__instance).m_runSpeed = ((Character)__instance).m_runSpeed * settings.runSpeed;
			((Character)__instance).m_jumpForce = ((Character)__instance).m_jumpForce * settings.jumpForce;
		}
	}

	[HarmonyPatch(typeof(Player), "OnDeath")]
	private class Player_OnDeath
	{
		private static void Postfix()
		{
			UpdateDeaths();
		}
	}

	[HarmonyPatch(typeof(Player), "Update")]
	private class Player_Update
	{
		private static void Postfix(Player __instance)
		{
			if (Object.op_Implicit((Object)(object)Game.instance) && ((Character)__instance).TakeInput() && Input.anyKeyDown)
			{
				if (!ZRoutedRpc.instance.m_server && !isSynced)
				{
					isSynced = true;
					ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "GetTimer", new object[1] { "GetTimer" });
				}
				if (!settings.isTimerRunning)
				{
					settings.isTimerRunning = true;
					((MonoBehaviour)speedchoice).StartCoroutine(TimerUpdate());
					ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "StartTimer", new object[1] { "StartTimer" });
				}
			}
		}
	}

	private struct PortalPin
	{
		public float x;

		public float y;

		public float z;

		public string text;

		public bool add;

		public bool remove;

		public PortalPin(Vector3 vector, string text, bool add, bool remove)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			x = vector.x;
			y = vector.y;
			z = vector.z;
			this.text = text;
			this.add = add;
			this.remove = remove;
		}
	}

	[HarmonyPatch(typeof(Player), "PlacePiece", new Type[]
	{
		typeof(Piece),
		typeof(Vector3),
		typeof(Quaternion),
		typeof(bool)
	})]
	private class Player_PlacePiece
	{
		private static void Postfix(Piece piece, Vector3 pos)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (settings.wherePortal && (Object)(object)piece != (Object)null && (((Object)piece).name == "portal_wood" || ((Object)piece).name == "portal_stone"))
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "PlacePortal", new object[1] { PortalPinJson(pos, "", add: true, remove: false) });
			}
		}
	}

	[HarmonyPatch(typeof(TeleportWorld), "SetText")]
	private class TeleportWorld_SetText
	{
		private static void Postfix(TeleportWorld __instance, string text)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (settings.wherePortal)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "PlacePortal", new object[1] { PortalPinJson(((Component)__instance).transform.position, text, add: true, remove: true) });
			}
		}
	}

	[HarmonyPatch(typeof(Piece), "DropResources")]
	private class Piece_DropResources
	{
		private static void Prefix(Piece __instance)
		{
			if (settings.structureLoot && !__instance.IsPlacedByPlayer())
			{
				overridePieceDrops = true;
			}
		}

		private static void Postfix(Piece __instance)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			overridePieceDrops = false;
			if (settings.wherePortal && (Object)(object)((Component)__instance).GetComponent<TeleportWorld>() != (Object)null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "PlacePortal", new object[1] { PortalPinJson(((Component)__instance).transform.position, "", add: false, remove: true) });
			}
		}
	}

	[HarmonyPatch(typeof(Piece), "FreeBuildKey")]
	private class Piece_FreeBuildKey
	{
		private static bool Prefix(Piece __instance, ref GlobalKeys __result)
		{
			if (settings.structureLoot && overridePieceDrops && !__instance.IsPlacedByPlayer())
			{
				__result = (GlobalKeys)2;
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(ZoneSystem), "PlaceVegetation")]
	private class ZoneSystem_PlaceVegetation
	{
		private static void Prefix(ZoneSystem __instance)
		{
			if (!settings.alwaysRocky || rockyied)
			{
				return;
			}
			foreach (ZoneVegetation item in __instance.m_vegetation)
			{
				if ((Object)(object)item.m_prefab != (Object)null && ((Object)item.m_prefab).name == "Pickable_Stone")
				{
					item.m_prefab = ZNetScene.instance.GetPrefab("Pickable_StoneRock");
				}
			}
			rockyied = true;
		}
	}

	[HarmonyPatch(typeof(Pickable), "Awake")]
	private class Pickable_Awake
	{
		private static void Prefix(Pickable __instance)
		{
			if (settings.alwaysRocky && ((Object)__instance.m_itemPrefab).name == "Stone")
			{
				__instance.m_itemPrefab = ObjectDB.instance.GetItemPrefab("StoneRock");
			}
		}
	}

	public const string PluginGUID = "com.lukkster.Speedchoice";

	public const string PluginName = "Speedchoice";

	public const string PluginVersion = "1.0.0";

	private readonly Harmony harmony = new Harmony("com.lukkster.Speedchoice");

	private static Speedchoice speedchoice;

	private static Settings settings = new Settings();

	private static readonly Dictionary<string, Profile> profiles = new Dictionary<string, Profile>
	{
		{
			"Speedchoice",
			new Profile(new List<string> { "eventrate 0", "teleportall", "nobuildcost" }, "Recommended Speedchoice settings. Faster gameplay, no grinding required, and Boss Reveals make the whole game completable in one sitting.", new Dictionary<string, float>
			{
				{ "Boat Speed", 2f },
				{ "Time to Rest", 1f },
				{ "Trophy Odds", 2f }
			}, new Dictionary<string, bool>
			{
				{ "Boss Reveals", true },
				{ "Boss Skills", true },
				{ "Cheat Death", true },
				{ "Drop Materials", true },
				{ "Fast Crops", true },
				{ "Fast Fermenters", true },
				{ "Harmless Pieces", true },
				{ "Increased Exp", false },
				{ "Instant Upgrades", true },
				{ "Lootless Bosses", false },
				{ "No Build Stations", true },
				{ "No Craft Cost", true },
				{ "No Craft Levels", false },
				{ "Show Deaths", true },
				{ "Show Logouts", true },
				{ "Show Timer", true },
				{ "Structure Loot", true },
				{ "Where's my Portal?", true }
			})
		},
		{
			"Trailblazer",
			new Profile(new List<string> { "deathkeepequip", "skillreductionrate 15", "resourcerate 200", "eventrate 0", "teleportall", "nobuildcost" }, "OatHorse's Trailblazer settings, without the trophy hunt aspect.", new Dictionary<string, float>
			{
				{ "Boat Speed", 2f },
				{ "Time to Rest", 1f },
				{ "Trophy Odds", 4f }
			}, new Dictionary<string, bool>
			{
				{ "Boss Reveals", true },
				{ "Boss Skills", true },
				{ "Cheat Death", true },
				{ "Drop Materials", false },
				{ "Fast Crops", true },
				{ "Fast Fermenters", true },
				{ "Harmless Pieces", false },
				{ "Increased Exp", true },
				{ "Instant Upgrades", false },
				{ "Lootless Bosses", false },
				{ "No Build Stations", true },
				{ "No Craft Cost", true },
				{ "No Craft Levels", true },
				{ "Show Deaths", true },
				{ "Show Logouts", true },
				{ "Show Timer", true },
				{ "Structure Loot", true },
				{ "Where's my Portal?", true }
			})
		},
		{
			"Blazing",
			new Profile(new List<string> { "eventrate 0", "teleportall", "nobuildcost" }, "Accelerated version of a Reverse Boss playthrough. Defeat the bosses in order, and get rewarded in Skill Levels. However, the bosses have no drops. Thus no Forsaken Powers, or Moder's Tears for late game crafting.", new Dictionary<string, float>
			{
				{ "Boat Speed", 2f },
				{ "Time to Rest", 2f },
				{ "Trophy Odds", 2f }
			}, new Dictionary<string, bool>
			{
				{ "Boss Reveals", true },
				{ "Boss Skills", true },
				{ "Cheat Death", true },
				{ "Drop Materials", true },
				{ "Fast Crops", true },
				{ "Fast Fermenters", true },
				{ "Harmless Pieces", true },
				{ "Increased Exp", false },
				{ "Instant Upgrades", true },
				{ "Lootless Bosses", true },
				{ "No Build Stations", true },
				{ "No Craft Cost", true },
				{ "No Craft Levels", false },
				{ "Show Deaths", true },
				{ "Show Logouts", true },
				{ "Show Timer", true },
				{ "Structure Loot", true },
				{ "Where's my Portal?", true }
			})
		}
	};

	private static readonly SortedDictionary<string, Range> ranges = new SortedDictionary<string, Range>
	{
		{
			"Boat Speed",
			new Range(() => settings.boatSpeed, delegate(float val)
			{
				settings.boatSpeed = val;
			}, "Changes the speed at which ships sail.", new List<RangeOption>
			{
				new RangeOption("Normal", "Boats travel normally."),
				new RangeOption("Fast", "Boats are 2.5 times faster, 2 times faster while paddling."),
				new RangeOption("Dangerous", "Boats are 10 times faster, 8 times faster while paddling."),
				new RangeOption("Capsize", "Boats travel ... faster.")
			})
		},
		{
			"Time to Rest",
			new Range(() => settings.timeToRest, delegate(float val)
			{
				settings.timeToRest = val;
			}, "Adjusts how long it takes to become rested.", new List<RangeOption>
			{
				new RangeOption("Normal", "The default of 20 seconds."),
				new RangeOption("Fast", "Spend 10 seconds to become rested."),
				new RangeOption("Instant", "Resting happens instantly.")
			})
		},
		{
			"Trophy Odds",
			new Range(() => settings.trophyOdds, delegate(float val)
			{
				settings.trophyOdds = val;
			}, "Adds an extra reroll for trophy drops to all enemies.", new List<RangeOption>
			{
				new RangeOption("Normal", "Vanilla drop rates."),
				new RangeOption("More", "Trophies drop 25%, multiplicity, more often. Thus a Deer trophy would have 62.5% drop rate, boosted from it's vanilla 50%. A Deathsquito trophy would have 28.75%, from 5%."),
				new RangeOption("Often", "Trophies drop 50%, multiplicity, more often. Thus 50% -> 75%, and 5% -> 52.5"),
				new RangeOption("Frequently", "Trophies drop 75%, multiplicity, more often. Thus 50% -> 87.5%, and 5% -> 76.25%"),
				new RangeOption("Always", "All creatures that can drop trophies, will drop trophies.")
			})
		}
	};

	private static readonly Dictionary<string, CheckBox> checkBoxes = new Dictionary<string, CheckBox>
	{
		{
			"Boss Reveals",
			new CheckBox(() => settings.bossReveals, delegate(bool val)
			{
				settings.bossReveals = val;
			}, "Upon defeating a Forsaken, the next Forsaken's locations are revealed.")
		},
		{
			"Boss Skills",
			new CheckBox(() => settings.bossSkills, delegate(bool val)
			{
				settings.bossSkills = val;
			}, "Upon defeating a Forsaken, all skills will be leveled up.")
		},
		{
			"Lootless Bosses",
			new CheckBox(() => settings.lootlessBosses, delegate(bool val)
			{
				settings.lootlessBosses = val;
			}, "Forsaken do not drop items, including both their Trophies, and their \"progressive\" materials.")
		},
		{
			"Cheat Death",
			new CheckBox(() => settings.cheatDeath, delegate(bool val)
			{
				settings.cheatDeath = val;
			}, "If one logs out shortly after dying, they'll log in where they died rather than their spawn point.")
		},
		{
			"Drop Materials",
			new CheckBox(() => settings.dropMaterials, delegate(bool val)
			{
				settings.dropMaterials = val;
			}, "Materials, items used for crafting exclusively, are immediately removed from the inventory.")
		},
		{
			"Harmless Pieces",
			new CheckBox(() => settings.harmlessPieces, delegate(bool val)
			{
				settings.harmlessPieces = val;
			}, "Player built structures, such as campfires or spikes, do no damage to creatures.")
		},
		{
			"Fast Crops",
			new CheckBox(() => settings.fastCrops, delegate(bool val)
			{
				settings.fastCrops = val;
			}, "Crops grow quickly.")
		},
		{
			"Fast Fermenters",
			new CheckBox(() => settings.fastFermenters, delegate(bool val)
			{
				settings.fastFermenters = val;
			}, "Fermenters brew quickly.")
		},
		{
			"Increased Exp",
			new CheckBox(() => settings.increasedExp, delegate(bool val)
			{
				settings.increasedExp = val;
			}, "Increases Skill experience gains by 500%.")
		},
		{
			"Instant Upgrades",
			new CheckBox(() => settings.instantUpgrades, delegate(bool val)
			{
				settings.instantUpgrades = val;
			}, "Instantly upgrades any upgradeable tool or armor.")
		},
		{
			"Structure Loot",
			new CheckBox(() => settings.structureLoot, delegate(bool val)
			{
				settings.structureLoot = val;
			}, "Naturally occurring structures, such as houses, will drop into materials when deconstructed with a hammer in \"No Build Cost\".")
		},
		{
			"Where's my Portal?",
			new CheckBox(() => settings.wherePortal, delegate(bool val)
			{
				settings.wherePortal = val;
			}, "Adds a portal pin to the map upon placing a portal.")
		},
		{
			"No Build Stations",
			new CheckBox(() => settings.noBuildStations, delegate(bool val)
			{
				settings.noBuildStations = val;
			}, "Player built pieces can be constructed without the required nearby crafting stations. For instance a Portal can be built without a nearby Workbench.")
		},
		{
			"No Craft Cost",
			new CheckBox(() => settings.noCraftCost, delegate(bool val)
			{
				settings.noCraftCost = val;
			}, "Items can be crafted without consuming or requiring the materials to do so.")
		},
		{
			"No Craft Levels",
			new CheckBox(() => settings.noCraftLevels, delegate(bool val)
			{
				settings.noCraftLevels = val;
			}, "Items can be crafted without the prerequisite Crafting Station Level to do so.")
		},
		{
			"Show Deaths",
			new CheckBox(() => settings.showDeaths, delegate(bool val)
			{
				settings.showDeaths = val;
			}, "Adds an UI element showing the number of Deaths.")
		},
		{
			"Show Logouts",
			new CheckBox(() => settings.showLogouts, delegate(bool val)
			{
				settings.showLogouts = val;
			}, "Adds an UI element showing the number of Logouts.")
		},
		{
			"Show Timer",
			new CheckBox(() => settings.showTimer, delegate(bool val)
			{
				settings.showTimer = val;
			}, "Adds an UI element showing how long there has been activity in the world. Starts on first input, and pauses when the game pauses.")
		}
	};

	private static readonly List<Prefab> harmingPrefabs = new List<Prefab>
	{
		new Prefab("piece_sharpstakes", "HIT AREA", new DamageTypes
		{
			m_pierce = 15f
		}),
		new Prefab("piece_dvergr_sharpstakes", "Colliders/HIT AREA", new DamageTypes
		{
			m_pierce = 15f
		}),
		new Prefab("piece_stakewall_blackwood", "HIT AREA", new DamageTypes
		{
			m_pierce = 120f
		}),
		new Prefab("piece_brazierfloor02", "_enabled_high/FireBurn", new DamageTypes
		{
			m_fire = 10f
		}),
		new Prefab("bonfire", "_enabled/FireBurn", new DamageTypes
		{
			m_fire = 20f
		}),
		new Prefab("fire_pit", "_enabled_high/FireBurn", new DamageTypes
		{
			m_fire = 10f
		}),
		new Prefab("piece_brazierceiling01", "_enabled_high/FireBurn", new DamageTypes
		{
			m_fire = 10f
		}),
		new Prefab("hearth", "_enabled_high/FireBurn", new DamageTypes
		{
			m_fire = 10f
		}),
		new Prefab("fire_pit_iron", "_enabled_high/FireBurn", new DamageTypes
		{
			m_fire = 10f
		}),
		new Prefab("piece_brazierfloor01", "_enabled_high/FireBurn", new DamageTypes
		{
			m_fire = 10f
		}),
		new Prefab("piece_trap_troll", "Damage Area", new DamageTypes
		{
			m_blunt = 50f,
			m_pierce = 50f,
			m_chop = 50f
		})
	};

	private static readonly Dictionary<float, float> boatSpeeds = new Dictionary<float, float>
	{
		{ 1f, 2.5f },
		{ 2f, 10f },
		{ 3f, 100f }
	};

	private static readonly Dictionary<float, float> restDelays = new Dictionary<float, float>
	{
		{ 1f, 10f },
		{ 2f, 0f }
	};

	private static readonly Dictionary<string, string> trophies = new Dictionary<string, string>
	{
		{ "$enemy_abomination", "TrophyAbomination" },
		{ "$enemy_asksvin", "TrophyAsksvin" },
		{ "$enemy_bjorn", "TrophyBjorn" },
		{ "$enemy_blob", "TrophyBlob" },
		{ "$enemy_blobelite", "TrophyBlob" },
		{ "$enemy_blobtar", "TrophyGrowth" },
		{ "$enemy_boar", "TrophyBoar" },
		{ "$enemy_bonemass", "TrophyBonemass" },
		{ "$enemy_bonemawserpent", "TrophyBonemawSerpent" },
		{ "$enemy_charred_archer", "TrophyCharredArcher" },
		{ "$enemy_charred_mage", "TrophyCharredMage" },
		{ "$enemy_charred_melee", "TrophyCharredMelee" },
		{ "$enemy_deathsquito", "TrophyDeathsquito" },
		{ "$enemy_deer", "TrophyDeer" },
		{ "$enemy_dragon", "TrophyDragonQueen" },
		{ "$enemy_drake", "TrophyHatchling" },
		{ "$enemy_draugr", "TrophyDraugr" },
		{ "$enemy_draugrelite", "TrophyDraugrElite" },
		{ "$enemy_dvergr", "TrophyDvergr" },
		{ "$enemy_dvergr_mage", "TrophyDvergr" },
		{ "$enemy_eikthyr", "TrophyEikthyr" },
		{ "$enemy_fader", "TrophyFader" },
		{ "$enemy_fallenvalkyrie", "TrophyFallenValkyrie" },
		{ "$enemy_fenring", "TrophyFenring" },
		{ "$enemy_fenringcultist", "TrophyCultist" },
		{ "$enemy_fenringcultist_hildir", "TrophyCultist_Hildir" },
		{ "$enemy_gdking", "TrophyTheElder" },
		{ "$enemy_ghost", "TrophyGhost" },
		{ "$enemy_gjall", "TrophyGjall" },
		{ "$enemy_goblin", "TrophyGoblin" },
		{ "$enemy_goblin_hildir", "TrophyGoblinBruteBrosShaman" },
		{ "$enemy_goblinbrute", "TrophyGoblinBrute" },
		{ "$enemy_goblinbrute_hildircombined", "TrophyGoblinBruteBrosBrute" },
		{ "$enemy_goblinking", "TrophyGoblinKing" },
		{ "$enemy_goblinshaman", "TrophyGoblinShaman" },
		{ "$enemy_greydwarf", "TrophyGreydwarf" },
		{ "$enemy_greydwarfbrute", "TrophyGreydwarfBrute" },
		{ "$enemy_greydwarfshaman", "TrophyGreydwarfShaman" },
		{ "$enemy_hare", "TrophyHare" },
		{ "$enemy_kvastur", "TrophyKvastur" },
		{ "$enemy_leech", "TrophyLeech" },
		{ "$enemy_lox", "TrophyLox" },
		{ "$enemy_morgen", "TrophyMorgen" },
		{ "$enemy_neck", "TrophyNeck" },
		{ "$enemy_seeker", "TrophySeeker" },
		{ "$enemy_seekerbrute", "TrophySeekerBrute" },
		{ "$enemy_seekerqueen", "TrophySeekerQueen" },
		{ "$enemy_serpent", "TrophySerpent" },
		{ "$enemy_skeleton", "TrophySkeleton" },
		{ "$enemy_skeletonfire", "TrophySkeletonHildir" },
		{ "$enemy_skeletonpoison", "TrophySkeletonPoison" },
		{ "$enemy_stonegolem", "TrophySGolem" },
		{ "$enemy_surtling", "TrophySurtling" },
		{ "$enemy_thehive,", "TrophyHatchling" },
		{ "$enemy_tick", "TrophyTick" },
		{ "$enemy_troll", "TrophyFrostTroll" },
		{ "$enemy_ulv", "TrophyUlv" },
		{ "$enemy_unbjorn", "TrophyBjornUndead" },
		{ "$enemy_volture", "TrophyVolture" },
		{ "$enemy_wolf", "TrophyWolf" },
		{ "$enemy_wraith", "TrophyWraith" }
	};

	private static readonly Dictionary<float, float> trophyOdds = new Dictionary<float, float>
	{
		{ 1f, 0.25f },
		{ 2f, 0.5f },
		{ 3f, 0.75f },
		{ 4f, 1f }
	};

	private const float bossRadius = 500f;

	private const float vendorRadius = 100f;

	private static readonly Dictionary<string, List<Poi>> reveals = new Dictionary<string, List<Poi>>
	{
		{
			"$enemy_eikthyr",
			new List<Poi>
			{
				new Poi("GDKing", (PinType)9, "$enemy_gdking", 500f),
				new Poi("Vendor_BlackForest", (PinType)3, "Haldor", 100f)
			}
		},
		{
			"$enemy_gdking",
			new List<Poi>
			{
				new Poi("Bonemass", (PinType)9, "$enemy_bonemass", 500f),
				new Poi("BogWitch_Camp", (PinType)3, "BogWitch", 100f)
			}
		},
		{
			"$enemy_bonemass",
			new List<Poi>
			{
				new Poi("Dragonqueen", (PinType)9, "$enemy_dragon", 500f)
			}
		},
		{
			"$enemy_dragon",
			new List<Poi>
			{
				new Poi("GoblinKing", (PinType)9, "$enemy_goblinking", 500f),
				new Poi("Hildir_camp", (PinType)3, "Hildir", 100f)
			}
		},
		{
			"$enemy_goblinking",
			new List<Poi>
			{
				new Poi("Mistlands_DvergrBossEntrance1", (PinType)9, "$enemy_seekerqueen", 500f)
			}
		},
		{
			"$enemy_seekerqueen",
			new List<Poi>
			{
				new Poi("FaderLocation", (PinType)9, "$enemy_fader_codename", 500f),
				new Poi("PlaceofMystery1", (PinType)3, "Mysterious Location", 100f)
			}
		}
	};

	private static readonly Dictionary<string, int> levels = new Dictionary<string, int>
	{
		{ "$enemy_fader", 100 },
		{ "$enemy_seekerqueen", 80 },
		{ "$enemy_goblinking", 60 },
		{ "$enemy_dragon", 50 },
		{ "$enemy_bonemass", 40 },
		{ "$enemy_gdking", 30 },
		{ "$enemy_eikthyr", 20 }
	};

	private static readonly List<ItemType> drops = new List<ItemType>
	{
		(ItemType)1,
		(ItemType)13
	};

	private static readonly List<string> exhausts = new List<string> { "$item_barberkit", "$item_barleyflour", "$item_barrelrings", "$item_dragontear", "$item_scythehandle", "$item_yagluththing" };

	private static readonly List<string> retains = new List<string>
	{
		"$item_catapult_ammo", "$item_bonefragments", "$item_catapult_training_ammo", "$item_charredbone", "$item_eitr", "$item_asksvin_meat", "$item_barley", "$item_bjorn_meat", "$item_bonemawmeat", "$item_breaddough",
		"$item_bug_meat", "$item_chicken_meat", "$item_deer_meat", "$item_fishandbreaduncooked", "$item_fish_raw", "$item_fish_raw", "$item_hare_meat", "$item_honeyglazedchickenuncooked", "$item_loxmeat", "$item_loxpie_uncooked",
		"$item_magicallystuffedmushroomuncooked", "$item_meatplatteruncooked", "$item_mistharesupremeuncooked", "$item_necktail", "$item_piquantpie_uncooked", "$item_boar_meat", "$item_roastedcrustpie_uncooked", "$item_serpentmeat", "$item_vikingcupcake_uncooked", "$item_volture_meat",
		"$item_wolf_meat", "$item_blackcore", "$item_fireworkrocket_blue", "$item_fireworkrocket_cyan", "$item_fireworkrocket_green", "$item_fireworkrocket_purple", "$item_fireworkrocket_red", "$item_fireworkrocket_white", "$item_fireworkrocket_yellow", "$item_resin",
		"$item_surtlingcore", "$item_thunderstone", "$item_trophy_bonemass", "$item_trophy_deer", "$item_trophy_dragonqueen", "$item_trophy_eikthyr", "$item_trophy_fader", "$item_trophy_goblinking", "$item_trophy_seeker_brute", "$item_trophy_seekerqueen",
		"$item_trophy_elder", "$item_witheredbone", "$item_barleywinebase", "$item_meadbasebugrepellent", "$item_meadbasebzerker", "$item_meadbaseeitr_lingering", "$item_meadbaseeitr", "$item_meadbasefrostresist", "$item_meadbasehasty", "$item_meadbasehealth_lingering",
		"$item_meadbasehealth_major", "$item_meadbasehealth_medium", "$item_meadbasehealth", "$item_meadbaselightfoot", "$item_meadbasepoisonresist", "$item_meadbasestamina_lingering", "$item_meadbasestamina_medium", "$item_meadbasestamina", "$item_meadbasestrength", "$item_meadbaseswimmer",
		"$item_meadbasetamer", "$item_meadbasetasty", "$item_amber", "$item_amberpearl", "$item_coins", "$item_ruby", "$item_silvernecklace", "$item_blackmetalscrap", "$item_bronzescrap", "$item_coal",
		"$item_copperore", "$item_copperscrap", "$item_finewood", "$item_flametalore_old", "$item_flametalore", "$item_flax", "$item_ironore", "$item_ironscrap", "$item_roundlog", "$item_sap",
		"$item_silverore", "$item_softtissue", "$item_tinore", "$item_wood", "$item_beechseeds", "$item_birchseeds", "$item_carrotseeds", "$item_dandelion", "$item_onionseeds", "$item_turnip",
		"$item_turnipseeds"
	};

	private static Dictionary<string, Recipe> upgradeAbles = new Dictionary<string, Recipe>();

	private static TMP_FontAsset font;

	private static TextMeshProUGUI deaths;

	private static readonly string logoutsKey = "logouts";

	private static TextMeshProUGUI logouts;

	private static TextMeshProUGUI timer;

	private static bool unlockedRecipes = false;

	private static bool isSynced = false;

	private static bool overridePieceDrops = false;

	private static bool rockyied = false;

	private void Start()
	{
		harmony.PatchAll();
		speedchoice = this;
	}

	private static string GetSavePath(World world)
	{
		return GetSavePath(world.m_name);
	}

	private static string GetSavePath(string name)
	{
		return Path.Combine(Path.Combine(Utils.GetSaveDataPath((FileSource)1), "worlds"), name + "_speedchoice.json");
	}

	private static string FromSettings()
	{
		return JsonConvert.SerializeObject((object)settings, (Formatting)1);
	}

	private static void ToSettings(string json)
	{
		settings = JsonConvert.DeserializeObject<Settings>(json);
	}

	private static void Save(World world)
	{
		File.WriteAllText(GetSavePath(world), FromSettings());
	}

	private static void Load(World world)
	{
		if (File.Exists(GetSavePath(world)))
		{
			ToSettings(File.ReadAllText(GetSavePath(world)));
		}
		else
		{
			settings = new Settings();
		}
	}

	private static void RemoveItem(Inventory inventory, ItemData itemData)
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		if (settings.dropMaterials && (drops.Contains(itemData.m_shared.m_itemType) || exhausts.Contains(itemData.m_shared.m_name)) && !retains.Contains(itemData.m_shared.m_name))
		{
			inventory.RemoveItem(itemData);
		}
	}

	private static void UpgradeInventory(Player player)
	{
		if (!settings.instantUpgrades)
		{
			return;
		}
		CraftingStation currentCraftingStation = player.GetCurrentCraftingStation();
		if ((Object)(object)currentCraftingStation == (Object)null)
		{
			return;
		}
		foreach (ItemData allItem in ((Humanoid)player).GetInventory().GetAllItems())
		{
			if (upgradeAbles.TryGetValue(allItem.m_shared.m_name, out var value) && (((Object)(object)value.m_craftingStation != (Object)null && currentCraftingStation.m_name == value.m_craftingStation.m_name) || ((Object)(object)value.m_craftingStation == (Object)null && currentCraftingStation.m_name == "$piece_workbench")))
			{
				int num = MaxLevel(currentCraftingStation, value);
				if (allItem.m_quality < num)
				{
					allItem.m_quality = num;
					allItem.m_durability = allItem.m_shared.m_maxDurability + allItem.m_shared.m_durabilityPerLevel * (float)allItem.m_quality;
				}
			}
		}
	}

	private static int MaxLevel(CraftingStation station, Recipe recipe)
	{
		if (settings.noCraftLevels)
		{
			return 4;
		}
		int num = 1;
		if ((Object)(object)station != (Object)null)
		{
			num = station.GetLevel(true);
		}
		int num2 = num - recipe.m_minStationLevel;
		if (recipe.m_minStationLevel != 0)
		{
			num2++;
		}
		if (num2 > 4)
		{
			num2 = 4;
		}
		return num2;
	}

	private static Sprite GetItemIcon(string itemPrefab)
	{
		return ObjectDB.instance.GetItemPrefab(itemPrefab).GetComponent<ItemDrop>().m_itemData.m_shared.m_icons[0];
	}

	private static void UpdateDeaths()
	{
		if ((Object)(object)deaths != (Object)null)
		{
			((TMP_Text)deaths).text = Game.instance.GetPlayerProfile().m_playerStats[(PlayerStatType)0].ToString();
		}
	}

	private static void UpdateLogouts()
	{
		if (Player.m_localPlayer.m_customData.TryGetValue(logoutsKey, out var value))
		{
			((TMP_Text)logouts).text = value;
		}
		else
		{
			((TMP_Text)logouts).text = "0";
		}
	}

	private static IEnumerator TimerUpdate()
	{
		while (true)
		{
			if (!Game.IsPaused())
			{
				if ((Object)(object)timer != (Object)null)
				{
					((TMP_Text)timer).text = $"<mspace=0.5em>{TimeSpan.FromSeconds(settings.time)}</mspace>";
				}
				settings.time++;
			}
			yield return (object)new WaitForSeconds(1f);
		}
	}

	private static string PortalPinJson(Vector3 vector, string text, bool add, bool remove)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		return JsonConvert.SerializeObject((object)new PortalPin(vector, text, add, remove));
	}
}