Decompiled source of D20Plugin v3.0.2

D20Plugin.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Bounce.ManagedCollections;
using Bounce.Singletons;
using Bounce.Unmanaged;
using Dice;
using GameChat.UI;
using HarmonyLib;
using ModdingTales;
using Newtonsoft.Json;
using RadialUI;
using TMPro;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("D20Plugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nth Dimension")]
[assembly: AssemblyProduct("D20Plugin")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("D20Plugin")]
[assembly: ComVisible(false)]
[assembly: Guid("c303405d-e66c-4316-9cdb-4e3ca15c6360")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("3.0.0.0")]
namespace LordAshes;

[BepInPlugin("org.lordashes.plugins.d20", "D20 Plugin", "3.0.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class PluginD20 : BaseUnityPlugin
{
	public static class Characters
	{
		public class SpecPair
		{
			public string key { get; set; } = "key";

			public string value { get; set; } = "Undefined";

			public SpecPair()
			{
			}

			public SpecPair(string key)
			{
				this.key = key;
				value = "Undefined";
			}

			public SpecPair(string key, string value)
			{
				this.key = key;
				this.value = value;
			}
		}

		public class Spec
		{
			public string name { get; set; } = "Skill";

			public string formula { get; set; } = null;

			public List<SpecPair> extra { get; set; } = null;

			public string menu { get; set; } = null;

			public Spec(string name, string formula, List<SpecPair> extra = null, string menu = null)
			{
				this.name = name;
				this.formula = formula;
				this.extra = extra;
				this.menu = menu;
			}

			public string Extra(string name)
			{
				return extra.Where((SpecPair e) => e.key == name).FirstOrDefault()?.value;
			}
		}

		public class CharacterSpecs
		{
			public string name { get; set; } = "Unnamed";

			public string chainSources { get; set; } = null;

			public List<Spec> specs { get; set; } = new List<Spec>();

			public void AddAbilityScore(string name, string value, string menu = null)
			{
				specs.Add(new Spec(name, ((int.Parse(value) >= 10) ? ((int.Parse(value) - 10) / 2) : ((int.Parse(value) - 11) / 2)).ToString(), new List<SpecPair>
				{
					new SpecPair("type", "ability"),
					new SpecPair("value", value)
				}, menu));
			}

			public void AddValue(string name, string value, string menu = null)
			{
				specs.Add(new Spec(name, value, new List<SpecPair>
				{
					new SpecPair("type", "value")
				}, menu));
			}

			public void AddSave(string name, string formula, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "save")
				}, menu));
			}

			public void AddSkill(string name, string formula, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "skill")
				}, menu));
			}

			public void AddSkill(string name, string formula, string opposed, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "skill"),
					new SpecPair("opposed", opposed)
				}, menu));
			}

			public void AddAttack(string name, string formula, string opposed, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "attack"),
					new SpecPair("opposed", opposed)
				}, menu));
			}

			public void AddDamage(string name, string formula, string damageType, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "damage"),
					new SpecPair("damageType", damageType)
				}, menu));
			}

			public void AddHealing(string name, string formula, string menu = null)
			{
				specs.Add(new Spec(name, formula, new List<SpecPair>
				{
					new SpecPair("type", "heal")
				}, menu));
			}

			public void AddResistances(string name, string list, string damageType, string menu = null)
			{
				List<SpecPair> list2 = new List<SpecPair>();
				string[] array = list.Split(new char[1] { ',' });
				foreach (string text in array)
				{
					list2.Add(new SpecPair(text, text));
				}
				specs.Add(new Spec("Resistances", list, list2, menu));
			}

			public void AddImmunities(string name, string list, string damageType, string menu = null)
			{
				List<SpecPair> list2 = new List<SpecPair>();
				string[] array = list.Split(new char[1] { ',' });
				foreach (string text in array)
				{
					list2.Add(new SpecPair(text, text));
				}
				specs.Add(new Spec("Immunities", list, list2, menu));
			}

			public void AddVulnerabilities(string name, string list, string damageType, string menu = null)
			{
				List<SpecPair> list2 = new List<SpecPair>();
				string[] array = list.Split(new char[1] { ',' });
				foreach (string text in array)
				{
					list2.Add(new SpecPair(text, text));
				}
				specs.Add(new Spec("Resistances", list, list2, menu));
			}

			public void AddOrModifyValue(string name, string value, string menu = null)
			{
				Spec spec = FindFirst(name);
				if (spec == null)
				{
					specs.Add(new Spec(name, value, new List<SpecPair>
					{
						new SpecPair("type", "value")
					}, menu));
				}
				else
				{
					spec.formula = value;
				}
			}

			public string Resolve(string formula, int replacements = 0)
			{
				LoggingPlugin.LogTrace("Processing Resolve: Formula=" + (formula ?? "Empty Formula") + ", Max Replacements=" + replacements);
				if (formula == null || formula.Trim() == "")
				{
					return "";
				}
				int num = 0;
				string text = "";
				for (int i = 0; i < nestedResolve; i++)
				{
					foreach (Spec spec in specs)
					{
						foreach (SpecPair item in spec.extra)
						{
							LoggingPlugin.LogTrace("Processing Resolve: Replacing [" + spec.name + "." + item.key + "] With " + item.value);
							text = formula;
							formula = formula.Replace("[" + spec.name + "." + item.key + "]", item.value);
							if (text != formula)
							{
								num++;
							}
							if (replacements > 0 && num >= replacements)
							{
								LoggingPlugin.LogTrace("Processing Resolve: Max Replacement " + replacements + " Resolve: " + formula);
								return formula;
							}
							LoggingPlugin.LogTrace("Processing Resolve: Formula=" + formula + ", Replacements Count=" + num);
						}
						LoggingPlugin.LogTrace("Processing Resolve: Replacing [" + spec.name + "] With " + spec.formula.ToString());
						text = formula;
						formula = formula.Replace("[" + spec.name + "]", spec.formula.ToString());
						formula = formula.Replace("+-", "-").Replace("-+", "-").Replace("--", "+")
							.Replace("++", "+");
						if (text != formula)
						{
							num++;
						}
						if (replacements > 0 && num >= replacements)
						{
							LoggingPlugin.LogTrace("Processing Resolve: Max Replacement " + replacements + " Resolve: " + formula);
							return formula;
						}
						LoggingPlugin.LogTrace("Processing Resolve: Formula=" + formula + ", Replacements Count=" + num);
					}
				}
				LoggingPlugin.LogTrace("Processing Resolve: Full Resolve: " + formula);
				return formula;
			}

			public Spec[] Find(string whereClause)
			{
				if (specs == null || specs.Count == 0 || string.IsNullOrWhiteSpace(whereClause))
				{
					return null;
				}
				if (whereClause.IndexOf("=") < 0 && whereClause.IndexOf("<") < 0 && whereClause.IndexOf(">") < 0)
				{
					whereClause = "name==\"" + whereClause + "\"";
				}
				LoggingPlugin.LogTrace("Find: " + whereClause);
				return DynamicQueryableExtensions.Where<Spec>(specs.AsQueryable(), whereClause, Array.Empty<object>()).ToArray();
			}

			public Spec FindFirst(string whereClause)
			{
				Spec[] array = Find(whereClause);
				LoggingPlugin.LogTrace("FindFirst: " + ((array != null) ? array.Length.ToString() : "0") + " Matches");
				return (array != null && array.Count() > 0) ? array[0] : null;
			}

			public string FindFirstValue(string whereClause)
			{
				Spec spec = FindFirst(whereClause);
				LoggingPlugin.LogTrace("FindFirstValue: " + ((spec != null) ? (spec.name + "=" + spec.formula) : "Null"));
				return (spec != null) ? spec.formula : "";
			}

			public string FindFirstExtraValue(string whereClause, string property)
			{
				Spec spec = FindFirst(whereClause);
				return (spec != null) ? spec.extra.Where((SpecPair p) => p.key == property).FirstOrDefault().value : "";
			}

			public CreatureBoardAsset FindAsset()
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return ((IEnumerable<CreatureBoardAsset>)(object)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets()).Where((CreatureBoardAsset a) => a.Name.Contains(name)).FirstOrDefault();
			}

			public CreatureBoardAsset[] FindAssets()
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return ((IEnumerable<CreatureBoardAsset>)(object)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets()).Where((CreatureBoardAsset a) => a.Name.Contains(name)).ToArray();
			}
		}

		public class CharactersSpecs
		{
			public enum CheckType
			{
				Regular = 1,
				Opposed,
				Attack,
				Damage,
				Effect,
				Heal,
				Generic
			}

			private List<CharacterSpecs> sheets = new List<CharacterSpecs>();

			private List<string> builtPaths = new List<string>();

			public static Sprite fallbackSprite = Image.LoadSprite("org.lordashes.plugins.d20.character.png", (CacheType)999);

			public List<CharacterSpecs> All()
			{
				return sheets;
			}

			public void Add(CharacterSpecs specs)
			{
				sheets.Add(specs);
			}

			public void Remove(string name)
			{
				for (int i = 0; i < sheets.Count; i++)
				{
					if (sheets[i].name == name)
					{
						sheets.RemoveAt(i);
						i--;
					}
				}
			}

			public void LoadCharacters(bool reload = false)
			{
				//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
				//IL_011c: Expected O, but got Unknown
				sheets.Clear();
				builtPaths.Clear();
				string[] array = File.Find("org.lordashes.plugins.d20.character.", (CacheType)999);
				foreach (string text in array)
				{
					if (text.ToLower().EndsWith(".json"))
					{
						LoadCharacter(text);
					}
				}
				LoggingPlugin.LogInfo("Loaded " + _self.characters.sheets.Count + " Character Sheets");
				if (!reload)
				{
					RadialUIPlugin.AddCustomButtonOnCharacter("org.lordashes.plugins.d20", new ItemArgs
					{
						Action = delegate
						{
							//IL_000e: Unknown result type (might be due to invalid IL or missing references)
							LoggingPlugin.LogTrace("Selected Character Menu. Triggering Deep Menu...");
							CreatureBoardAsset val = null;
							CreaturePresenter.TryGetAsset(LocalClient.SelectedCreatureId, ref val);
							DeepMenusPlugin.NavigateTo(DiceRoller.StripTrailingInteger(val.Name));
						},
						CloseMenuOnActivate = true,
						FadeName = true,
						Icon = LoadSpriteOrDefault("org.lordashes.plugins.d20.character.png", fallbackSprite),
						Title = "Actions"
					}, (Func<NGuid, NGuid, bool>)delegate
					{
						//IL_000e: Unknown result type (might be due to invalid IL or missing references)
						CreatureBoardAsset instigator = null;
						CreaturePresenter.TryGetAsset(LocalClient.SelectedCreatureId, ref instigator);
						if ((Object)(object)instigator != (Object)null)
						{
							LoggingPlugin.LogDebug("Looking for Sheet For '" + DiceRoller.StripTrailingInteger(instigator.Name) + "'");
							return _self.characters.sheets.Any((CharacterSpecs c) => c.name == DiceRoller.StripTrailingInteger(instigator.Name));
						}
						return false;
					});
				}
				foreach (CharacterSpecs character in sheets)
				{
					DeepMenusPlugin._self.CreateSubMenuItem("/" + character.name, DeepMenusPlugin._self.MakeItemEntry("Edit", (Action<string, string>)delegate
					{
						LoadUserSettings(_self.characters.FindFirst(character.name));
						menuEditOpen = true;
						GameInputEnabled(!menuEditOpen);
					}, LoadSpriteOrDefault("org.lordashes.plugins.d20.edit.png", fallbackSprite), false, true), (Func<bool>)(() => true));
					foreach (Spec spec in character.specs)
					{
						LoggingPlugin.LogTrace("Considering Entry " + spec.name + " (" + spec.menu + ")");
						if (spec.menu != null && spec.menu.Trim() != "")
						{
							BuildMenu(character.name, spec.menu);
						}
					}
				}
			}

			private static void LoadCharacter(string characterSheet)
			{
				string text = File.ReadAllText(characterSheet, (CacheType)999);
				text = text.TrimStart('\ufeff', '\u200b');
				LoggingPlugin.LogInfo("Loading Character Sheet From " + characterSheet);
				try
				{
					CharacterSpecs characterSpecs = JsonConvert.DeserializeObject<CharacterSpecs>(text);
					string characterName = characterSpecs.name;
					if (!_self.characters.All().Any((CharacterSpecs cs) => cs.name == characterName))
					{
						_self.characters.Add(characterSpecs);
						if (characterSpecs.chainSources == null || !(characterSpecs.chainSources != ""))
						{
							return;
						}
						LoggingPlugin.LogDebug("Chain Loading Set To " + characterSpecs.chainSources);
						LoggingPlugin.LogDebug(JsonConvert.SerializeObject((object)characterSpecs));
						string[] array = characterSpecs.chainSources.Split(new char[1] { ',' });
						string[] array2 = array;
						foreach (string text2 in array2)
						{
							LoggingPlugin.LogDebug("Chain Loading org.lordashes.plugins.d20.character." + text2);
							text = File.ReadAllText("org.lordashes.plugins.d20.common." + text2, (CacheType)999);
							text = text.TrimStart('\ufeff', '\u200b');
							CharacterSpecs characterSpecs2 = JsonConvert.DeserializeObject<CharacterSpecs>(text);
							foreach (Spec spec in characterSpecs2.specs)
							{
								if (!characterSpecs.specs.Where((Spec s) => s.name == spec.name).Any())
								{
									LoggingPlugin.LogDebug("Adding Chain Spec " + spec.name);
									characterSpecs.specs.Add(spec);
								}
								else
								{
									LoggingPlugin.LogDebug("Ignoring Chain Spec " + spec.name + " (Already Exists)");
								}
							}
						}
					}
					else
					{
						LoggingPlugin.LogWarning("Duplicated Character Sheet For '" + characterName + "'");
						SystemMessage.DisplayInfoText("D20 Plugin:\r\nDuplicate Character " + characterName, 2.5f, 0f, (Action)null);
					}
				}
				catch (Exception ex)
				{
					string fileName = Path.GetFileName(characterSheet);
					if (ex.Message.IndexOf("line") > -1)
					{
						string text3 = ex.Message.Substring(ex.Message.IndexOf("line") + 4).Trim();
						text3 = text3.Substring(0, text3.IndexOf(",")).Trim();
						LoggingPlugin.LogError("Error On Line " + text3.Substring(1) + " Of " + fileName + " (" + ex.Message + ")");
						try
						{
							int num2 = int.Parse(text3);
							string[] array3 = text.Split(new string[1] { "\r\n" }, StringSplitOptions.None);
							LoggingPlugin.LogError("Problem Line: " + array3[num2].Trim());
						}
						catch (Exception ex2)
						{
							LoggingPlugin.LogError("'" + text3 + "'");
							LoggingPlugin.LogError(ex2.Message);
						}
					}
					else
					{
						LoggingPlugin.LogError(ex.Message);
					}
					string[] source = text.Split(new string[1] { "\r\n" }, StringSplitOptions.None);
					string text4 = string.Join("\r\n", source.Select((string line, int index) => $"Line {index + 1:0000}: {line}"));
					LoggingPlugin.LogInfo("Fault JSON:\r\n" + text4);
				}
			}

			public CharacterSpecs[] Find(string name)
			{
				if (name == "")
				{
					return null;
				}
				return DynamicQueryableExtensions.Where<CharacterSpecs>(sheets.AsQueryable(), "name==\"" + name + "\"", Array.Empty<object>()).ToArray();
			}

			public CharacterSpecs FindFirst(string name)
			{
				if (name == "")
				{
					return null;
				}
				return DynamicQueryableExtensions.Where<CharacterSpecs>(sheets.AsQueryable(), "name==\"" + name + "\"", Array.Empty<object>()).FirstOrDefault();
			}

			public string FindValue(string name, string whereClause)
			{
				return FindFirst(name)?.FindFirstValue(whereClause);
			}

			public static Sprite LoadSpriteOrDefault(string seekSprite, Sprite fallBackSprite)
			{
				if (File.Find(seekSprite, (CacheType)999).Any())
				{
					return Image.LoadSprite(seekSprite, (CacheType)999);
				}
				return fallBackSprite;
			}

			private void BuildMenu(string characterName, string menu)
			{
				menu = "/" + characterName + menu;
				string text = menu.Substring(menu.LastIndexOf("/") + 1);
				string text2 = menu.Substring(0, menu.LastIndexOf("/"));
				string[] array = text2.Substring(1).Split(new char[1] { '/' });
				string text3 = "";
				for (int i = 0; i < array.Length; i++)
				{
					if (!builtPaths.Contains(text3 + ":" + array[i]))
					{
						LoggingPlugin.LogDebug("Building Path " + text3 + "/" + array[i]);
						DeepMenusPlugin._self.CreateSubMenu(text3, DeepMenusPlugin._self.MakeSubMenuEntry(array[i], (text3 != "") ? LoadSpriteOrDefault("org.lordashes.plugins.d20." + array[i] + ".png", fallbackSprite) : null, false, true), (Func<bool>)(() => true));
						builtPaths.Add(text3 + ":" + array[i]);
					}
					text3 = text3 + "/" + array[i];
				}
				LoggingPlugin.LogDebug("Building Leaf " + text3 + "/" + text);
				DeepMenusPlugin._self.CreateSubMenuItem(text3, DeepMenusPlugin._self.MakeItemEntry(text, (Action<string, string>)delegate(string item, string m)
				{
					((MonoBehaviour)_self).StartCoroutine(InitiateMenuAction(item, m));
				}, LoadSpriteOrDefault("org.lordashes.plugins.d20." + text + ".png", fallbackSprite), false, true), (Func<bool>)(() => true));
			}
		}

		public static CreatureBoardAsset[] GetCreatureAssets(CreatureGuid[] cids)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			List<CreatureBoardAsset> list = new List<CreatureBoardAsset>();
			if (cids != null)
			{
				foreach (CreatureGuid val in cids)
				{
					CreatureBoardAsset val2 = null;
					CreaturePresenter.TryGetAsset(val, ref val2);
					if ((Object)(object)val2 != (Object)null)
					{
						list.Add(val2);
					}
				}
			}
			return list.ToArray();
		}

		public static string[] GetCreatureNames(CreatureGuid[] cids)
		{
			return (from a in GetCreatureAssets(cids)
				select a.Name).ToArray();
		}

		private static CreatureBoardAsset[] GetAffectedCreatures()
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			List<CreatureBoardAsset> list = new List<CreatureBoardAsset>();
			FieldInfo fieldInfo = (from i in typeof(CreatureBoardAsset).GetRuntimeFields()
				where i.Name == "_selected"
				select i).FirstOrDefault();
			if (fieldInfo != null)
			{
				foreach (CreatureBoardAsset item2 in (IEnumerable<CreatureBoardAsset>)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets()/*cast due to .constrained prefix*/)
				{
					if ((Object)(object)item2 != (Object)null && (bool)fieldInfo.GetValue(item2))
					{
						list.Add(item2);
					}
				}
			}
			if (!list.Any((CreatureBoardAsset c) => c.CreatureId == new CreatureGuid(RadialUIPlugin.GetLastRadialTargetCreature())))
			{
				CreatureBoardAsset val = null;
				CreaturePresenter.TryGetAsset(new CreatureGuid(RadialUIPlugin.GetLastRadialTargetCreature()), ref val);
				if ((Object)(object)val != (Object)null)
				{
					list.Add(val);
				}
			}
			CreatureBoardAsset item = default(CreatureBoardAsset);
			CreaturePresenter.TryGetAsset(LocalClient.SelectedCreatureId, ref item);
			if (list.Contains(item))
			{
				list.Remove(item);
			}
			return list.ToArray();
		}

		public static IEnumerator InitiateMenuAction(string item, string menu, CreatureBoardAsset[] instigators = null, CreatureBoardAsset[] targets = null)
		{
			LoggingPlugin.LogDebug("---[ACTION SELECTED: " + item + " (" + menu + ")]---");
			((MonoBehaviour)_self).StartCoroutine(PatchCallCameraClick.preventClickCollection(1f));
			yield return (object)new WaitForSeconds(0.1f);
			CreatureGuid[] selectedAssetsIds = null;
			LocalClient.TryGetLassoedCreatureIds(ref selectedAssetsIds);
			if (selectedAssetsIds == null)
			{
				instigators = GetCreatureAssets(selectedAssetsIds);
			}
			if (selectedAssetsIds == null)
			{
				instigators = GetCreatureAssets((CreatureGuid[])(object)new CreatureGuid[1] { LocalClient.SelectedCreatureId });
			}
			if (targets == null)
			{
				targets = GetAffectedCreatures();
			}
			LoggingPlugin.LogDebug("Instagators (" + instigators.Length + ") = " + string.Join(",", instigators.Select((CreatureBoardAsset a) => a.Name)));
			LoggingPlugin.LogDebug("Targets (" + targets.Length + ") = " + string.Join(",", targets.Select((CreatureBoardAsset a) => a.Name)));
			menu = menu.Substring(1);
			menu = menu.Substring(menu.IndexOf("/"));
			CreatureBoardAsset[] array = instigators;
			foreach (CreatureBoardAsset instigator in array)
			{
				LoggingPlugin.LogDebug("Current Pass Instinagtor: " + instigator.Name);
				LoggingPlugin.LogDebug("Current Targets (" + targets.Length + ") = " + string.Join(",", targets.Select((CreatureBoardAsset a) => a.Name)));
				if (!((Object)(object)instigator != (Object)null))
				{
					continue;
				}
				CharacterSpecs stack = new CharacterSpecs();
				CharacterSpecs sheet = _self.characters.FindFirst(DiceRoller.StripTrailingInteger(instigator.Name));
				string action = sheet.FindFirstExtraValue("menu==\"" + menu + "/" + item + "\"", "type");
				LoggingPlugin.LogDebug("Action: " + ((action != null) ? action : "Null"));
				if (action == null || action.Trim() == "")
				{
					action = "skill";
				}
				Spec spec = sheet.specs.Where((Spec s) => s.menu == menu + "/" + item).FirstOrDefault();
				if (spec == null)
				{
					continue;
				}
				LoggingPlugin.LogTrace("Getting Publicity");
				string publicityStr = spec.Extra("message");
				string text = publicityStr;
				string text2 = text;
				Scripts.MessagePublicity publicity = ((text2 == "private") ? Scripts.MessagePublicity.privateMessage : ((text2 == "semiprivate") ? Scripts.MessagePublicity.semiPrivateMessage : Scripts.MessagePublicity.publicMessage));
				switch (action)
				{
				case "info":
				case "skill":
				case "attack":
				case "save":
				case "spell":
				{
					LoggingPlugin.LogDebug("Found Spec: " + (spec != null));
					string opposed = spec.Extra("opposed");
					LoggingPlugin.LogDebug("Found Opposed: " + (opposed != null));
					LoggingPlugin.LogDebug("Expected Targets: " + ((spec.Extra("targets") != null) ? int.Parse(spec.Extra("targets")) : 0));
					if (opposed != null && opposed != "" && new CreatureGuid(RadialUIPlugin.GetLastRadialTargetCreature()) != LocalClient.SelectedCreatureId)
					{
						LoggingPlugin.LogDebug("Processing " + instigator.Name + "'s " + item + " (" + action + ") As Opposed Skill With Selected Target.");
						CreatureBoardAsset targetAsset = null;
						CreaturePresenter.TryGetAsset(new CreatureGuid(RadialUIPlugin.GetLastRadialTargetCreature()), ref targetAsset);
						yield return Scripts.ProcessSequence(stack, (action == "attack" || action == "spell") ? CharactersSpecs.CheckType.Attack : CharactersSpecs.CheckType.Opposed, spec, instigator, (CreatureBoardAsset[])(object)new CreatureBoardAsset[1] { targetAsset }, publicity);
					}
					else if (opposed != null && opposed != "")
					{
						LoggingPlugin.LogDebug("Processing " + instigator.Name + "'s " + item + " (" + action + ") As Opposed Skill. Collecting Targets.");
						TargetsCollection obj = new TargetsCollection
						{
							targetsCollectingSpecType = action,
							targetsCollectingSpec = spec,
							targetsCollectingInstigator = instigator,
							targetsCollectingPublicity = publicity
						};
						string t = spec.Extra("targets");
						obj.targetsCollecting = int.Parse((t != null) ? t : int.MaxValue.ToString());
						targetsCollection = obj;
					}
					else
					{
						LoggingPlugin.LogDebug("Processing " + instigator.Name + "'s " + item + " (" + action + ") As Skill");
						yield return Scripts.ProcessSequence(stack, CharactersSpecs.CheckType.Regular, spec, instigator, null, publicity);
					}
					break;
				}
				case "effect":
					spec = sheet.specs.Where((Spec s) => s.menu == menu + "/" + item).FirstOrDefault();
					LoggingPlugin.LogDebug("Found Spec: " + (spec != null));
					LoggingPlugin.LogDebug("Processing " + instigator.Name + "'s " + item + " (" + action + ") As Damage");
					yield return Scripts.ProcessEffectOnTarget(stack, CharactersSpecs.CheckType.Effect, spec, instigator, (targets.Length != 0) ? targets[0] : instigator, "Hit", publicity, spec.name);
					break;
				case "damage":
					spec = sheet.specs.Where((Spec s) => s.menu == menu + "/" + item).FirstOrDefault();
					LoggingPlugin.LogDebug("Found Spec: " + (spec != null));
					LoggingPlugin.LogDebug("Processing " + instigator.Name + "'s " + item + " (" + action + ") As Damage");
					yield return Scripts.ProcessDamageOnTarget(stack, CharactersSpecs.CheckType.Damage, spec, instigator, (targets.Length != 0) ? targets[0] : instigator, "Hit", publicity, spec.name);
					break;
				case "heal":
					spec = sheet.specs.Where((Spec s) => s.menu == menu + "/" + item).FirstOrDefault();
					LoggingPlugin.LogDebug("Found Spec: " + (spec != null));
					LoggingPlugin.LogDebug("Processing " + instigator.Name + "'s " + item + " (" + action + ") As Heal");
					yield return Scripts.ProcessHealOnTarget(stack, CharactersSpecs.CheckType.Heal, spec, instigator, (targets.Length != 0) ? targets[0] : instigator, publicity);
					break;
				default:
					spec = sheet.specs.Where((Spec s) => s.menu == menu + "/" + item).FirstOrDefault();
					LoggingPlugin.LogDebug("Found Spec: " + (spec != null));
					LoggingPlugin.LogDebug("Processing " + instigator.Name + "'s " + item + " (" + action + ") As Generic");
					yield return Scripts.ProcessGeneric(stack, CharactersSpecs.CheckType.Generic, spec, instigator, (targets.Length != 0) ? targets[0] : instigator, publicity);
					break;
				}
			}
			LoggingPlugin.LogDebug("Action Processing Completed");
		}
	}

	public static class DiceRoller
	{
		public class RollResult
		{
			public string name { get; set; }

			public string formula { get; set; }

			public string formulaResolved { get; set; }

			public string formulaDice { get; set; }

			public int total { get; set; }

			public int[] dice { get; set; }
		}

		public enum RollingMethod
		{
			randomGeneratorDice = 1,
			talespireDice
		}

		public static class RollSimplifier
		{
			public class RollParseResult
			{
				public string RollString { get; set; }

				public List<short> AllDiceValues { get; set; }

				public List<int> Totals { get; set; }
			}

			public static RollParseResult ParseRollResults(RollResults rollResults)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				List<short> allDiceValues = new List<short>();
				List<string> list = new List<string>();
				List<int> list2 = new List<int>();
				RollGroup[] array = rollResults.ResultsGroups.ToArray();
				foreach (RollGroup val in array)
				{
					var (item, item2) = ProcessOperand(val.Result, allDiceValues);
					list.Add(item);
					list2.Add(item2);
				}
				return new RollParseResult
				{
					RollString = string.Join(" / ", list),
					AllDiceValues = allDiceValues,
					Totals = list2
				};
			}

			private static (string str, int total) ProcessOperand(RollOperand operand, List<short> allDiceValues)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: 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_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Invalid comparison between Unknown and I8
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
				//IL_0101: Unknown result type (might be due to invalid IL or missing references)
				//IL_015e: Unknown result type (might be due to invalid IL or missing references)
				//IL_016d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_0082: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				RollOperation val2 = default(RollOperation);
				RollResult val3 = default(RollResult);
				RollValue val4 = default(RollValue);
				Which val = ((RollOperand)(ref operand)).Get(ref val2, ref val3, ref val4);
				Which val5 = val;
				Which val6 = val5;
				if ((long)val6 <= 2L)
				{
					switch ((uint)val6)
					{
					case 0u:
					{
						RollOperand[] array2 = val2.Operands.ToArray();
						if (array2.Length != 2)
						{
							throw new InvalidOperationException("Unexpected number of operands in RollOperation (expected 2).");
						}
						(string, int) tuple = ProcessOperand(array2[0], allDiceValues);
						(string, int) tuple2 = ProcessOperand(array2[1], allDiceValues);
						int item2 = (((int)val2.Operator == 0) ? (tuple.Item2 + tuple2.Item2) : (tuple.Item2 - tuple2.Item2));
						string text = (((int)val2.Operator == 0) ? "+" : "-");
						return (str: tuple.Item1 + text + tuple2.Item1, total: item2);
					}
					case 1u:
					{
						int num = ((IEnumerable<short>)val3.Results).Count();
						string registeredName = ((DieKind)(ref val3.Kind)).RegisteredName;
						short[] array = val3.Results.ToArray();
						allDiceValues.AddRange(array);
						int item = array.Sum((short r) => r);
						return (str: $"{num}{registeredName}", total: item);
					}
					case 2u:
					{
						short value = val4.Value;
						return (str: value.ToString(), total: val4.Value);
					}
					}
				}
				throw new InvalidOperationException("Unknown RollOperand type encountered.");
			}
		}

		private static readonly Random _rng = new Random();

		private static readonly Regex TokenRegex = new Regex("(\\d+[dD]\\d+[aAdD]?|\\d+|[+\\-*/])", RegexOptions.Compiled);

		private static readonly Regex DiceRegex = new Regex("(\\d+)[dD](\\d+)([aAdD]?)", RegexOptions.Compiled);

		private static readonly string TermPattern = "(?:\\d+[dD]\\d+[aAdD]?|\\d+|[A-Za-z_][A-Za-z0-9_]*)";

		public static TaskCompletionSource<RollResult> pendingRoll;

		public static async Task<RollResult> Roll(Characters.CharacterSpecs instigatorSheet, string rollName, string expression, RollingMethod? rollingStyle = null)
		{
			RollingMethod useRollingStyle = (rollingStyle.HasValue ? rollingStyle.Value : rollingStyleOffensive);
			RollResult rollResult = new RollResult
			{
				name = rollName,
				formula = expression,
				formulaResolved = SimplifyExpression(ComputeConstants(instigatorSheet.Resolve(expression)))
			};
			RollResult rawRollResult;
			switch (useRollingStyle)
			{
			case RollingMethod.randomGeneratorDice:
				rawRollResult = RollRandomGeneratorDice(instigatorSheet, rollResult.formulaResolved);
				break;
			case RollingMethod.talespireDice:
			{
				string justDice = ExtractTalespireDiceRolls(rollResult.formulaResolved);
				rawRollResult = ((!(justDice.Trim() != "")) ? new RollResult
				{
					dice = new int[0]
				} : (await RollTalespireDice(instigatorSheet, rollName, justDice.Trim())));
				break;
			}
			default:
				return null;
			}
			rollResult.formulaDice = ResolveDiceValues(rollResult.formulaResolved, rawRollResult.dice);
			rollResult.total = ResolveTotal(rollResult.formulaResolved, rawRollResult.dice);
			rollResult.dice = rawRollResult.dice;
			LoggingPlugin.LogDebug("Dice Roller: Name: " + rollResult.name);
			LoggingPlugin.LogDebug("Dice Roller: Formula: " + rollResult.formula);
			LoggingPlugin.LogDebug("Dice Roller: Roll: " + rollResult.formulaResolved);
			LoggingPlugin.LogDebug("Dice Roller: Dice: " + rollResult.formulaDice);
			LoggingPlugin.LogDebug("Dice Roller: Total: " + rollResult.total);
			return rollResult;
		}

		public static Task<RollResult> RollTalespireDice(Characters.CharacterSpecs instigatorSheet, string rollName, string expression)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			LoggingPlugin.LogDebug("Using Talespire Dice");
			if (pendingRoll != null)
			{
				throw new InvalidOperationException("A virtual dice roll is already in progress.");
			}
			LoggingPlugin.LogDebug("Setting Dice Expecting Flag");
			pendingRoll = new TaskCompletionSource<RollResult>();
			string text = "talespire://dice/" + rollName + ":" + expression;
			LoggingPlugin.LogDebug("Requesting: " + text);
			LocalConnectionManager.ProcessTaleSpireUrl(text);
			return pendingRoll.Task;
		}

		public static RollResult RollRandomGeneratorDice(Characters.CharacterSpecs instigatorSheet, string expression)
		{
			LoggingPlugin.LogDebug("Using Random Generator Dice");
			if (string.IsNullOrWhiteSpace(expression))
			{
				throw new ArgumentException("Expression cannot be empty.");
			}
			List<int> diceRolls = new List<int>();
			string expression2 = DiceRegex.Replace(expression, delegate(Match match)
			{
				int count = int.Parse(match.Groups[1].Value);
				int sides = int.Parse(match.Groups[2].Value);
				char c = ((match.Groups[3].Value.Length > 0) ? char.ToUpperInvariant(match.Groups[3].Value[0]) : '\0');
				if (c == '\0')
				{
					return RollOnce().ToString();
				}
				int val = RollOnce();
				int val2 = RollOnce();
				return ((c == 'A') ? Math.Max(val, val2) : Math.Min(val, val2)).ToString();
			});
			int total = EvaluateIntegerExpression(expression2);
			return new RollResult
			{
				formula = expression,
				formulaResolved = SimplifyExpression(ComputeConstants(instigatorSheet.Resolve(expression))),
				formulaDice = SimplifyExpression(ResolveDiceValues(ComputeConstants(instigatorSheet.Resolve(expression)), diceRolls.ToArray())),
				total = total,
				dice = diceRolls.ToArray()
			};
			int RollOnce()
			{
				int num = 0;
				for (int i = 0; i < P_0.count; i++)
				{
					int num2 = _rng.Next(1, P_0.sides + 1);
					diceRolls.Add(num2);
					num += num2;
				}
				return num;
			}
		}

		public static string ResolveDiceValues(string formula, int[] dice)
		{
			if (string.IsNullOrWhiteSpace(formula))
			{
				throw new ArgumentException("Expression cannot be empty.");
			}
			if (dice == null)
			{
				throw new ArgumentNullException("dice");
			}
			int num = 0;
			StringBuilder stringBuilder = new StringBuilder();
			int num2 = 0;
			foreach (Match item in DiceRegex.Matches(formula))
			{
				stringBuilder.Append(formula.Substring(num2, item.Index - num2));
				int num3 = int.Parse(item.Groups[1].Value);
				char c = ((item.Groups[3].Value.Length > 0) ? char.ToUpperInvariant(item.Groups[3].Value[0]) : '\0');
				int num4 = ((c != 'A' && c != 'D') ? 1 : 2);
				int num5 = num3 * num4;
				if (num + num5 > dice.Length)
				{
					throw new ArgumentException("Not enough dice values provided.");
				}
				if (num4 > 1)
				{
					stringBuilder.Append("(");
					for (int i = 0; i < num5; i++)
					{
						if (i > 0)
						{
							stringBuilder.Append(",");
						}
						stringBuilder.Append(dice[num + i]);
					}
					stringBuilder.Append(")");
					stringBuilder.Append(c);
				}
				else if (num3 == 1)
				{
					stringBuilder.Append(dice[num]);
				}
				else
				{
					stringBuilder.Append("(");
					for (int j = 0; j < num3; j++)
					{
						if (j > 0)
						{
							stringBuilder.Append(",");
						}
						stringBuilder.Append(dice[num + j]);
					}
					stringBuilder.Append(")");
				}
				num += num5;
				num2 = item.Index + item.Length;
			}
			stringBuilder.Append(formula.Substring(num2));
			return stringBuilder.ToString();
		}

		public static int ResolveTotal(string formula, int[] dice)
		{
			int num = 0;
			StringBuilder stringBuilder = new StringBuilder();
			foreach (Match item in TokenRegex.Matches(formula))
			{
				string value = item.Value;
				Match match2 = DiceRegex.Match(value);
				if (match2.Success)
				{
					int num2 = int.Parse(match2.Groups[1].Value);
					char c = ((match2.Groups[3].Length > 0) ? char.ToUpperInvariant(match2.Groups[3].Value[0]) : '\0');
					if (c == '\0')
					{
						if (num + num2 > dice.Length)
						{
							throw new ArgumentException("Not enough dice values supplied.");
						}
						int num3 = 0;
						for (int i = 0; i < num2; i++)
						{
							num3 += dice[num++];
						}
						stringBuilder.Append(num3);
						continue;
					}
					int num4 = num2 * 2;
					if (num + num4 > dice.Length)
					{
						throw new ArgumentException("Not enough dice values supplied.");
					}
					int num5 = 0;
					for (int j = 0; j < num2; j++)
					{
						num5 += dice[num++];
					}
					int num6 = 0;
					for (int k = 0; k < num2; k++)
					{
						num6 += dice[num++];
					}
					int value2 = ((c == 'A') ? Math.Max(num5, num6) : Math.Min(num5, num6));
					stringBuilder.Append(value2);
				}
				else
				{
					stringBuilder.Append(value);
				}
			}
			object value3 = new DataTable().Compute(stringBuilder.ToString(), null);
			return Convert.ToInt32(value3);
		}

		public static int ResolveMaxTotal(string expression)
		{
			if (string.IsNullOrWhiteSpace(expression))
			{
				throw new ArgumentException("Expression cannot be empty.");
			}
			List<int> list = new List<int>();
			foreach (Match item2 in DiceRegex.Matches(expression))
			{
				int num = int.Parse(item2.Groups[1].Value);
				int num2 = int.Parse(item2.Groups[2].Value);
				string value = item2.Groups[3].Value;
				int item = num * num2;
				list.Add(item);
				if (!string.IsNullOrEmpty(value))
				{
					list.Add(item);
				}
			}
			return ResolveTotal(expression, list.ToArray());
		}

		public static string ExtractTalespireDiceRolls(string expression)
		{
			Regex regex = new Regex("(?<op>[+\\-*/]?)\\s*(?<dice>\\d+[dD]\\d+)(?<rep>[aAdD]?)|\\d+", RegexOptions.Compiled);
			StringBuilder stringBuilder = new StringBuilder();
			bool flag = true;
			foreach (Match item in regex.Matches(expression))
			{
				if (!item.Groups["dice"].Success)
				{
					continue;
				}
				string value = item.Groups["op"].Value;
				string value2 = item.Groups["dice"].Value;
				string value3 = item.Groups["rep"].Value;
				int num = ((value3.Length <= 0) ? 1 : 2);
				for (int i = 0; i < num; i++)
				{
					if (!flag)
					{
						stringBuilder.Append((value.Length > 0) ? value : "+");
					}
					stringBuilder.Append(value2);
					flag = false;
				}
			}
			return stringBuilder.ToString().Replace("-", "+").Replace("/", "+")
				.Replace("*", "+");
		}

		public static string SimplifyExpression(string formula)
		{
			if (string.IsNullOrWhiteSpace(formula))
			{
				return formula;
			}
			formula = Regex.Replace(formula, "(?<!\\w)(" + TermPattern + ")\\s*\\*\\s*0|0\\s*\\*\\s*(" + TermPattern + ")", "+0");
			formula = Regex.Replace(formula, "(?<!\\w)1\\s*\\*\\s*(" + TermPattern + ")", "$1");
			formula = Regex.Replace(formula, "(" + TermPattern + ")\\s*\\*\\s*1(?!\\w)", "$1");
			formula = Regex.Replace(formula, "\\+\\+", "+");
			formula = Regex.Replace(formula, "\\+-", "-");
			formula = Regex.Replace(formula, "-\\+", "-");
			formula = Regex.Replace(formula, "--", "+");
			formula = Regex.Replace(formula, "^\\+", "");
			return formula;
		}

		public static string StripTrailingInteger(string input)
		{
			if (string.IsNullOrEmpty(input))
			{
				return input;
			}
			return Regex.Replace(input, "(\\(\\d+\\)|\\d+)$", "");
		}

		public static string ComputeConstants(string expression)
		{
			while (expression.Contains("("))
			{
				int startIndex = expression.IndexOf("(");
				string text = expression.Substring(startIndex);
				text = expression.Substring(0, expression.IndexOf(")") + 1);
				string text2 = Compute(text).ToString();
				expression = expression.Replace(text, text2);
				LoggingPlugin.LogDebug("Compute Constants: Replacing '" + text + "' With '" + text2 + "'. Expression is now: " + expression);
			}
			return expression;
		}

		private static string Compute(string expression)
		{
			DataTable dataTable = new DataTable();
			return dataTable.Compute(expression, null).ToString();
		}

		private static int EvaluateIntegerExpression(string expression)
		{
			object value = new DataTable().Compute(expression, null);
			return Convert.ToInt32(value);
		}
	}

	public class TargetsCollection
	{
		public string targetsCollectingSpecType = null;

		public Characters.Spec targetsCollectingSpec = null;

		public CreatureBoardAsset targetsCollectingInstigator;

		public Scripts.MessagePublicity targetsCollectingPublicity = Scripts.MessagePublicity.publicMessage;

		public int targetsCollecting = 0;

		public List<CreatureBoardAsset> targetsCollected = new List<CreatureBoardAsset>();
	}

	[HarmonyPatch(typeof(UI_DiceRollGroup), "DisplayGroup")]
	public static class PatchSetResult
	{
		public static bool Prefix(UI_DiceRollGroup __instance, RollGroup resultsGroup, bool isFirst, TMP_Text ____headerText, FactoryInspectorSetup<UI_DiceOperator> ____operatorFactory, RectTransform ____content, int ____contentGridWrapWidth, GridLayoutGroup ____contentGrid, RectTransform ____transform)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			if (DiceRoller.pendingRoll != null)
			{
				string text = (isFirst ? "Rolled" : "And");
				string name = resultsGroup.Name;
				if (!string.IsNullOrWhiteSpace(name))
				{
					text = text + " " + name;
				}
				____headerText.text = text;
				int num = (int)(from m in typeof(UI_DiceRollGroup).GetRuntimeMethods()
					where m.Name == "DisplayOperand"
					select m).FirstOrDefault().Invoke(__instance, new object[2] { resultsGroup.Result, true });
				UI_DiceOperator val = ____operatorFactory.Hire(true);
				((Component)val).transform.SetAsLastSibling();
				if (((Transform)____content).childCount <= ____contentGridWrapWidth)
				{
					____contentGrid.constraint = (Constraint)2;
					____contentGrid.constraintCount = 1;
					RectTransformExtensions.SetHeight(____transform, 25f + ____contentGrid.cellSize.y);
					return false;
				}
				____contentGrid.constraint = (Constraint)1;
				____contentGrid.constraintCount = ____contentGridWrapWidth;
				float num2 = math.ceil((float)((Transform)____content).childCount / (float)____contentGrid.constraintCount) * (____contentGrid.cellSize.y + ____contentGrid.spacing.y);
				RectTransformExtensions.SetHeight(____transform, 25f + num2);
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(GUIManager), "PlayMode_OnStateChange")]
	public static class GUIManagerPlayModeOnStateChange
	{
		public static bool Prefix(State obj)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if (((object)obj).ToString() == "PlayMode+TurnBased")
			{
				LoggingPlugin.LogDebug("Initiative Mode Selected");
				AssetDataPlugin.SendInfo("org.lordashes.plugins.d20", "action:initiative");
				ChatManager.SendChatMessageToBoard("[Roll Initiative!]\r\nCollecting Initiatives", LocalPlayer.Id.Value, (float3?)null, false);
				initiativeOrder.Clear();
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(UI_InitativeManager), "OpenEdit")]
	public class InitiativeManagerApplyEditPatch
	{
		private static void Postfix(bool value)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			LoggingPlugin.LogDebug("Applying Stored Initiatives");
			InitiativeManager.SetEditQueue(initiativeOrder.Values.ToArray());
			LoggingPlugin.LogDebug("Ending Initiative Collection");
			if (collectingInitiative && summarizeInitiative)
			{
				string text = "";
				foreach (KeyValuePair<int, QueueElement> item in initiativeOrder)
				{
					CreatureBoardAsset val = null;
					CreaturePresenter.TryGetAsset(item.Value.CreatureGuid, ref val);
					if ((Object)(object)val != (Object)null)
					{
						text = text + item.Key + ": " + val.Name + "\r\n";
					}
				}
				if (text != "")
				{
					text = text.Substring(0, text.Length - 2);
					ChatManager.SendChatMessageToBoard("[Initiative]\r\n" + text, LocalPlayer.Id.Value, (float3?)null, false);
				}
			}
			collectingInitiative = false;
		}
	}

	[HarmonyPatch(typeof(UIChatMessageManager), "AddChatMessage")]
	public static class PatchAddMessage
	{
		public static bool Prefix(string creatureName, Texture2D icon, string chatMessage, IChatFocusable focus = null)
		{
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			LoggingPlugin.LogDebug("Initiative Collection: " + collectingInitiative);
			if (collectingInitiative)
			{
				LoggingPlugin.LogDebug("Initiative Collection: Active");
				LoggingPlugin.LogDebug("Initiative Collection: Caption: " + ((creatureName != null) ? creatureName : "None"));
				LoggingPlugin.LogDebug("Initiative Collection: Icon: " + (((Object)(object)icon != (Object)null && ((Object)icon).name != null) ? ((Object)icon).name : "None"));
				LoggingPlugin.LogDebug("Initiative Collection: Message: " + ((chatMessage != null) ? chatMessage.Replace("\r\n", "|") : "None"));
				CreatureBoardAsset val = null;
				CreaturePresenter.TryGetAsset(LocalClient.SelectedCreatureId, ref val);
				if (LocalClient.IsPartyGm)
				{
					LoggingPlugin.LogDebug("Initiative Collection: GM Client");
					try
					{
						string text = chatMessage.Substring(chatMessage.LastIndexOf(" ") + 1);
						LoggingPlugin.LogDebug("Initiative Collection: Adding Roll: " + text + " For " + creatureName);
						initiativeOrder.Add(int.Parse(text), new QueueElement((ElementType)0, LocalClient.SelectedCreatureId));
					}
					catch
					{
						SystemMessage.DisplayInfoText("D20 Plugin:\r\nRoll may be set to value instead of skill.", 2.5f, 0f, (Action)null);
					}
				}
				else
				{
					LoggingPlugin.LogDebug("Initiative Collection: Non-GM Client");
				}
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(UIChatMessageManager), "AddDiceResultMessage")]
	public static class PatchAddDiceResultMessage
	{
		public static bool Prefix(RollResults diceResult, ResultsOrigin origin, ClientGuid sender, bool hidden, IChatFocusable focus = null)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			if (DiceRoller.pendingRoll != null)
			{
				DiceRoller.RollSimplifier.RollParseResult rollParseResult = DiceRoller.RollSimplifier.ParseRollResults(diceResult);
				int num = rollParseResult.Totals.Sum();
				DiceRoller.RollResult result = new DiceRoller.RollResult
				{
					total = rollParseResult.Totals.Sum(),
					dice = ((IEnumerable<short>)rollParseResult.AllDiceValues).Select((Func<short, int>)((short s) => s)).ToArray()
				};
				DiceRoller.pendingRoll?.TrySetResult(result);
				DiceRoller.pendingRoll = null;
				DiceRollManager val = Object.FindObjectOfType<DiceRollManager>();
				if ((Object)(object)val != (Object)null)
				{
					val.RemoveRoll(diceResult.RollId);
				}
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(BoardTool), "CallCameraClick")]
	public static class PatchCallCameraClick
	{
		public static bool preventClickCalls;

		public unsafe static bool Prefix(CameraClickEvent click)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			if (!preventClickCalls && targetsCollection.targetsCollecting > 0 && !((object)BoardToolManager.CurrentTool).ToString().Contains("RulerBoardTool"))
			{
				string[] obj = new string[6] { "Generic Click: User Click At ", null, null, null, null, null };
				Vector2 position = click.position;
				obj[1] = ((object)(*(Vector2*)(&position))/*cast due to .constrained prefix*/).ToString();
				obj[2] = " With Tool ";
				obj[3] = ((object)BoardToolManager.CurrentTool).ToString();
				obj[4] = " And Collecting ";
				obj[5] = collecting;
				LoggingPlugin.LogDebug(string.Concat(obj));
				preventClickCalls = true;
				((MonoBehaviour)_self).StartCoroutine(preventClickCollection(1f));
				CreatureBoardAsset val = null;
				float3 val2 = default(float3);
				PixelPickingManager.TryGetPickedCreature(ref val2, ref val);
				if ((Object)(object)val != (Object)null)
				{
					LoggingPlugin.LogDebug("Generic Click: Added Asset " + val.Name + " At " + ((object)(*(float3*)(&val2))/*cast due to .constrained prefix*/).ToString());
					targetsCollection.targetsCollected.Add(val);
					if (targetsCollection.targetsCollected.Count >= targetsCollection.targetsCollecting)
					{
						ProcessSelection();
					}
				}
				if (Input.GetMouseButtonDown(2))
				{
					ProcessSelection();
				}
			}
			return true;
		}

		public static void ProcessSelection()
		{
			Characters.CharacterSpecs stack = new Characters.CharacterSpecs();
			((MonoBehaviour)_self).StartCoroutine(preventClickCollection(2f));
			((MonoBehaviour)_self).StartCoroutine(Scripts.ProcessSequence(stack, (targetsCollection.targetsCollectingSpecType == "attack" || targetsCollection.targetsCollectingSpecType == "spell") ? Characters.CharactersSpecs.CheckType.Attack : Characters.CharactersSpecs.CheckType.Opposed, targetsCollection.targetsCollectingSpec, targetsCollection.targetsCollectingInstigator, targetsCollection.targetsCollected.ToArray(), targetsCollection.targetsCollectingPublicity));
			((MonoBehaviour)_self).StartCoroutine(holdAndClear(2f));
		}

		public static IEnumerator holdAndClear(float delay)
		{
			yield return (object)new WaitForSeconds(delay);
			targetsCollection.targetsCollecting = 0;
			targetsCollection.targetsCollected.Clear();
		}

		public static IEnumerator preventClickCollection(float delay)
		{
			preventClickCalls = true;
			yield return (object)new WaitForSeconds(delay);
			preventClickCalls = false;
		}
	}

	[HarmonyPatch(typeof(Ruler), "SetNewMode")]
	public static class PatchSetNewMode
	{
		public static bool Prefix(int newModeIndex, bool forceRecreate)
		{
			if (targetsCollection.targetsCollecting > 0)
			{
				LoggingPlugin.LogDebug("D20 Plugin: Ruler Mode Change To Type " + rulerTypes[newModeIndex] + " (" + newModeIndex + ")");
				collecting = rulerTypes[newModeIndex];
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(Ruler), "OnClick")]
	public static class PatchOnClick
	{
		public static bool Prefix(Ruler __instance, int buttonId)
		{
			return true;
		}

		public unsafe static void Postfix(Ruler __instance, int buttonId)
		{
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0315: Unknown result type (might be due to invalid IL or missing references)
			//IL_031a: Unknown result type (might be due to invalid IL or missing references)
			//IL_031f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0342: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			//IL_0553: Unknown result type (might be due to invalid IL or missing references)
			//IL_0558: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0395: Unknown result type (might be due to invalid IL or missing references)
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			//IL_039f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_040b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0410: Unknown result type (might be due to invalid IL or missing references)
			//IL_057a: Unknown result type (might be due to invalid IL or missing references)
			//IL_057f: Unknown result type (might be due to invalid IL or missing references)
			//IL_048c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0491: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0615: Unknown result type (might be due to invalid IL or missing references)
			//IL_061c: Unknown result type (might be due to invalid IL or missing references)
			//IL_062d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0673: Unknown result type (might be due to invalid IL or missing references)
			//IL_0678: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + " Click: Button " + buttonId + ", Targets: " + targetsCollection.targetsCollecting + ", Collecting: " + PluginD20.collecting);
			if (PatchCallCameraClick.preventClickCalls || targetsCollection.targetsCollecting <= 0)
			{
				return;
			}
			List<Vector3> list = new List<Vector3>();
			if (!(PluginD20.collecting != ""))
			{
				return;
			}
			List<Vector3> list2 = new List<Vector3>();
			GameObject val = GameObject.Find(((Object)__instance).name);
			Vector3 val2;
			if ((Object)(object)val != (Object)null)
			{
				foreach (Transform item in ExtensionMethods.Children(val.transform))
				{
					LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Found Child: " + ((Object)item).name + " While Searching For " + PluginD20.collecting + "Indicator(Clone)");
					if (!(((Object)item).name == PluginD20.collecting + "Indicator(Clone)"))
					{
						continue;
					}
					LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Found " + ((Object)item).name + " With " + ExtensionMethods.Children(((Component)item).transform).Count() + " Children");
					foreach (Transform item2 in ExtensionMethods.Children(((Component)item).transform))
					{
						string collecting = PluginD20.collecting;
						val2 = item2.position;
						LoggingPlugin.LogDebug(collecting + " Point: " + ((object)(*(Vector3*)(&val2))/*cast due to .constrained prefix*/).ToString());
						if (item2.position != Vector3.zero)
						{
							list.Add(item2.position);
						}
					}
				}
			}
			LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Collecting: " + PluginD20.collecting + ", Points: " + list.Count);
			string collecting2 = PluginD20.collecting;
			string text = collecting2;
			if (!(text == "Sphere"))
			{
				if (!(text == "Box") || list.Count != 2)
				{
					return;
				}
				LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Applying Selection Based On " + PluginD20.collecting);
				foreach (CreatureBoardAsset item3 in (IEnumerable<CreatureBoardAsset>)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets()/*cast due to .constrained prefix*/)
				{
					if (item3.CreatureId != LocalClient.SelectedCreatureId)
					{
						string[] obj = new string[8]
						{
							"Ruler ",
							((Object)__instance).name,
							": Asset ",
							item3.Name,
							" (",
							((object)item3.CreatureId/*cast due to .constrained prefix*/).ToString(),
							") At ",
							null
						};
						val2 = ((Component)((MovableBoardAsset)item3).Rotator).transform.position;
						obj[7] = ((object)(*(Vector3*)(&val2))/*cast due to .constrained prefix*/).ToString();
						LoggingPlugin.LogDebug(string.Concat(obj));
						if (IsPointInsideBox(list[0], list[1], ((Component)((MovableBoardAsset)item3).Rotator).transform.position))
						{
							LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Asset " + item3.Name + " (" + ((object)item3.CreatureId/*cast due to .constrained prefix*/).ToString() + ") Is Selected");
							targetsCollection.targetsCollected.Add(item3);
						}
					}
				}
				PatchCallCameraClick.preventClickCalls = true;
				((MonoBehaviour)_self).StartCoroutine(PatchCallCameraClick.preventClickCollection(1f));
				((MonoBehaviour)_self).StartCoroutine(closeRuler());
				PluginD20.collecting = "";
			}
			else
			{
				if (list.Count != 2)
				{
					return;
				}
				LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Applying Selection Based On " + PluginD20.collecting);
				val2 = list[0] - list[1];
				float magnitude = ((Vector3)(ref val2)).magnitude;
				LoggingPlugin.LogDebug("Radius = " + magnitude);
				foreach (CreatureBoardAsset item4 in (IEnumerable<CreatureBoardAsset>)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets()/*cast due to .constrained prefix*/)
				{
					if (item4.CreatureId != LocalClient.SelectedCreatureId)
					{
						val2 = ((Component)((MovableBoardAsset)item4).Rotator).transform.position - list[0];
						float magnitude2 = ((Vector3)(ref val2)).magnitude;
						string[] obj2 = new string[11]
						{
							"Ruler ",
							((Object)__instance).name,
							": Asset ",
							item4.Name,
							" (",
							((object)item4.CreatureId/*cast due to .constrained prefix*/).ToString(),
							") At ",
							null,
							null,
							null,
							null
						};
						val2 = ((Component)((MovableBoardAsset)item4).Rotator).transform.position;
						obj2[7] = ((object)(*(Vector3*)(&val2))/*cast due to .constrained prefix*/).ToString();
						obj2[8] = " Is ";
						obj2[9] = magnitude2.ToString();
						obj2[10] = " away";
						LoggingPlugin.LogDebug(string.Concat(obj2));
						if (magnitude2 <= magnitude)
						{
							LoggingPlugin.LogDebug("Ruler " + ((Object)__instance).name + ": Asset " + item4.Name + " (" + ((object)item4.CreatureId/*cast due to .constrained prefix*/).ToString() + ") Is Selected");
							targetsCollection.targetsCollected.Add(item4);
						}
					}
				}
				PatchCallCameraClick.preventClickCalls = true;
				((MonoBehaviour)_self).StartCoroutine(PatchCallCameraClick.preventClickCollection(1f));
				((MonoBehaviour)_self).StartCoroutine(closeRuler());
				PluginD20.collecting = "";
			}
		}

		public static IEnumerator closeRuler()
		{
			UI_Rulers.EnableRulers(false);
			yield return (object)new WaitForSeconds(0.1f);
			UI_Rulers.EnableRulers(true);
			yield return (object)new WaitForSeconds(0.1f);
			UI_Rulers.EnableRulers(false);
		}

		public static bool IsPointInsideBox(Vector3 cornerA, Vector3 cornerB, Vector3 point)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Min(cornerA.x, cornerB.x);
			float num2 = Mathf.Max(cornerA.x, cornerB.x);
			float num3 = Mathf.Min(cornerA.y, cornerB.y);
			float num4 = Mathf.Max(cornerA.y, cornerB.y);
			float num5 = Mathf.Min(cornerA.z, cornerB.z);
			float num6 = Mathf.Max(cornerA.z, cornerB.z);
			return point.x >= num && point.x <= num2 && point.y >= num3 && point.y <= num4 && point.z >= num5 && point.z <= num6;
		}
	}

	public class RemoteQuerySpecs
	{
		public string name { get; set; }

		public string item { get; set; }
	}

	public class RemoteQueryRequest
	{
		public Guid id { get; set; }

		public RemoteQuerySpecs query { get; set; }

		public string requestor { get; set; }

		public string[] targetClients { get; set; }

		public string[] targetPlayers { get; set; }
	}

	public class RemoteQueryResponse
	{
		public Guid id { get; set; }

		public string response { get; set; }

		public string requestor { get; set; }

		public string client { get; set; }

		public string player { get; set; }
	}

	public static class RemoteQuery
	{
		public static string hold;

		public static TaskCompletionSource<bool> reactionToken;

		public static Task<List<RemoteQueryResponse>> MakeRequest(RemoteQuerySpecs query, TaskCompletionSource<List<RemoteQueryResponse>> token, string[] specificClients = null, string[] specificPlayers = null, int expectedResult = 0, int expectedResultsTimeout = 0)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			Guid guid = System.Guid.NewGuid();
			results.Add(guid, new List<RemoteQueryResponse>());
			string text = JsonConvert.SerializeObject((object)new RemoteQueryRequest
			{
				id = guid,
				query = query,
				requestor = ((object)LocalClient.Id/*cast due to .constrained prefix*/).ToString(),
				targetClients = specificClients,
				targetPlayers = specificPlayers
			});
			LoggingPlugin.LogDebug("Sending Remote Request:" + text);
			AssetDataPlugin.SendInfo("org.lordashes.plugins.d20", text);
			if (expectedResult == 0 && expectedResultsTimeout > 0)
			{
				((MonoBehaviour)_self).StartCoroutine(ProcessResultsAfterSetDelay(guid, token, expectedResultsTimeout));
			}
			else if (expectedResult == 0 && expectedResultsTimeout == 0)
			{
				((MonoBehaviour)_self).StartCoroutine(ProcessResultsAfterSetResponses(guid, token, expectedResult, 10));
			}
			else
			{
				((MonoBehaviour)_self).StartCoroutine(ProcessResultsAfterSetResponses(guid, token, expectedResult, expectedResultsTimeout));
			}
			return token.Task;
		}

		public static async void ReceiveRemoteQueryResult(DatumChange datum)
		{
			LoggingPlugin.LogDebug("Remote Message:" + JsonConvert.SerializeObject((object)datum));
			ChangeAction action = datum.action;
			ChangeAction val = action;
			ChangeAction val2 = val;
			if ((int)val2 != 0 && val2 - 2 > 1)
			{
				return;
			}
			LoggingPlugin.LogDebug("Remote Message: Checking Message Type");
			if (datum.value.ToString().Contains("message:"))
			{
				SystemMessage.DisplayInfoText("D20 Plugin:\r\n" + datum.value.ToString().Substring("message:".Length), 2.5f, 0f, (Action)null);
			}
			else if (datum.value.ToString().Contains("action:"))
			{
				string action2 = datum.value.ToString().Substring("action:".Length);
				string text = action2;
				if (text == "initiative")
				{
					LoggingPlugin.LogDebug("Remote Message: Starting Initiative Collection");
					collectingInitiative = true;
				}
			}
			else if (datum.value.ToString().Contains("query"))
			{
				LoggingPlugin.LogDebug("Remote Message: Is A Request");
				RemoteQueryRequest request = JsonConvert.DeserializeObject<RemoteQueryRequest>(datum.value.ToString());
				if ((request.targetClients != null && !request.targetClients.Contains<string>(((object)LocalClient.Id/*cast due to .constrained prefix*/).ToString())) || (request.targetPlayers != null && !request.targetPlayers.Contains<string>(((object)LocalPlayer.Id/*cast due to .constrained prefix*/).ToString())))
				{
					return;
				}
				LoggingPlugin.LogDebug("Remote Message: Seeking Sheets Matching " + request.query.name);
				Characters.CharacterSpecs[] queryResults = _self.characters.Find(DiceRoller.StripTrailingInteger(request.query.name));
				LoggingPlugin.LogDebug("Remote Message: Found " + ((queryResults == null) ? "0" : queryResults.Length.ToString()) + " Sheets");
				bool foundMatch = false;
				if (queryResults == null || queryResults.Length == 0)
				{
					return;
				}
				Characters.CharacterSpecs[] array = queryResults;
				foreach (Characters.CharacterSpecs sheet in array)
				{
					LoggingPlugin.LogDebug("Remote Message: Opposed Options " + request.query.item);
					string msg = "";
					string opposedOption = request.query.item;
					if (opposedOption.StartsWith("damage:"))
					{
						if (queryResults[0].FindFirstValue("Reaction") == "1")
						{
							LoggingPlugin.LogDebug("Delaying Response Until Opposing User Click Continue");
							hold = "Damage Reaction";
							await WaitForReaction();
						}
						LoggingPlugin.LogDebug("Remote Message: Looking For Damage Adjustments");
						string matchKeword = opposedOption.Substring("damage:".Length);
						LoggingPlugin.LogDebug("Remote Message: Looking For '" + matchKeword + "' Damage Adjustments");
						Characters.Spec immunitiesSpec = sheet.specs.Where((Characters.Spec e) => e.name == "Immunities").FirstOrDefault();
						Characters.Spec resistancesSpec = sheet.specs.Where((Characters.Spec e) => e.name == "Resistances").FirstOrDefault();
						Characters.Spec reductionsSpec = sheet.specs.Where((Characters.Spec e) => e.name == "Reductions").FirstOrDefault();
						Characters.Spec vulnerabilitiesSpec = sheet.specs.Where((Characters.Spec e) => e.name == "Vulnerabilities").FirstOrDefault();
						string immunities = ((immunitiesSpec != null) ? sheet.Resolve(immunitiesSpec.formula) : "");
						string resistances = ((resistancesSpec != null) ? sheet.Resolve(resistancesSpec.formula) : "");
						string reductions = ((reductionsSpec != null) ? sheet.Resolve(reductionsSpec.formula) : "");
						string vulnerabilities = ((vulnerabilitiesSpec != null) ? sheet.Resolve(vulnerabilitiesSpec.formula) : "");
						LoggingPlugin.LogDebug("Remote Message: Collected Possible Damage Adjustments");
						LoggingPlugin.LogDebug("Remote Message: Immunities = " + immunities);
						LoggingPlugin.LogDebug("Remote Message: Resistances = " + resistances);
						LoggingPlugin.LogDebug("Remote Message: Reductions = " + reductions);
						LoggingPlugin.LogDebug("Remote Message: Vulnerabilities = " + vulnerabilities);
						if (immunities != null && (immunities.Contains(matchKeword) || immunities.Contains("*")))
						{
							msg = msg + opposedOption + "=Immunity,";
						}
						else if (resistances != null && (resistances.Contains(matchKeword) || resistances.Contains("*")))
						{
							msg = msg + opposedOption + "=Resistance,";
						}
						else if (reductions == null || (!reductions.Contains(matchKeword) && !resistances.Contains("*")))
						{
							msg = ((vulnerabilities == null || (!vulnerabilities.Contains(matchKeword) && !vulnerabilities.Contains("*"))) ? (msg + opposedOption + "=Regular,") : (msg + opposedOption + "=Vulnerability,"));
						}
						else
						{
							string amount = reductions.Substring(reductions.IndexOf(matchKeword));
							amount = amount.Substring(amount.IndexOf("(") + 1);
							amount = amount.Substring(0, amount.IndexOf(")"));
							msg = msg + opposedOption + "=" + amount + ",";
						}
					}
					else
					{
						int bestScore = 0;
						string bestOptionName = "";
						Characters.Spec bestOption = null;
						string[] array2 = opposedOption.Split(new char[1] { ',' });
						foreach (string opposedOptionItem in array2)
						{
							if (queryResults[0].FindFirstValue("Reaction") == "1")
							{
								LoggingPlugin.LogDebug("Delaying Response Until Opposing User Click Continue");
								hold = "Defense Reaction";
								await WaitForReaction();
							}
							LoggingPlugin.LogDebug("Remote Message: Trying To Find " + opposedOption);
							Characters.Spec seekResult = sheet.specs.Where((Characters.Spec e) => e.name == opposedOption).FirstOrDefault();
							if (seekResult != null)
							{
								LoggingPlugin.LogDebug("Remote Message: Found " + seekResult.name + " (" + seekResult.formula + ")");
								int score = DiceRoller.ResolveMaxTotal(sheet.Resolve(seekResult.formula));
								if (score > bestScore)
								{
									bestScore = score;
									bestOptionName = opposedOptionItem;
									bestOption = seekResult;
								}
							}
						}
						CreatureBoardAsset target = null;
						try
						{
							target = ((IEnumerable<CreatureBoardAsset>)(object)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets()).Where((CreatureBoardAsset cba) => cba.Name == request.query.name).FirstOrDefault();
						}
						catch
						{
						}
						DiceRoller.RollResult rollResult = await DiceRoller.Roll(sheet, bestOptionName, bestOption.formula, rollingStyleDefensive);
						Scripts.ProcessExtensions(Scripts.ExtensionType.targetSkillResult, null, target, null, sheet, null, bestOptionName, null, rollResult, delegate(DiceRoller.RollResult r)
						{
							rollResult = r;
						});
						msg = msg + JsonConvert.SerializeObject((object)rollResult) + ",";
					}
					if (msg != "")
					{
						if (msg.IndexOf("=") < 0)
						{
							msg = "[" + msg.Substring(0, msg.Length - 1) + "]";
						}
						foundMatch = true;
						if (msg.EndsWith(","))
						{
							msg = msg.Substring(0, msg.Length - 1);
						}
						LoggingPlugin.LogDebug("Remote Message: Sending Result To Requestor " + request.requestor.ToString() + " Message '" + msg + "'");
						RemoteQueryResponse response = new RemoteQueryResponse
						{
							id = request.id,
							requestor = request.requestor.ToString(),
							response = msg,
							client = ((object)LocalClient.Id/*cast due to .constrained prefix*/).ToString(),
							player = ((object)LocalPlayer.Id/*cast due to .constrained prefix*/).ToString()
						};
						AssetDataPlugin.SendInfo("org.lordashes.plugins.d20", JsonConvert.SerializeObject((object)response));
					}
				}
				if (!foundMatch)
				{
					SystemMessage.DisplayInfoText("Characte Sheet For " + request.query.name + " Is Missing " + request.query.item, 2.5f, 0f, (Action)null);
				}
			}
			else
			{
				LoggingPlugin.LogDebug("Remote Message: Is A Response");
				RemoteQueryResponse result = JsonConvert.DeserializeObject<RemoteQueryResponse>(datum.value.ToString());
				LoggingPlugin.LogDebug("Remote Message: Message Destined For Requestor " + result.requestor.ToString());
				LoggingPlugin.LogDebug("Remote Message: Check: " + result.requestor + "=" + ((object)LocalClient.Id/*cast due to .constrained prefix*/).ToString() + ", Expecting Id=" + results.ContainsKey(result.id));
				if (result.requestor == ((object)LocalClient.Id/*cast due to .constrained prefix*/).ToString() && results.ContainsKey(result.id))
				{
					LoggingPlugin.LogDebug("Remote Message: Adding Response To Results List (" + result.response + ")");
					results[result.id].Add(result);
					LoggingPlugin.LogDebug("Remote Message: Collected " + results[result.id].Count() + " Responses");
				}
			}
		}

		public static async Task WaitForReaction()
		{
			try
			{
				reactionToken = new TaskCompletionSource<bool>();
				await reactionToken.Task;
				LoggingPlugin.LogDebug("Reaction " + hold + " finished");
			}
			catch (OperationCanceledException)
			{
				LoggingPlugin.LogDebug("Reaction " + hold + " was canceled");
			}
			catch (Exception ex2)
			{
				Exception ex3 = ex2;
				Debug.LogException(ex3);
			}
		}

		public static IEnumerator ProcessResultsAfterSetDelay(Guid id, TaskCompletionSource<List<RemoteQueryResponse>> token, float delay)
		{
			LoggingPlugin.LogDebug("Wait: Waiting For Responses: Started Wait For Timeout Of " + delay);
			yield return (object)new WaitForSeconds(delay);
			LoggingPlugin.LogDebug("Wait: Triggering Set Delay Callback With " + results[id].Count + " results");
			List<RemoteQueryResponse> returnResponse = results[id];
			results.Remove(id);
			LoggingPlugin.LogDebug("Wait: Results Removed From Queue. Posting Results (Token: " + ((token == null) ? "Null" : "Ready") + ")");
			token?.TrySetResult(returnResponse);
			token = null;
		}

		public static IEnumerator ProcessResultsAfterSetResponses(Guid id, TaskCompletionSource<List<RemoteQueryResponse>> token, int expectedResult, int delay)
		{
			if (delay == 0)
			{
				delay = int.MaxValue;
			}
			LoggingPlugin.LogDebug("Wait: Waiting For Responses: Started Wait For " + expectedResult + " Responses With Timeout Of " + delay);
			for (ulong i = 0uL; i < (ulong)((long)delay * 2L); i++)
			{
				if (results[id].Count >= expectedResult)
				{
					break;
				}
				yield return (object)new WaitForSeconds(0.5f);
			}
			LoggingPlugin.LogDebug("Wait: Triggering Set Responses Callback With " + results[id].Count + " results");
			List<RemoteQueryResponse> returnResponse = results[id];
			results.Remove(id);
			LoggingPlugin.LogDebug("Wait: Results Removed From Queue. Posting Results (Token: " + ((token == null) ? "Null" : "Ready") + ")");
			token?.TrySetResult(returnResponse);
			token = null;
		}
	}

	public static class Scripts
	{
		public class Script
		{
			public string use { get; set; }

			public string gm { get; set; }

			public string instigator { get; set; }

			public string target { get; set; }

			public string others { get; set; }

			public string instigator_speech { get; set; }

			public string target_speech { get; set; }
		}

		public enum ExtensionType
		{
			instigatorSkillResult = 1,
			targetSkillResult,
			damageResult
		}

		public class ToggleCallaback
		{
			public ToggleRequired toggleOnWho { get; set; }

			public string toggleName { get; set; }

			public Func<CreatureBoardAsset, CreatureBoardAsset, Characters.CharacterSpecs, Characters.CharacterSpecs, Characters.Spec, string, Characters.Spec, DiceRoller.RollResult, Task<DiceRoller.RollResult>> callback { get; set; }
		}

		public enum ToggleRequired
		{
			instigator,
			target
		}

		public enum MessagePublicity
		{
			publicMessage,
			semiPrivateMessage,
			privateMessage
		}

		public static List<Script> scripts = new List<Script>();

		public static DiceRoller.RollResult commonDamage = null;

		public static bool waitingOnRemoteAction = false;

		public static List<object[]> chainList = new List<object[]>();

		private static Dictionary<ExtensionType, List<ToggleCallaback>> extensions = new Dictionary<ExtensionType, List<ToggleCallaback>>();

		public static void LoadScripts()
		{
			string text = File.ReadAllText("org.lordashes.plugins.d20.scripts.json", (CacheType)999);
			text = text.TrimStart('\ufeff', '\u200b');
			scripts = JsonConvert.DeserializeObject<List<Script>>(text);
			LoggingPlugin.LogInfo("Loaded " + scripts.Count + " Scripts");
			foreach (ExtensionType value in Enum.GetValues(typeof(ExtensionType)))
			{
				if (!extensions.ContainsKey(value))
				{
					extensions.Add(value, new List<ToggleCallaback>());
				}
			}
		}

		public static void RegisterExtension(ToggleRequired toggleOnWho, ExtensionType extensionType, string toggleName, Func<CreatureBoardAsset, CreatureBoardAsset, Characters.CharacterSpecs, Characters.CharacterSpecs, Characters.Spec, string, Characters.Spec, DiceRoller.RollResult, Task<DiceRoller.RollResult>> callback)
		{
			if (!extensions.ContainsKey(extensionType))
			{
				extensions.Add(extensionType, new List<ToggleCallaback>());
			}
			extensions[extensionType].Add(new ToggleCallaback
			{
				toggleName = toggleName,
				callback = callback
			});
		}

		public static IEnumerator ProcessExtensions(ExtensionType extensionType, CreatureBoardAsset instigator, CreatureBoardAsset target, Characters.CharacterSpecs instigatorSheet, Characters.CharacterSpecs targetSheet, Characters.Spec instigatorCheck, string targetCheck, Characters.Spec spec, DiceRoller.RollResult rollResult, Action<DiceRoller.RollResult> onComplete)
		{
			foreach (ToggleCallaback extension in extensions[extensionType])
			{
				if ((extension.toggleOnWho == ToggleRequired.instigator && instigatorSheet.FindFirstValue(extension.toggleName) == "1") || (extension.toggleOnWho == ToggleRequired.target && targetSheet.FindFirstValue(extension.toggleName) == "1"))
				{
					LoggingPlugin.LogDebug("Executing Extension For " + extension.toggleName);
					Task<DiceRoller.RollResult> extensionTask = extension.callback(instigator, target, instigatorSheet, targetSheet, instigatorCheck, targetCheck, spec, rollResult);
					yield return (object)new WaitUntil((Func<bool>)(() => extensionTask.IsCompleted));
					rollResult = extensionTask.Result;
				}
			}
			onComplete?.Invoke(rollResult);
		}

		private static IEnumerator QueryRemotes(RemoteQuerySpecs query, TaskCompletionSource<List<RemoteQueryResponse>> token, string[] specificClients, string[] specificPlayers, int expectedResults, int expectedResultsTimeout, Action<DiceRoller.RollResult> onComplete)
		{
			Task<List<RemoteQueryResponse>> queryTask = RemoteQuery.MakeRequest(query, token, specificClients, specificPlayers, expectedResults, expectedResultsTimeout);
			yield return (object)new WaitUntil((Func<bool>)(() => queryTask.IsCompleted));
			DiceRoller.RollResult queryTaskRollResult = JsonConvert.DeserializeObject<List<DiceRoller.RollResult>>(queryTask.Result[0].response).ToArray()[0];
			onComplete?.Invoke(queryTaskRollResult);
		}

		private static IEnumerator QueryRemotesForDamage(RemoteQuerySpecs query, TaskCompletionSource<List<RemoteQueryResponse>> token, string[] specificClients, string[] specificPlayers, int expectedResults, int expectedResultsTimeout, Action<string> onComplete)
		{
			Task<List<RemoteQueryResponse>> queryTask = RemoteQuery.MakeRequest(query, token, specificClients, specificPlayers, expectedResults, expectedResultsTimeout);
			yield return (object)new WaitUntil((Func<bool>)(() => queryTask.IsCompleted));
			onComplete?.Invoke(queryTask.Result[0].response);
		}

		private static IEnumerator RollDice(Characters.CharacterSpecs instigatorSheet, string rollName, string rollFormula, Action<DiceRoller.RollResult> onComplete)
		{
			Task<DiceRoller.RollResult> rollTask = DiceRoller.Roll(instigatorSheet, rollName, rollFormula, rollingStyleOffensive);
			yield return (object)new WaitUntil((Func<bool>)(() => rollTask.IsCompleted));
			onComplete?.Invoke(rollTask.Result);
		}

		public static IEnumerator ProcessSequence(Characters.CharacterSpecs stack, Characters.CharactersSpecs.CheckType action, Characters.Spec check, CreatureBoardAsset instigator, CreatureBoardAsset[] targets, MessagePublicity publicity)
		{
			LoggingPlugin.LogInfo("--------------------------------------------------------------------------------");
			LoggingPlugin.LogInfo("  Started " + instigator.Name + "'s " + check.name + " (" + action.ToString() + ")");
			LoggingPlugin.LogInfo("--------------------------------------------------------------------------------");
			yield return (object)new WaitForSeconds(0.1f);
			if (action == Characters.CharactersSpecs.CheckType.Attack || action == Characters.CharactersSpecs.CheckType.Opposed || action == Characters.CharactersSpecs.CheckType.Regular)
			{
				yield return ProcessInstigatorRoll(stack, action, check, instigator, publicity);
				if (action != Characters.CharactersSpecs.CheckType.Regular && (targets == null || targets.Length == 0))
				{
					LoggingPlugin.LogDebug("No Target Selected For Opposed Check. Processing As Regular Check.");
					action = Characters.CharactersSpecs.CheckType.Regular;
				}
			}
			if (targets != null)
			{
				bool firstTarget = true;
				foreach (CreatureBoardAsset target in targets)
				{
					LoggingPlugin.LogDebug("--------------------------------------------------------------------------------");
					LoggingPlugin.LogDebug("  Processing " + instigator.Name + "'s " + check.name + " Vs " + target.Name);
					LoggingPlugin.LogDebug("--------------------------------------------------------------------------------");
					if (action == Characters.CharactersSpecs.CheckType.Attack || action == Characters.CharactersSpecs.CheckType.Opposed)
					{
						yield return ProcessTargetRoll(stack, action, check, instigator, target, publicity);
						if (int.Parse(stack.FindFirstValue("total")) >= int.Parse(stack.FindFirstValue("opposedTotal")))
						{
							stack.AddOrModifyValue("result", "Hit");
						}
						else if (check.Extra("half") != null)
						{
							stack.AddOrModifyValue("result", "Half");
						}
						else
						{
							stack.AddOrModifyValue("result", "Miss");
						}
						SendMessages(action.ToString() + "." + stack.FindFirstValue("result"), stack, instigator, null, publicity);
						if (action == Characters.CharactersSpecs.CheckType.Attack && stack.FindFirstValue("result").ToUpper() != "MISS")
						{
							yield return AnimateAttack(check, instigator, target, firstTarget, success: true);
							yield return ProcessDamageOnTarget(stack, action, check, instigator, target, stack.FindFirstValue("result"), publicity);
							yield return ProcessEffectOnTarget(stack, action, check, instigator, target, stack.FindFirstValue("result"), publicity);
						}
						else if (action == Characters.CharactersSpecs.CheckType.Attack)
						{
							yield return AnimateAttack(check, instigator, target, firstTarget, success: false);
						}
					}
					LoggingPlugin.LogDebug("Staring etting Instigator Sheet...");
					LoggingPlugin.LogDebug(instigator.Name);
					LoggingPlugin.LogDebug(DiceRoller.StripTrailingInteger(instigator.Name));
					_self.characters.FindFirst(DiceRoller.StripTrailingInteger(instigator.Name));
					LoggingPlugin.LogDebug("Ended Getting Instigator Sheet...");
					LoggingPlugin.LogDebug("Looking For Chains");
					string chain = check.Extra("chainAlways");
					if (chain != null)
					{
						LoggingPlugin.LogDebug("Adding chainAlways chain: " + chain);
						string item = chain.Substring(chain.LastIndexOf("/") + 1);
						string menu = chain.Substring(0, chain.LastIndexOf("/"));
						chainList.Add(new object[5]
						{
							item,
							"/" + instigator.Name + menu,
							new CreatureBoardAsset[1] { instigator },
							new CreatureBoardAsset[1] { target },
							publicity
						});
					}
					else if (stack.FindFirstValue("result") == "Hit")
					{
						chain = check.Extra("chainSuccess");
						if (chain != null)
						{
							LoggingPlugin.LogDebug("Adding chainSuccess chain: " + chain);
							string item2 = chain.Substring(chain.LastIndexOf("/") + 1);
							string menu2 = chain.Substring(0, chain.LastIndexOf("/"));
							chainList.Add(new object[5]
							{
								item2,
								"/" + instigator.Name + menu2,
								new CreatureBoardAsset[1] { instigator },
								new CreatureBoardAsset[1] { target },
								publicity
							});
						}
					}
					else
					{
						chain = check.Extra("chainFailure");
						if (chain != null)
						{
							LoggingPlugin.LogDebug("Adding chainFailure chain: " + chain);
							string item3 = chain.Substring(chain.LastIndexOf("/") + 1);
							string menu3 = chain.Substring(0, chain.LastIndexOf("/"));
							chainList.Add(new object[5]
							{
								item3,
								"/" + instigator.Name + menu3,
								new CreatureBoardAsset[1] { instigator },
								new CreatureBoardAsset[1] { target },
								publicity
							});
						}
					}
					firstTarget = false;
				}
			}
			if (chainList.Count > 0)
			{
				LoggingPlugin.LogDebug("Processing next chain");
				object[] parameters = chainList.ElementAt(0);
				chainList.RemoveAt(0);
				for (int p = 0; p <= 3; p++)
				{
					LoggingPlugin.LogDebug("Parameter " + p + ": " + parameters[p].GetType()?.ToString() + ": " + parameters[p].ToString());
				}
				((MonoBehaviour)_self).StartCoroutine(Characters.InitiateMenuAction((string)parameters[0], (string)parameters[1], (CreatureBoardAsset[])parameters[2], (CreatureBoardAsset[])parameters[3]));
			}
			commonDamage = null;
			LoggingPlugin.LogTrace("--------------------------------------------------------------------------------");
			LoggingPlugin.LogTrace("  Completed " + instigator.Name + "'s " + check.name + " (" + action.ToString() + ")");
			LoggingPlugin.LogTrace("--------------------------------------------------------------------------------");
		}

		public static IEnumerator ProcessInstigatorRoll(Characters.CharacterSpecs stack, Characters.CharactersSpecs.CheckType action, Characters.Spec check, CreatureBoardAsset instigator, MessagePublicity publicity)
		{
			LoggingPlugin.LogDebug("Starting ProcessInstigatorRoll...");
			if ((Object)(object)instigator != (Object)null)
			{
				LoggingPlugin.LogDebug("Instigator: " + instigator.Name);
				LoggingPlugin.LogTrace("Getting " + DiceRoller.StripTrailingInteger(instigator.Name) + " Sheet");
				Characters.CharacterSpecs instigatorSheet = _self.characters.FindFirst(DiceRoller.StripTrailingInteger(instigator.Name));
				DiceRoller.RollResult rollResult = null;
				yield return RollDice(instigatorSheet, check.name, check.formula, delegate(DiceRoller.RollResult r)
				{
					rollResult = r;
				});
				LoggingPlugin.LogDebug("Instigator Roll: Name: " + rollResult.name);
				LoggingPlugin.LogDebug("Instigator Roll: Formula: " + rollResult.formula);
				LoggingPlugin.LogDebug("Instigator Roll: Roll: " + rollResult.formulaResolved);
				LoggingPlugin.LogDebug("Instigator Roll: Dice: " + rollResult.formulaDice);
				LoggingPlugin.LogDebug("Instigator Roll: Total: " + rollResult.total);
				yield return ProcessExtensions(ExtensionType.instigatorSkillResult, instigator, null, instigatorSheet, null, check, null, null, rollResult, delegate(DiceRoller.RollResult r)
				{
					rollResult = r;
				});
				stack.AddOrModifyValue("instigatorName", instigator.Name);
				stack.AddOrModifyValue("name", rollResult.name);
				stack.AddOrModifyValue("formula", rollResult.formula);
				stack.AddOrModifyValue("roll", rollResult.formulaResolved);
				stack.AddOrModifyValue("dice", rollResult.formulaDice);
				stack.AddOrModifyValue("total", rollResult.total.ToString());
				LoggingPlugin.LogInfo(instigator.Name + "'s " + check.name + " = " + rollResult.total);
				LoggingPlugin.LogDebug("Setting up crit value");
				string co = check.Extra("critOn");
				int critOn = ((co != null) ? int.Parse(co) : 20);
				bool crit = false;
				if (rollResult.dice != null && rollResult.dice.Length != 0)
				{
					crit = rollResult.dice[0] >= critOn && critOn > 0;
					LoggingPlugin.LogDebug("Die: " + rollResult.dice[0] + ", Crit On: " + critOn + ", Crit: " + crit);
				}
				stack.AddOrModifyValue("crit", crit.ToString());
				LoggingPlugin.LogDebug("Sending notifications");
				stack.AddOrModifyValue("instigatorName", instigator.Name);
				stack.AddOrModifyValue("name", rollResult.name);
				stack.AddOrModifyValue("formula", rollResult.formula);
				stack.AddOrModifyValue("roll", rollResult.formulaResolved);
				stack.AddOrModifyValue("dice", rollResult.formulaDice);
				stack.AddOrModifyValue("total", rollResult.total.ToString());
				SendMessages(action.ToString() + ".Instigation", stack, instigator, null, publicity);
			}
		}

		public static IEnumerator ProcessTargetRoll(Characters.CharacterSpecs stack, Characters.CharactersSpecs.CheckType action, Characters.Spec instigatorCheck, CreatureBoardAsset instigator, CreatureBoardAsset target, MessagePublicity publicity)
		{
			LoggingPlugin.LogDebug("Starting ProcessTargetRoll...");
			if ((Object)(object)target != (Object)null)
			{
				LoggingPlugin.LogDebug("Target: " + target.Name);
				string opposed = instigatorCheck.Extra("opposed");
				string opposedList = ((opposed != null) ? opposed : "AC");
				LoggingPlugin.LogDebug(instigatorCheck.name + " is opposed by " + opposedList);
				waitingOnRemoteAction = true;
				DiceRoller.RollResult opposedRoll = null;
				yield return QueryRemotes(new RemoteQuerySpecs
				{
					name = target.Name,
					item = opposedList
				}, new TaskCompletionSource<List<RemoteQueryResponse>>(), null, null, 1, 0, delegate(DiceRoller.RollResult r)
				{
					opposedRoll = r;
				});
				waitingOnRemoteAction = false;
				stack.AddOrModifyValue("targetName", target.Name);
				stack.AddOrModifyValue("opposedName", opposedRoll.name);
				stack.AddOrModifyValue("opposedFormula", opposedRoll.formula);
				stack.AddOrModifyValue("opposedRoll", opposedRoll.formulaResolved);
				stack.AddOrModifyValue("opposedDice", opposedRoll.formulaDice);
				stack.AddOrModifyValue("opposedTotal", opposedRoll.total.ToString());
				Characters.CharacterSpecs instigatorSheet = _self.characters.FindFirst(DiceRoller.StripTrailingInteger(instigator.Name));
				Characters.CharacterSpecs targetSheet = _self.characters.FindFirst(DiceRoller.StripTrailingInteger(target.Name));
				yield return ProcessExtensions(ExtensionType.targetSkillResult, instigator, target, instigatorSheet, targetSheet, instigatorCheck, opposedRoll.name, null, opposedRoll, delegate(DiceRoller.RollResult r)
				{
					opposedRoll = r;
				});
				stack.AddOrModifyValue("opposedName", opposedRoll.name);
				stack.AddOrModifyValue("opposedFormula", opposedRoll.formula);
				stack.AddOrModifyValue("opposedRoll", opposedRoll.formulaResolved);
				stack.AddOrModifyValue("opposedDice", opposedRoll.formulaDice);
				stack.AddOrModifyValue("opposedTotal", opposedRoll.total.ToString());
				LoggingPlugin.LogInfo(target.Name + "'s " + opposedRoll.name + " = " + opposedRoll.total);
				SendMessages(action.ToString() + ".Opposition", stack, instigator, target, publicity);
			}
			LoggingPlugin.LogDebug("Ended ProcessTargetRoll...");
		}

		public static IEnumerator ProcessDamageOnTarget(Characters.CharacterSpecs stack, Characters.CharactersSpecs.CheckType action, Characters.Spec check, CreatureBoardAsset instigator, CreatureBoardAsset target, string severity, MessagePublicity publicity, string overrideDamage = null)
		{
			LoggingPlugin.LogDebug("Starting ProcessDamageOnTarget..." + instigator.Name + " To " + (((Object)(object)target != (Object)null) ? target.Name : "None"));
			stack.AddOrModifyValue("instigatorName", ((Object)(object)instigator != (Object)null) ? instigator.Name : "None");
			stack.AddOrModifyValue("targetName", ((Object)(object)target != (Object)null) ? target.Name : "None");
			Characters.CharacterSpecs instigatorSheet = _self.characters.FindFirst(DiceRoller.StripTrailingInteger(instigator.Name));
			Characters.CharacterSpecs targetSheet = _self.characters.FindFirst(DiceRoller.StripTrailingInteger(target.Name));
			string dmg = check.Extra("damage");
			string[] damageSpecNames = ((dmg != null) ? dmg.Replace("[", "").Replace("]", "").Replace("'", "")
				.Split(new char[1] { ',' }) : new string[0]);
			if (overrideDamage != null)
			{
				damageSpecNames = overrideDamage.Split(new char[1] { ',' });
			}
			LoggingPlugin.LogDebug("Damages: " + string.Join(",", damageSpecNames));
			string[] array = damageSpecNames;
			CreatureDataV4 creatureData = default(CreatureDataV4);
			foreach (string damageSpecNameRaw in array)
			{
				string damageSpecName = damageSpecNameRaw.Trim();
				if (damageSpecName.Trim() != "" || damageSpecName.ToUpper() != "NONE")
				{
					LoggingPlugin.LogDebug("Damage: '" + damageSpecName + "'");
					Characters.Spec damageSpec = instigatorSheet.FindFirst(damageSpecName);
					LoggingPlugin.LogDebug("Found damage spec '" + damageSpecName + "': " + (damageSpec != null));
					LoggingPlugin.LogDebug("Querying " + target.Name + " For Modifiers To " + damageSpec.Extra("damageType"));
					string adjustor = null;
					waitingOnRemoteAction = true;
					yield return QueryRemotesForDamage(new RemoteQuerySpecs
					{
						name = target.Name,
						item = "damage:" + damageSpec.Extra("damageType")
					}, new TaskCompletionSource<List<RemoteQueryResponse>>(), null, null, 1, 0, delegate(string r)
					{
						adjustor = r;
					});
					waitingOnRemoteAction = false;
					adjustor = adjustor.Substring(adjustor.IndexOf("=") + 1);
					string critString = stack.FindFirstValue("crit");
					bool crit = ((critString != null && critString != "" && bool.Parse(critString)) ? true : false);
					string cf = damageSpec.Extra("critFormula");
					string critFormula = ((cf != null) ? cf : damageSpec.formula);
					string damageFormula;
					if (crit)
					{
						LoggingPlugin.LogDebug("Using Crit Damage: \"" + Convert.ToString(critFormula) + "\"");
						damageFormula = critFormula;
					}
					else
					{
						LoggingPlugin.LogDebug("Using Regular Damage: \"" + Convert.ToString(damageSpec.formula) + "\"");
						damageFormula = damageSpec.formula;
					}
					DiceRoller.RollResult damage = null;
					if (commonDamage == null)
					{
						yield return RollDice(instigatorSheet, damageSpec.name, damageFormula, delegate(DiceRoller.RollResult r)
						{
							damage = r;
						});
						stack.AddOrModifyValue("damageName", damageSpec.name);
						stack.AddOrModifyValue("damageType", instigatorSheet.Resolve(damageSpec.Extra("damageType")));
						stack.AddOrModifyValue("damageFormula", damage.formula);
						stack.AddOrModifyValue("damageRoll", damage.formulaResolved);
						stack.AddOrModifyValue("damageDice", damage.formulaDice);
						stack.AddOrModifyValue("damageTotal", damage.total.ToString());
						yield return ProcessExtensions(ExtensionType.damageResult, instigator, target, instigatorSheet, targetSheet, check, null, damageSpec, damage, delegate(DiceRoller.RollResult r)
						{
							damage = r;
						});
						if (!ResolvePlaceHolders(instigatorSheet, check.formula).Contains("1D20"))
						{
							LoggingPlugin.LogDebug("Storing Common Damage");
							commonDamage = damage;
						}
						else
						{
							LoggingPlugin.LogDebug("Using Individual Damage");
						}
					}
					else
					{
						damage = commonDamage;
					}
					stack.AddOrModifyValue("damageName", damageSpec.name);
					stack.AddOrModifyValue("damageType", instigatorSheet.Resolve(damageSpec.Extra("damageType")));
					stack.AddOrModifyValue("damageFormula", damage.formula);
					stack.AddOrModifyValue("damageRoll", damage.formulaResolved);
					stack.AddOrModifyValue("damageDice", damage.formulaDice);
					stack.AddOrModifyValue("damageTotal", damage.total.ToString());
					int damageAdjusted = damage.total;
					if (damageSpec.Extra("damageType").ToUpper() == "NON-RESISTED")
					{
						adjustor = "Regular";
					}
					LoggingPlugin.LogDebug("Damage Total: " + damageAdjusted);
					damageAdjusted = ((!(severity.ToUpper() == "HIT")) ? Convert.ToInt32(damage.total / 2) : damage.total);
					LoggingPlugin.LogDebug("Damage Total After Save-For-Half Adjustment: " + damageAdjusted);
					switch (adjustor)
					{
					case "Vulnerability":
						LoggingPlugin.LogDebug("Applying Vulnerability");
						damageAdjusted *= 2;
						break;
					case "Resistance":
						LoggingPlugin.LogDebug("Applying Resistance");
						damageAdjusted = Convert.ToInt32(damageAdjusted / 2);
						break;
					case "Immunity":
						LoggingPlugin.LogDebug("Applying Immunity");
						damageAdjusted = 0;
						break;
					}
					LoggingPlugin.LogDebug("Damage Total After V/R/I Adjustment: " + damageAdjusted);
					int adjustorInt = 0;
					if (int.TryParse(adjustor, out adjustorInt))
					{
						LoggingPlugin.LogDebug("Applying Reduction " + adjustor);
						damageAdjusted -= adjustorInt;
						adjustor = "Reduction(" + adjustor + ")";
					}
					damageAdjusted = Math.Max(damageAdjusted, 0);
					string[] obj = new string[8]
					{
						instigator.Name,
						"'s ",
						check.name,
						" does ",
						damageAdjusted.ToString(),
						" ",
						null,
						null
					};
					string dt = damageSpec.Extra("damageType");
					obj[6] = ((dt != null) ? dt : "Generic");
					obj[7] = " damage";
					LoggingPlugin.LogInfo(string.Concat(obj));
					stack.AddOrModifyValue("damageAdjusted", damageAdjusted.ToString());
					if (severity == "Half")
					{
						if (adjustor == "Regular")
						{
							adjustor = "Save";
						}
						else
						{
							adjustor = "Save With " + adjustor;
						}
					}
					stack.AddOrModifyValue("damageAdjustor", adjustor);
					CreatureManager.TryGetCreatureData(target.CreatureId, ref creatureData);
					float value = creatureData.Hp.Value;
					stack.AddOrModifyValue("targetOldHP", value.ToString());
					stack.AddOrModifyValue("targetHP", (creatureData.Hp.Value - (float)damageAdjusted).ToString());
					value = creatureData.Hp.Max;
					stack.AddOrModifyValue("targetMaxHP", value.ToString());
					float lifePercentage = 100f * (target.Hp.Value - (float)damageAdjusted) / creatureData.Hp.Max;
					if (lifePercentage == 100f)
					{
						stack.AddOrModifyValue("targetState", "Unhurt");
					}
					else if (lifePercentage >= 75f)
					{
						stack.AddOrModifyValue("targetState", "Scratched");
					}
					else if (lifePercentage >= 50f)
					{
						stack.AddOrModifyValue("targetState", "Wounded");
					}
					else if (lifePercentage >= 25f)
					{
						stack.AddOrModifyValue("targetState", "Bloodied");
					}
					else if (lifePercentage > 0f)
					{
						stack.AddOrModifyValue("targetState", "Critical");
					}
					else
					{
						stack.AddOrModifyValue("targetState", "Dying");
						if (useAnimations.Value)
						{
							EmoteCollectionItem emote = EmoteManager.GetCollection().Emotes.Where((EmoteCollectionItem e) => ((Object)e.Emote).name.Contains(deadAnimation.Value.ToS

plugins/Convert_5E_D20.exe

Decompiled 2 months ago
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Newtonsoft.Json;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Convert_5E_D20")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Convert_5E_D20")]
[assembly: AssemblyCopyright("Copyright ©  2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("95555fb9-cfae-4c7f-a72d-9f9b39621e26")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("2.0.0.0")]
namespace Convert_5E_D20;

internal class Program
{
	public class Link
	{
		public string name { get; set; } = "";

		public string type { get; set; } = "";

		public string roll { get; set; } = "";

		public Link link { get; set; } = null;
	}

	public class Attack
	{
		public string name { get; set; } = "";

		public string type { get; set; } = "";

		public string roll { get; set; } = "";

		public string critrangemin { get; set; } = "";

		public string critmultip { get; set; } = "";

		public string range { get; set; } = "";

		public Link link { get; set; } = null;

		public string menuUI { get; set; } = null;
	}

	private class Character
	{
		public string NPC { get; set; } = "";

		public string reach { get; set; } = "";

		public string lv { get; set; } = "";

		public string ac { get; set; } = "";

		public string hp { get; set; } = "";

		public string str { get; set; } = "";

		public string dex { get; set; } = "";

		public string con { get; set; } = "";

		public string Int { get; set; } = "";

		public string wis { get; set; } = "";

		public string cha { get; set; } = "";

		public string speed { get; set; } = "";

		public string var1 { get; set; } = "";

		public string var2 { get; set; } = "";

		public string var3 { get; set; } = "";

		public Attack[] attacks { get; set; } = null;

		public Attack[] attacksDC { get; set; } = null;

		public Link[] saves { get; set; } = null;

		public Link[] skills { get; set; } = null;

		public Link[] healing { get; set; } = null;

		public string[] resistance { get; set; } = new string[0];

		public string[] immunity { get; set; } = new string[0];

		public string[] vulnerability { get; set; } = new string[0];

		public void Convert(string name)
		{
			File.WriteAllText("org.lordashes.plugins.d20.character." + name + ".json", "{\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "  \"name\": \"" + name + "\",\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "  \"specs\": [\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"NPC\", \"formula\": \"" + NPC + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"LV\", \"formula\": \"" + ((lv == "") ? "1" : lv) + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"EX\", \"formula\": \"" + Prof("EX") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"PB\", \"formula\": \"" + Prof("PB") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"PH\", \"formula\": \"" + Prof("PH") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"VAR1\", \"formula\": \"" + var1 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"VAR2\", \"formula\": \"" + var2 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"VAR3\", \"formula\": \"" + var3 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"Reaction\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Reaction\" }, { \"key\": \"toggle\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"ROLL\", \"formula\": \"\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Roll (A/D)\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"AB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Attack Bonus (AB)\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"ACB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic AC Bonus (ACB)\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"DB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Damage Bonus (DB)\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"DCB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Spell DC Bonus (DCB)\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"HB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Healing Bonus (HB)\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"SB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Skill Bonus (SB)\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"SVB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Save Bonus (SVB)\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"AC\", \"formula\": \"" + ac + "+[SS]+[ACB]\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"} ], \"menu\": \"/info/AC\" },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"HP\", \"formula\": \"" + hp + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"} ], \"menu\": \"/info/HP(Max)\" },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"REACH\", \"formula\": \"" + reach + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"} ], \"menu\": \"/info/Reach\" },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"SPEED\", \"formula\": \"" + speed + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"} ], \"menu\": \"/info/Speed\" },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"STR\", \"formula\": \"" + Modifier(str) + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + str + "\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"DEX\", \"formula\": \"" + Modifier(dex) + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + dex + "\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"CON\", \"formula\": \"" + Modifier(con) + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + con + "\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"INT\", \"formula\": \"" + Modifier(Int) + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + Int + "\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"WIS\", \"formula\": \"" + Modifier(wis) + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + wis + "\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"CHA\", \"formula\": \"" + Modifier(cha) + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + cha + "\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"EVASION_ZERO\", \"formula\": \"\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Evasion (* for Zero Damage)\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"EVASION_HALF\", \"formula\": \"\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Evasion (* for 1/2 Damage)\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"TOGGLE1\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Shield Spell (SS)\" }, { \"key\": \"toggle\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"SS\", \"formula\": \"[TOGGLE1]*5\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"TOGGLE2\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Bless Spell (BLESS)\" }, { \"key\": \"toggle\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"BLESS\", \"formula\": \"[TOGGLE2]*1D4\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"TOGGLE3\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Guidance Cantrip (GUIDE)\" }, { \"key\": \"toggle\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"GUIDE\", \"formula\": \"[TOGGLE3]*1D4\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" } ], \"menu\": null },\r\n");
			Link[] array = saves;
			foreach (Link link in array)
			{
				File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"" + link.name + " Save\", \"formula\": \"" + link.roll.ToUpper().Replace("1D20", "").Replace("{", "[")
					.Replace("}", "]") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			}
			Link[] array2 = saves;
			foreach (Link link2 in array2)
			{
				File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"" + link2.name + " Save Roll\", \"formula\": \"1D20+[" + link2.name.ToUpper().Replace("{", "[").Replace("}", "]") + " Save]+[BLESS]+[SVB]\", \"extra\": [ {\"key\": \"type\", \"value\": \"save\"} ], \"menu\": \"/saves/" + link2.name + "\" },\r\n");
			}
			Link[] array3 = skills;
			foreach (Link link3 in array3)
			{
				File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"" + link3.name.Replace(" [GM]", "") + "\", \"formula\": \"" + link3.roll.ToUpper().Replace("{", "[").Replace("}", "]") + "+[GUIDE]+[SB]\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}" + OpposedSkill(link3.name) + " ], \"menu\": \"/skills/" + link3.name + "\" },\r\n");
			}
			Attack[] array4 = attacks;
			foreach (Attack attack in array4)
			{
				if (!attack.roll.StartsWith("100"))
				{
					File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"" + attack.name + "\", \"formula\": \"" + attack.roll.ToUpper().Replace("{", "[").Replace("}", "]") + "+[BLESS]+[AB]\", \"extra\": [ {\"key\": \"type\", \"value\": \"attack\"}, { \"key\": \"opposed\", \"value\": \"AC\" }" + GetDamageListJson(attack.name, attack.link) + GetEffectListJson(attack.name, attack.link) + " ], \"menu\": \"" + Menu(attack.menuUI, "/attack/" + attack.type + "/" + attack.name) + "\" },\r\n");
				}
				ProcessLinks(name, attack.name, attack.type, attack.link);
			}
			Attack[] array5 = attacksDC;
			foreach (Attack attack2 in array5)
			{
				string[] array6 = ParseSave(attack2.roll);
				if (!attack2.roll.StartsWith("100"))
				{
					File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"" + attack2.name + "\", \"formula\": \"" + array6[0].ToUpper().Replace("{", "[").Replace("}", "]") + "+[DCB]\", \"extra\": [ {\"key\": \"type\", \"value\": \"attack\"}, { \"key\": \"opposed\", \"value\": \"" + array6[1] + "\" }" + GetDamageListJson(attack2.name, attack2.link) + GetEffectListJson(attack2.name, attack2.link) + " ], \"menu\": \"" + Menu(attack2.menuUI, "/attack/" + attack2.type + "/" + attack2.name) + "\" },\r\n");
				}
				ProcessLinks(name, attack2.name, attack2.type, attack2.link);
			}
			Link[] array7 = healing;
			foreach (Link link4 in array7)
			{
				File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"" + link4.name + "\", \"formula\": \"" + link4.roll.ToUpper().Replace("{", "[").Replace("}", "]") + "+[HB]\", \"extra\": [ {\"key\": \"type\", \"value\": \"heal\"} ], \"menu\": \"/healing/" + link4.name + "\" },\r\n");
			}
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"Immunities\", \"formula\": \"" + string.Join(",", immunity) + ",[EVASION_ZERO]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"Resistances\", \"formula\": \"" + string.Join(",", resistance) + ",[EVASION_HALF]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"Vulnerabilities\", \"formula\": \"" + string.Join(",", vulnerability) + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"BATTLECRY\", \"formula\": \"CHOICE: Take that! | Face my wrath! | And now you die!\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" } ], \"menu\": null },\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"FAILURECRY\", \"formula\": \"CHOICE: Close! | Wait till next time! | That was a warning!\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" } ], \"menu\": null }\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "  ]\r\n");
			File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "}\r\n");
		}

		public string Modifier(string valueStr)
		{
			int num = int.Parse(valueStr);
			if (num >= 10)
			{
				return ((num - 10) / 2).ToString();
			}
			return ((num - 11) / 2).ToString();
		}

		public int Prof(string name)
		{
			int num = ((lv == "") ? 1 : int.Parse(lv));
			int num2 = 2 + (num - 1) / 4;
			int result = num2 * 2;
			int result2 = num2 / 2;
			string text = name.ToUpper();
			string text2 = text;
			if (!(text2 == "EX"))
			{
				if (text2 == "PH")
				{
					return result2;
				}
				return num2;
			}
			return result;
		}

		public string Menu(string location, string defaultLocation)
		{
			string text = defaultLocation.Substring(defaultLocation.LastIndexOf("/") + 1);
			if (location == null || location == "")
			{
				return defaultLocation.Trim();
			}
			return ("/Attacks/" + location + "/" + text).Trim();
		}

		public void ProcessLinks(string name, string attackName, string attackType, Link link)
		{
			while (link != null)
			{
				if (link.type != "")
				{
					File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"" + attackName + " (" + link.name + ") Damage\", \"formula\": \"" + link.roll.ToUpper().Replace("{", "[").Replace("}", "]") + "+[DB]\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"" + link.type + "\"} ], \"menu\": \"/damage/" + attackType + "/" + attackName + " (" + link.name + ") Damage\" },\r\n");
				}
				else
				{
					File.AppendAllText("org.lordashes.plugins.d20.character." + name + ".json", "    { \"name\": \"" + attackName + " (" + link.name + ") Effect\", \"formula\": \"Causes " + link.name + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"effect\"} ], \"menu\": \"/effect/" + attackType + "/" + attackName + " (" + link.name + ") Effect\" },\r\n");
				}
				link = link.link;
			}
		}

		private string OpposedSkill(string name)
		{
			string text = ", { \"key\": \"opposed\", \"value\": \"";
			switch (name)
			{
			case "Acrobatics":
				return "";
			case "Animal Handling":
				return "";
			case "Arcana":
				return "";
			case "Athletics":
				return "";
			case "Deception":
				text += "Insight";
				break;
			case "Grapple":
				text += "Athletics,Acrobatics";
				break;
			case "History":
				return "";
			case "Insight":
				text += "Deception";
				break;
			case "Intimidation":
				return "";
			case "Investigation":
				return "";
			case "Medicine":
				return "";
			case "Nature":
				return "";
			case "Perception":
				text += "Stealth";
				break;
			case "Performance":
				return "";
			case "Persuasion":
				return "";
			case "Religion":
				return "";
			case "Sleight of Hand":
				text += "Perception";
				break;
			case "Stealth":
				text += "Perception";
				break;
			case "Survival":
				return "";
			default:
				return "";
			}
			return text + "\"}";
		}

		private string GetDamageListJson(string name, Link link)
		{
			string text = ", { \"key\": \"damage\", \"value\": \"[ ";
			while (link != null)
			{
				if (link.type != "")
				{
					text = text + "'" + name + " (" + link.name + ") Damage',";
				}
				link = link.link;
			}
			if (text.EndsWith(","))
			{
				return text.Substring(0, text.Length - 2) + " ]\" }";
			}
			return "";
		}

		private string GetEffectListJson(string name, Link link)
		{
			string text = ", { \"key\": \"effect\", \"value\": \"[ ";
			while (link != null)
			{
				if (link.type == "")
				{
					text = text + "'" + name + " (" + link.name + ") Effect',";
				}
				link = link.link;
			}
			if (text.EndsWith(","))
			{
				return text.Substring(0, text.Length - 2) + " ]\" }";
			}
			return "";
		}

		private string[] ParseSave(string save)
		{
			string[] array = (save + "/AC").Split(new char[1] { '/' });
			array[0] = array[0].ToUpper().Replace("{", "[").Replace("}", "]");
			if (array[1] != "" && array[1].Length == 3)
			{
				array[1] = array[1].ToUpper() + " Save Roll";
			}
			else
			{
				array[1] = array[1].ToUpper();
			}
			return array;
		}
	}

	private static void Main(string[] args)
	{
		Character character = JsonConvert.DeserializeObject<Character>(File.ReadAllText(args[0]));
		character.Convert(args[1]);
	}
}

plugins/D20Editor.exe

Decompiled 2 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Newtonsoft.Json;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("D20Editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("D20Editor")]
[assembly: AssemblyCopyright("Copyright ©  2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("034c7165-3f97-4949-b2ad-66589d6719c3")]
[assembly: AssemblyFileVersion("2.5.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("2.5.0.0")]
namespace D20Editor
{
	public class EditorForm : Form
	{
		private Label[] skills;

		private CheckBox[] ex;

		private CheckBox[] pb;

		private string source = "";

		private static readonly Dictionary<string, string> SkillToAbility = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
		{
			{ "Athletics", "STR" },
			{ "Acrobatics", "DEX" },
			{ "Sleight of Hand", "DEX" },
			{ "Stealth", "DEX" },
			{ "Arcana", "INT" },
			{ "History", "INT" },
			{ "Investigation", "INT" },
			{ "Nature", "INT" },
			{ "Religion", "INT" },
			{ "Animal Handling", "WIS" },
			{ "Insight", "WIS" },
			{ "Medicine", "WIS" },
			{ "Perception", "WIS" },
			{ "Survival", "WIS" },
			{ "Deception", "CHA" },
			{ "Intimidation", "CHA" },
			{ "Performance", "CHA" },
			{ "Persuasion", "CHA" }
		};

		private List<string> exclusionList = new List<string>
		{
			"NPC", "LV", "EX", "PB", "PH", "Reaction", "ROLL", "AB", "ACB", "DB",
			"DCB", "HB", "SB", "SVB", "STR", "DEX", "CON", "INT", "WIS", "CHA",
			"STR Save", "DEX Save", "CON Save", "INT Save", "WIS Save", "CHA Save", "STR Save Roll", "DEX Save Roll", "CON Save Roll", "INT Save Roll",
			"WIS Save Roll", "CHA Save Roll", "EVASION_ZERO", "EVASION_HALF", "TOGGLE_SS", "SS", "TOGGLE_BLESS", "BLESS", "TOGGLE_GUIDE", "GUIDE",
			"TOGGLE_WM", "WM", "WM_ATK", "Grapple", "Fall 10'", "Fall 20'", "Fall 30'", "Fall 40'", "Fall 50'", "Fall 60'",
			"Fall 70'", "Fall 80'", "Fall 90'", "Fall 100'"
		};

		private List<string> stripFromFormulaList = new List<string>
		{
			"AB", "ACB", "DB", "DCB", "HB", "SB", "SVB", "EVASION_ZERO", "EVASION_HALF", "SS",
			"BLESS", "GUIDE", "ROLL", "WM", "WM_ATK"
		};

		private List<string> excludeByNameList = new List<string>
		{
			"NPC", "LV", "EX", "PB", "PH", "Reaction", "ROLL", "AB", "ACB", "DB",
			"DCB", "HB", "SB", "SVB", "STR", "DEX", "CON", "INT", "WIS", "CHA",
			"STR Save", "DEX Save", "CON Save", "INT Save", "WIS Save", "CHA Save", "STR Save Roll", "DEX Save Roll", "CON Save Roll", "INT Save Roll",
			"WIS Save Roll", "CHA Save Roll", "STR Save Roll (Regular)", "DEX Save Roll (Regular)", "CON Save Roll (Regular)", "INT Save Roll (Regular)", "WIS Save Roll (Regular)", "CHA Save Roll (Regular)", "EVASION_ZERO", "EVASION_HALF",
			"TOGGLE_SS", "SS", "TOGGLE_BLESS", "BLESS", "TOGGLE_GUIDE", "GUIDE", "Grapple", "TOGGLE_WM", "WM", "WM_ATK"
		};

		private IContainer components = null;

		private TextBox txtName;

		private Label lblname;

		private Label lblLevel;

		private TextBox txtLevel;

		private GroupBox fraCharacterSheet;

		private ListBox lstActions;

		private Label lblActions;

		private ListBox lstDamages;

		private Label lblDamage;

		private ListBox lstEffects;

		private Label lblEffects;

		private ListBox lstValues;

		private Label lblValues;

		private Label lblFeatures;

		private CheckBox chkHalfProf;

		private Label lblAbilityScores;

		private Label lblSkillsLegend;

		private Label lblSkills;

		private Label lblModCHA;

		private Label lblCHA;

		private TextBox txtCHA;

		private Label lblModWIS;

		private Label lblWIS;

		private TextBox txtWIS;

		private Label lblModINT;

		private Label lblINT;

		private TextBox txtINT;

		private Label lblModCON;

		private Label lblCON;

		private TextBox txtCON;

		private Label lblModDEX;

		private Label lblDEX;

		private TextBox txtDEX;

		private Label lblModSTR;

		private Label lblSTR;

		private TextBox txtSTR;

		private CheckBox chkBonusDC;

		private CheckBox chkBonusSkill;

		private CheckBox chkBonusSave;

		private CheckBox chkBonusAttack;

		private CheckBox chkBonusAC;

		private CheckBox chkEvasion;

		private CheckBox chkShieldSpell;

		private CheckBox chkGuidance;

		private CheckBox chkBless;

		private GroupBox framEdit;

		private Label lblPB;

		private ListBox lstEditType;

		private Label lblEditType;

		private Label lblEditEffects;

		private TextBox txtEditDamages;

		private Label lblEditDamage;

		private TextBox txtEditEffects;

		private TextBox txtEditOpposed;

		private Label lblOpposed;

		private TextBox txtEditFormula;

		private Label lblFormula;

		private TextBox txtEditName;

		private Label lblEditName;

		private Button btnAdd;

		private TextBox txtEditDamageType;

		private Label lblEditDamageType;

		private ListBox lstCustomSkills;

		private Label lblCustomSkills;

		private CheckBox chkEditIsToggle;

		private TextBox txtEditDisplayName;

		private Label lblDisplayName;

		private TextBox txtEditLocation;

		private Label lblLocation;

		private Button btnExport;

		private Button btnImport;

		private CheckBox chkPC;

		private CheckBox chkReaction;

		private CheckBox chkBonusDamage;

		private CheckBox chkBonusHeal;

		private CheckBox chkCHA;

		private CheckBox chkWIS;

		private CheckBox chkINT;

		private CheckBox chkCON;

		private CheckBox chkDEX;

		private CheckBox chkSTR;

		private Label lblHealing;

		private ListBox lstHealing;

		private CheckBox chkGrapple;

		private CheckBox chkMagicResistance;

		private GroupBox fraSkills;

		private GroupBox fraScores;

		private GroupBox fraFeatures;

		private GroupBox frmFeatures2;

		private Label lblHlafDamage;

		private CheckBox chkEditHalfDamage;

		private TextBox txtEditTargets;

		private Label lblTargets;

		private TextBox txtEditCritFormula;

		private Label lblEditCritFormula;

		private TextBox txtEditCritOn;

		private Label lblEditCritOn;

		private TextBox txtEditAnim;

		private Label lblEditAnim;

		private TextBox txtEditAnimOnce;

		private Label lblEditAnimOnce;

		private CheckBox chkWM;

		private CheckBox chkEditIsSpellToggle;

		private CheckBox chkEditPrivateToggle;

		private CheckBox chkEditSemiPrivateToggle;

		private CheckBox chkFallingDamage;

		private CheckBox chkCore;

		private Button btnExportCommon;

		private GroupBox fraLinkedContent;

		private TextBox txtLinkedContent;

		public EditorForm()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Expected O, but got Unknown
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Expected O, but got Unknown
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Expected O, but got Unknown
			string[] array = new string[18]
			{
				"Acrobatics", "Animal Handling", "Arcana", "Athletics", "Deception", "History", "Insight", "Intimidation", "Investigation", "Medicine",
				"Nature", "Perception", "Performance", "Persuasion", "Religion", "Sleight of Hand", "Stealth", "Survival"
			};
			exclusionList.AddRange(array);
			skills = (Label[])(object)new Label[array.Length];
			ex = (CheckBox[])(object)new CheckBox[array.Length];
			pb = (CheckBox[])(object)new CheckBox[array.Length];
			for (int i = 0; i < skills.Length; i++)
			{
				skills[i] = new Label();
				((Control)skills[i]).Text = array[i] ?? "";
				((Control)skills[i]).AutoSize = true;
				((Control)skills[i]).Location = new Point(5, 20 + i * 20);
				((Control)fraSkills).Controls.Add((Control)(object)skills[i]);
				pb[i] = new CheckBox();
				((Control)pb[i]).AutoSize = true;
				((Control)pb[i]).Location = new Point(111, 20 + i * 20);
				((Control)fraSkills).Controls.Add((Control)(object)pb[i]);
				ex[i] = new CheckBox();
				((Control)ex[i]).AutoSize = true;
				((Control)ex[i]).Location = new Point(135, 20 + i * 20);
				((Control)fraSkills).Controls.Add((Control)(object)ex[i]);
			}
			DisableAll();
		}

		private void txtSTR_TextChanged(object sender, EventArgs e)
		{
			try
			{
				int num = int.Parse(((Control)txtSTR).Text);
				if (num >= 10)
				{
					((Control)lblModSTR).Text = "(+" + (num - 10) / 2 + ")";
				}
				if (num < 10)
				{
					((Control)lblModSTR).Text = "(" + (num - 11) / 2 + ")";
				}
			}
			catch
			{
				((Control)lblModSTR).Text = "(+?)";
			}
		}

		private void txtDEX_TextChanged(object sender, EventArgs e)
		{
			try
			{
				int num = int.Parse(((Control)txtDEX).Text);
				if (num >= 10)
				{
					((Control)lblModDEX).Text = "(+" + (num - 10) / 2 + ")";
				}
				if (num < 10)
				{
					((Control)lblModDEX).Text = "(" + (num - 11) / 2 + ")";
				}
			}
			catch
			{
				((Control)lblModDEX).Text = "(+?)";
			}
		}

		private void txtCON_TextChanged(object sender, EventArgs e)
		{
			try
			{
				int num = int.Parse(((Control)txtCON).Text);
				if (num >= 10)
				{
					((Control)lblModCON).Text = "(+" + (num - 10) / 2 + ")";
				}
				if (num < 10)
				{
					((Control)lblModCON).Text = "(" + (num - 11) / 2 + ")";
				}
			}
			catch
			{
				((Control)lblModCON).Text = "(+?)";
			}
		}

		private void txtINT_TextChanged(object sender, EventArgs e)
		{
			try
			{
				int num = int.Parse(((Control)txtINT).Text);
				if (num >= 10)
				{
					((Control)lblModINT).Text = "(+" + (num - 10) / 2 + ")";
				}
				if (num < 10)
				{
					((Control)lblModINT).Text = "(" + (num - 11) / 2 + ")";
				}
			}
			catch
			{
				((Control)lblModINT).Text = "(+?)";
			}
		}

		private void txtWIS_TextChanged(object sender, EventArgs e)
		{
			try
			{
				int num = int.Parse(((Control)txtWIS).Text);
				if (num >= 10)
				{
					((Control)lblModWIS).Text = "(+" + (num - 10) / 2 + ")";
				}
				if (num < 10)
				{
					((Control)lblModWIS).Text = "(" + (num - 11) / 2 + ")";
				}
			}
			catch
			{
				((Control)lblModWIS).Text = "(+?)";
			}
		}

		private void txtCHA_TextChanged(object sender, EventArgs e)
		{
			try
			{
				int num = int.Parse(((Control)txtCHA).Text);
				if (num >= 10)
				{
					((Control)lblModCHA).Text = "(+" + (num - 10) / 2 + ")";
				}
				if (num < 10)
				{
					((Control)lblModCHA).Text = "(" + (num - 11) / 2 + ")";
				}
			}
			catch
			{
				((Control)lblModCHA).Text = "(+?)";
			}
		}

		private void txtLevel_TextChanged(object sender, EventArgs e)
		{
			try
			{
				int num = int.Parse(((Control)txtLevel).Text);
				((Control)lblPB).Text = "PB: +" + ((num - 1) / 4 + 2);
			}
			catch
			{
				((Control)lblPB).Text = "PB: +?";
			}
			RemoveFromList(lstValues, "LV");
			lstValues.Items.Add((object)("LV: " + ((Control)txtLevel).Text + ": : : " + false));
			RemoveFromList(lstValues, "PB");
			lstValues.Items.Add((object)("PB: " + ((Control)lblPB).Text.Substring(5) + ": : : " + false));
		}

		private void DisableAll()
		{
			((Control)txtEditName).Enabled = false;
			((Control)txtEditName).Text = "";
			((Control)txtEditFormula).Enabled = false;
			((Control)txtEditFormula).Text = "";
			((Control)txtEditOpposed).Enabled = false;
			((Control)txtEditOpposed).Text = "";
			((Control)txtEditEffects).Enabled = false;
			((Control)txtEditEffects).Text = "";
			((Control)txtEditDamages).Enabled = false;
			((Control)txtEditDamages).Text = "";
			((Control)txtEditDamageType).Enabled = false;
			((Control)txtEditDamageType).Text = "";
			((Control)txtEditCritOn).Enabled = false;
			((Control)txtEditCritOn).Text = "";
			((Control)txtEditCritFormula).Enabled = false;
			((Control)txtEditCritFormula).Text = "";
			((Control)txtEditTargets).Enabled = false;
			((Control)txtEditTargets).Text = "";
			((Control)chkEditHalfDamage).Enabled = false;
			chkEditHalfDamage.Checked = false;
			((Control)txtEditAnimOnce).Enabled = false;
			((Control)txtEditAnimOnce).Text = "";
			((Control)txtEditAnim).Enabled = false;
			((Control)txtEditAnim).Text = "";
			((Control)txtEditLocation).Enabled = false;
			((Control)txtEditLocation).Text = "";
			((Control)txtEditDisplayName).Enabled = false;
			((Control)txtEditDisplayName).Text = "";
			((Control)chkEditIsToggle).Enabled = false;
			chkEditIsToggle.Checked = false;
			chkEditIsSpellToggle.Checked = false;
			((Control)chkEditIsSpellToggle).Enabled = false;
			chkEditSemiPrivateToggle.Checked = false;
			((Control)chkEditSemiPrivateToggle).Enabled = false;
			chkEditPrivateToggle.Checked = false;
			((Control)chkEditPrivateToggle).Enabled = false;
		}

		private void lstEditType_SelectedIndexChanged(object sender, EventArgs e)
		{
			DisableAll();
			((Control)txtEditName).Enabled = true;
			((Control)txtEditFormula).Enabled = true;
			switch (((ListControl)lstEditType).SelectedIndex)
			{
			case 0:
				((Control)txtEditOpposed).Enabled = true;
				((Control)txtEditDamages).Enabled = true;
				((Control)txtEditEffects).Enabled = true;
				((Control)txtEditCritOn).Enabled = true;
				((Control)txtEditTargets).Enabled = true;
				((Control)chkEditHalfDamage).Enabled = true;
				((Control)txtEditAnimOnce).Enabled = true;
				((Control)txtEditAnim).Enabled = true;
				((Control)txtEditLocation).Enabled = true;
				((Control)chkEditIsSpellToggle).Enabled = true;
				((Control)chkEditSemiPrivateToggle).Enabled = true;
				((Control)chkEditPrivateToggle).Enabled = true;
				break;
			case 1:
				((Control)txtEditDamageType).Enabled = true;
				((Control)txtEditCritFormula).Enabled = true;
				((Control)txtEditLocation).Enabled = true;
				break;
			case 2:
				((Control)txtEditLocation).Enabled = true;
				break;
			case 3:
				((Control)txtEditLocation).Enabled = true;
				break;
			case 4:
				((Control)txtEditOpposed).Enabled = true;
				((Control)txtEditLocation).Enabled = true;
				((Control)chkEditSemiPrivateToggle).Enabled = true;
				((Control)chkEditPrivateToggle).Enabled = true;
				break;
			case 5:
				((Control)txtEditLocation).Enabled = true;
				((Control)txtEditDisplayName).Enabled = true;
				((Control)chkEditIsToggle).Enabled = true;
				break;
			}
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			//IL_0025: 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_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			if (((Control)txtEditName).Text.Trim() == "")
			{
				MessageBox.Show("Error: Entry Name Cannot Be Empty");
				return;
			}
			if (((Control)txtEditFormula).Text.Trim() == "")
			{
				MessageBox.Show("Error: Entry Formula Cannot Be Empty");
				return;
			}
			if (((ListControl)lstEditType).SelectedIndex == 0 && ((Control)txtEditDamages).Text.Trim() == "" && ((Control)txtEditEffects).Text.Trim() == "")
			{
				MessageBox.Show("Error: Attack Entry Must Have At Least One Damage Or One Effect");
				return;
			}
			if (((ListControl)lstEditType).SelectedIndex == 1 && ((Control)txtEditDamageType).Text.Trim() == "")
			{
				MessageBox.Show("Error: Damage Entry Must Have At Damage Type");
				return;
			}
			if (((Control)txtEditLocation).Text != "" && (!((Control)txtEditLocation).Text.StartsWith("/") || ((Control)txtEditLocation).Text.EndsWith("/")))
			{
				MessageBox.Show("Error: Menu Must Be Empty Or Start With A Forward Slash Character And Not End With A Forward Slash");
				return;
			}
			switch (((ListControl)lstEditType).SelectedIndex)
			{
			case 0:
				RemoveFromList(lstActions, ((Control)txtEditName).Text);
				lstActions.Items.Add((object)(((Control)txtEditName).Text + ": " + ((Control)txtEditFormula).Text + ": " + ((Control)txtEditOpposed).Text + ": " + ((Control)txtEditDamages).Text + ": " + ((Control)txtEditEffects).Text + ": " + ((Control)txtEditTargets).Text + ": " + chkEditHalfDamage.Checked + ": " + ((Control)txtEditCritOn).Text + ": " + ((Control)txtEditAnimOnce).Text + ": " + ((Control)txtEditAnim).Text + ": " + chkEditIsSpellToggle.Checked + ": " + chkEditPrivateToggle.Checked + ": " + chkEditSemiPrivateToggle.Checked + ": " + ((Control)txtEditLocation).Text + ": " + ((Control)txtEditDisplayName).Text + ": " + chkEditIsToggle.Checked));
				break;
			case 1:
				RemoveFromList(lstDamages, ((Control)txtEditName).Text);
				lstDamages.Items.Add((object)(((Control)txtEditName).Text + ": " + ((Control)txtEditFormula).Text + ": " + ((Control)txtEditDamageType).Text + ": " + ((Control)txtEditCritFormula).Text + ": " + ((Control)txtEditLocation).Text + ": " + ((Control)txtEditDisplayName).Text + ": " + chkEditIsToggle.Checked));
				break;
			case 2:
				RemoveFromList(lstEffects, ((Control)txtEditName).Text);
				lstEffects.Items.Add((object)(((Control)txtEditName).Text + ": " + ((Control)txtEditFormula).Text + ": " + ((Control)txtEditLocation).Text + ": " + ((Control)txtEditDisplayName).Text + ": " + chkEditIsToggle.Checked));
				break;
			case 3:
				RemoveFromList(lstHealing, ((Control)txtEditName).Text);
				lstHealing.Items.Add((object)(((Control)txtEditName).Text + ": " + ((Control)txtEditFormula).Text + ": " + ((Control)txtEditLocation).Text + ": " + ((Control)txtEditDisplayName).Text + ": " + chkEditIsToggle.Checked));
				break;
			case 4:
				RemoveFromList(lstCustomSkills, ((Control)txtEditName).Text);
				lstCustomSkills.Items.Add((object)(((Control)txtEditName).Text + ": " + ((Control)txtEditFormula).Text + ": " + ((Control)txtEditOpposed).Text + ": " + chkEditPrivateToggle.Checked + ": " + chkEditSemiPrivateToggle.Checked + ": " + ((Control)txtEditLocation).Text + ": " + ((Control)txtEditDisplayName).Text + ": " + chkEditIsToggle.Checked));
				break;
			case 5:
				RemoveFromList(lstValues, ((Control)txtEditName).Text);
				lstValues.Items.Add((object)(((Control)txtEditName).Text + ": " + ((Control)txtEditFormula).Text + ": " + ((Control)txtEditLocation).Text + ": " + ((Control)txtEditDisplayName).Text + ": " + chkEditIsToggle.Checked));
				break;
			}
		}

		private void lstActions_Click(object sender, EventArgs e)
		{
			try
			{
				string text = lstActions.Items[((ListControl)lstActions).SelectedIndex].ToString();
				((ListControl)lstEditType).SelectedIndex = 0;
				string[] array = text.Split(new string[1] { ": " }, StringSplitOptions.None);
				((Control)txtEditName).Text = array[0];
				((Control)txtEditFormula).Text = array[1];
				((Control)txtEditOpposed).Text = array[2];
				((Control)txtEditDamages).Text = array[3];
				((Control)txtEditEffects).Text = array[4];
				((Control)txtEditTargets).Text = array[5];
				chkEditHalfDamage.Checked = bool.Parse(array[6]);
				((Control)txtEditCritOn).Text = array[7];
				((Control)txtEditAnimOnce).Text = array[8];
				((Control)txtEditAnim).Text = array[9];
				chkEditIsSpellToggle.Checked = bool.Parse(array[10]);
				chkEditPrivateToggle.Checked = bool.Parse(array[11]);
				chkEditSemiPrivateToggle.Checked = bool.Parse(array[12]);
				((Control)txtEditLocation).Text = array[13];
				((Control)txtEditDisplayName).Text = array[14];
				chkEditIsToggle.Checked = bool.Parse(array[15]);
				((ListControl)lstCustomSkills).SelectedIndex = -1;
				((ListControl)lstDamages).SelectedIndex = -1;
				((ListControl)lstEffects).SelectedIndex = -1;
				((ListControl)lstHealing).SelectedIndex = -1;
				((ListControl)lstValues).SelectedIndex = -1;
			}
			catch
			{
			}
		}

		private void lstActions_DoubleClick(object sender, EventArgs e)
		{
			string text = lstActions.Items[((ListControl)lstActions).SelectedIndex].ToString();
			if (ConfirmAction("Delete '" + text.Substring(0, text.IndexOf(": ")) + "'?"))
			{
				lstActions.Items.RemoveAt(((ListControl)lstActions).SelectedIndex);
			}
		}

		private void lstDamages_Click(object sender, EventArgs e)
		{
			try
			{
				string text = lstDamages.Items[((ListControl)lstDamages).SelectedIndex].ToString();
				((ListControl)lstEditType).SelectedIndex = 1;
				string[] array = text.Split(new string[1] { ": " }, StringSplitOptions.None);
				((Control)txtEditName).Text = array[0];
				((Control)txtEditFormula).Text = array[1];
				((Control)txtEditDamageType).Text = array[2];
				((Control)txtEditCritFormula).Text = array[3];
				((Control)txtEditLocation).Text = array[4];
				((Control)txtEditDisplayName).Text = array[5];
				chkEditIsToggle.Checked = bool.Parse(array[6]);
				((ListControl)lstActions).SelectedIndex = -1;
				((ListControl)lstCustomSkills).SelectedIndex = -1;
				((ListControl)lstEffects).SelectedIndex = -1;
				((ListControl)lstHealing).SelectedIndex = -1;
				((ListControl)lstValues).SelectedIndex = -1;
			}
			catch
			{
			}
		}

		private void lstDamages_DoubleClick(object sender, EventArgs e)
		{
			string text = lstDamages.Items[((ListControl)lstDamages).SelectedIndex].ToString();
			if (ConfirmAction("Delete '" + text.Substring(0, text.IndexOf(": ")) + "'?"))
			{
				lstDamages.Items.RemoveAt(((ListControl)lstDamages).SelectedIndex);
			}
		}

		private void lstEffects_Click(object sender, EventArgs e)
		{
			try
			{
				string text = lstEffects.Items[((ListControl)lstEffects).SelectedIndex].ToString();
				((ListControl)lstEditType).SelectedIndex = 2;
				string[] array = text.Split(new string[1] { ": " }, StringSplitOptions.None);
				((Control)txtEditName).Text = array[0];
				((Control)txtEditFormula).Text = array[1];
				((Control)txtEditLocation).Text = array[2];
				((Control)txtEditDisplayName).Text = array[3];
				chkEditIsToggle.Checked = bool.Parse(array[4]);
				((ListControl)lstActions).SelectedIndex = -1;
				((ListControl)lstCustomSkills).SelectedIndex = -1;
				((ListControl)lstDamages).SelectedIndex = -1;
				((ListControl)lstHealing).SelectedIndex = -1;
				((ListControl)lstValues).SelectedIndex = -1;
			}
			catch
			{
			}
		}

		private void lstEffects_DoubleClick(object sender, EventArgs e)
		{
			string text = lstEffects.Items[((ListControl)lstEffects).SelectedIndex].ToString();
			if (ConfirmAction("Delete '" + text.Substring(0, text.IndexOf(": ")) + "'?"))
			{
				lstEffects.Items.RemoveAt(((ListControl)lstEffects).SelectedIndex);
			}
		}

		private void lstHealing_Click(object sender, EventArgs e)
		{
			try
			{
				string text = lstHealing.Items[((ListControl)lstHealing).SelectedIndex].ToString();
				((ListControl)lstEditType).SelectedIndex = 3;
				string[] array = text.Split(new string[1] { ": " }, StringSplitOptions.None);
				((Control)txtEditName).Text = array[0];
				((Control)txtEditFormula).Text = array[1];
				((Control)txtEditLocation).Text = array[2];
				((Control)txtEditDisplayName).Text = array[3];
				chkEditIsToggle.Checked = bool.Parse(array[4]);
				((ListControl)lstActions).SelectedIndex = -1;
				((ListControl)lstCustomSkills).SelectedIndex = -1;
				((ListControl)lstDamages).SelectedIndex = -1;
				((ListControl)lstEffects).SelectedIndex = -1;
				((ListControl)lstValues).SelectedIndex = -1;
			}
			catch
			{
			}
		}

		private void lstHealing_DoubleClick(object sender, EventArgs e)
		{
			string text = lstHealing.Items[((ListControl)lstHealing).SelectedIndex].ToString();
			if (ConfirmAction("Delete '" + text.Substring(0, text.IndexOf(": ")) + "'?"))
			{
				lstHealing.Items.RemoveAt(((ListControl)lstHealing).SelectedIndex);
			}
		}

		private void lstCustomSkills_Click(object sender, EventArgs e)
		{
			try
			{
				string text = lstCustomSkills.Items[((ListControl)lstCustomSkills).SelectedIndex].ToString();
				((ListControl)lstEditType).SelectedIndex = 4;
				string[] array = text.Split(new string[1] { ": " }, StringSplitOptions.None);
				((Control)txtEditName).Text = array[0];
				((Control)txtEditFormula).Text = array[1];
				((Control)txtEditOpposed).Text = array[2];
				chkEditPrivateToggle.Checked = bool.Parse(array[3]);
				chkEditSemiPrivateToggle.Checked = bool.Parse(array[4]);
				((Control)txtEditLocation).Text = array[5];
				((Control)txtEditDisplayName).Text = array[4];
				chkEditIsToggle.Checked = bool.Parse(array[5]);
				((ListControl)lstActions).SelectedIndex = -1;
				((ListControl)lstDamages).SelectedIndex = -1;
				((ListControl)lstEffects).SelectedIndex = -1;
				((ListControl)lstHealing).SelectedIndex = -1;
				((ListControl)lstValues).SelectedIndex = -1;
			}
			catch
			{
			}
		}

		private void lstCustomSkills_DoubleClick(object sender, EventArgs e)
		{
			string text = lstCustomSkills.Items[((ListControl)lstCustomSkills).SelectedIndex].ToString();
			if (ConfirmAction("Delete '" + text.Substring(0, text.IndexOf(": ")) + "'?"))
			{
				lstCustomSkills.Items.RemoveAt(((ListControl)lstCustomSkills).SelectedIndex);
			}
		}

		private void lstValues_Click(object sender, EventArgs e)
		{
			try
			{
				string text = lstValues.Items[((ListControl)lstValues).SelectedIndex].ToString();
				((ListControl)lstEditType).SelectedIndex = 5;
				string[] array = text.Split(new string[1] { ": " }, StringSplitOptions.None);
				((Control)txtEditName).Text = array[0];
				((Control)txtEditFormula).Text = array[1];
				((Control)txtEditLocation).Text = array[2];
				((Control)txtEditDisplayName).Text = array[3];
				chkEditIsToggle.Checked = bool.Parse(array[4]);
				((ListControl)lstActions).SelectedIndex = -1;
				((ListControl)lstCustomSkills).SelectedIndex = -1;
				((ListControl)lstDamages).SelectedIndex = -1;
				((ListControl)lstEffects).SelectedIndex = -1;
				((ListControl)lstHealing).SelectedIndex = -1;
			}
			catch
			{
			}
		}

		private void lstValues_DoubleClick(object sender, EventArgs e)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			string text = lstValues.Items[((ListControl)lstValues).SelectedIndex].ToString();
			if (!text.StartsWith("LV: ") && !text.StartsWith("PB: "))
			{
				if (ConfirmAction("Delete '" + text.Substring(0, text.IndexOf(": ")) + "'?"))
				{
					lstValues.Items.RemoveAt(((ListControl)lstValues).SelectedIndex);
				}
			}
			else
			{
				MessageBox.Show("Values 'LV' and 'PB' cannot be removed.\r\nThey are determine by the Level text box.");
			}
		}

		private void RemoveFromList(ListBox list, string name)
		{
			for (int i = 0; i < list.Items.Count; i++)
			{
				if (list.Items[i].ToString().StartsWith(name + ": "))
				{
					list.Items.RemoveAt(i);
					i--;
				}
			}
		}

		private void btnExportCommon_Click(object sender, EventArgs e)
		{
			btnExport_Click_Execute("common");
		}

		private void btnExport_Click(object sender, EventArgs e)
		{
			btnExport_Click_Execute("character");
		}

		private void btnExport_Click_Execute(string keyWord)
		{
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0389: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_09cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0481: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0862: Unknown result type (might be due to invalid IL or missing references)
			//IL_0985: Unknown result type (might be due to invalid IL or missing references)
			//IL_3802: Unknown result type (might be due to invalid IL or missing references)
			string text = SelectFolder();
			string text2 = ((Control)txtName).Text;
			string text3 = "";
			string text4 = "";
			string text5 = "";
			List<string> list = new List<string>();
			list.AddRange(excludeByNameList);
			list.Add("AC");
			int num = 0;
			foreach (string item in lstActions.Items)
			{
				string[] parts = item.Split(new string[1] { ": " }, StringSplitOptions.None);
				if (!((IEnumerable)lstValues.Items).Cast<string>().Any((string val) => val.StartsWith(parts[2] + ": ")) && !((IEnumerable)lstCustomSkills.Items).Cast<string>().Any((string cskill) => cskill.StartsWith(parts[2] + ": ")) && !skills.Any((Label bskill) => ((Control)bskill).Text.StartsWith(parts[2] + ": ")) && !list.Contains(parts[2]))
				{
					num++;
					MessageBox.Show("Action '" + parts[0] + "' contains Opposed entry '" + parts[2] + "'.\r\n\r\nProblem: Entry '" + parts[2] + "' does not exist.\r\n\r\nTip: Check the spelling, casing, look for extra spaces.");
				}
				string[] array = parts[3].Replace("[", "").Replace("]", "").Replace("'", "")
					.Split(new char[1] { ',' });
				foreach (string check in array)
				{
					if (!((IEnumerable)lstDamages.Items).Cast<string>().Any((string dmg) => dmg.StartsWith(check + ": ")) && check.Trim() != "")
					{
						num++;
						MessageBox.Show("Action '" + parts[0] + "' contains Damage entry '" + parts[3] + "'.\r\n\r\nProblem: Entry '" + parts[3] + "' does not exist.\r\n\r\nTip: Check the spelling, casing, look for extra spaces.");
					}
				}
				string[] array2 = parts[4].Replace("[", "").Replace("]", "").Replace("'", "")
					.Split(new char[1] { ',' });
				foreach (string check2 in array2)
				{
					if (!((IEnumerable)lstEffects.Items).Cast<string>().Any((string dmg) => dmg.StartsWith(check2 + ": ")) && check2.Trim() != "")
					{
						num++;
						MessageBox.Show("Action '" + parts[0] + "' contains Effect entry '" + parts[4] + "'.\r\n\r\nProblem: Entry '" + parts[4] + "' does not exist.\r\n\r\nTip: Check the spelling, casing, look for extra spaces.");
					}
				}
				foreach (Match item2 in Regex.Matches(parts[1], "\\[([^\\]]+)\\]"))
				{
					string entry = item2.Groups[1].Value;
					if (!((IEnumerable)lstValues.Items).Cast<string>().Any((string val) => val.StartsWith(entry + ":")) && !list.Contains(entry))
					{
						num++;
						MessageBox.Show("Action '" + parts[0] + "' contains Formula reference '" + entry + "'.\r\n\r\nProblem: Entry '" + entry + "' does not exist.\r\n\r\nTip: Check the spelling, casing, look for extra spaces.");
					}
				}
			}
			foreach (string item3 in lstDamages.Items)
			{
				string[] array3 = item3.Split(new string[1] { ": " }, StringSplitOptions.None);
				foreach (Match item4 in Regex.Matches(array3[1], "\\[([^\\]]+)\\]"))
				{
					string entry2 = item4.Groups[1].Value;
					if (!((IEnumerable)lstValues.Items).Cast<string>().Any((string val) => val.StartsWith(entry2 + ":")) && !list.Contains(entry2))
					{
						num++;
						MessageBox.Show("Damage '" + array3[0] + "' contains Formula reference '" + entry2 + "'.\r\n\r\nProblem: Entry '" + entry2 + "' does not exist.\r\n\r\nTip: Check the spelling, casing, look for extra spaces.");
					}
				}
				foreach (Match item5 in Regex.Matches(array3[2], "\\[([^\\]]+)\\]"))
				{
					string entry3 = item5.Groups[1].Value;
					if (!((IEnumerable)lstValues.Items).Cast<string>().Any((string val) => val.StartsWith(entry3 + ":")) && !list.Contains(entry3))
					{
						num++;
						MessageBox.Show("Damage '" + array3[0] + "' contains Damage Type reference '" + entry3 + "'.\r\n\r\nProblem: Entry '" + entry3 + "' does not exist.\r\n\r\nTip: Check the spelling, casing, look for extra spaces.");
					}
				}
			}
			foreach (string item6 in lstCustomSkills.Items)
			{
				string[] parts2 = item6.Split(new string[1] { ": " }, StringSplitOptions.None);
				foreach (Match item7 in Regex.Matches(parts2[1], "\\[([^\\]]+)\\]"))
				{
					string entry4 = item7.Groups[1].Value;
					if (!((IEnumerable)lstValues.Items).Cast<string>().Any((string val) => val.StartsWith(entry4 + ":")) && !list.Contains(entry4))
					{
						num++;
						MessageBox.Show("Skill '" + parts2[0] + "' contains Formula reference '" + entry4 + "'.\r\n\r\nProblem: Entry '" + entry4 + "' does not exist.\r\n\r\nTip: Check the spelling, casing, look for extra spaces.");
					}
				}
				if (parts2[2].Trim() != "" && !((IEnumerable)lstValues.Items).Cast<string>().Any((string val) => val.StartsWith(parts2[2] + ": ")) && !((IEnumerable)lstCustomSkills.Items).Cast<string>().Any((string cskill) => cskill.StartsWith(parts2[2] + ": ")) && !skills.Any((Label bskill) => ((Control)bskill).Text.StartsWith(parts2[2] + ": ")) && !list.Contains(parts2[2]))
				{
					num++;
					MessageBox.Show("Skill '" + parts2[0] + "' contains Opposed entry '" + parts2[2] + "'.\r\n\r\nProblem: Entry '" + parts2[2] + "' does not exist.\r\n\r\nTip: Check the spelling, casing, look for extra spaces.");
				}
			}
			if (num > 0)
			{
				MessageBox.Show(num + " Faults Found. Aborting Export.");
			}
			else
			{
				if (text == null)
				{
					return;
				}
				File.WriteAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "{\r\n");
				File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "  \"chainSources\": \"" + ((keyWord.ToUpper() != "CHARACTER") ? "Unsupported" : ((Control)txtLinkedContent).Text) + "\",\r\n");
				File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "  \"name\": \"" + text2 + "\",\r\n");
				File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "  \"specs\": [\r\n");
				if (chkCore.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"NPC\", \"formula\": \"" + !chkPC.Checked + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"LV\", \"formula\": \"" + ((((Control)txtLevel).Text.Trim() == "") ? "1" : ((Control)txtLevel).Text) + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"EX\", \"formula\": \"" + int.Parse(((Control)lblPB).Text.Replace("PB: ", "")) * 2 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"PB\", \"formula\": \"" + ((Control)lblPB).Text.Replace("PB: ", "").Replace("+", "") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
				}
				if (chkHalfProf.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"PH\", \"formula\": \"" + int.Parse(((Control)lblPB).Text.Replace("PB: ", "").Replace("+", "")) / 2 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
				}
				if (chkReaction.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Reaction\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Reaction\" }, { \"key\": \"toggle\" } ], \"menu\": null },\r\n");
				}
				if (chkCore.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"ROLL\", \"formula\": \"\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Roll (A/D)\" } ], \"menu\": null },\r\n");
				}
				if (chkBonusAttack.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"AB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Attack Bonus (AB)\" } ], \"menu\": null },\r\n");
				}
				if (chkBonusAC.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"ACB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic AC Bonus (ACB)\" } ], \"menu\": null },\r\n");
				}
				if (chkBonusDamage.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"DB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Damage Bonus (DB)\" } ], \"menu\": null },\r\n");
				}
				if (chkBonusDC.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"DCB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Spell DC Bonus (DCB)\" } ], \"menu\": null },\r\n");
				}
				if (chkBonusHeal.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"HB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Healing Bonus (HB)\" } ], \"menu\": null },\r\n");
				}
				if (chkBonusSkill.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"SB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Skill Bonus (SB)\" } ], \"menu\": null },\r\n");
				}
				if (chkBonusSave.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"SVB\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Generic Save Bonus (SVB)\" } ], \"menu\": null },\r\n");
				}
				foreach (string item8 in lstValues.Items)
				{
					string[] array4 = item8.Split(new string[1] { ": " }, StringSplitOptions.None);
					text4 = array4[1].Replace("1D20", "1D20[ROLL]");
					text5 = ((!(array4[2].Trim() == "")) ? array4[2] : (text5 = "/Info/" + array4[0]));
					string text10 = ((array4[3].Trim() == "") ? "" : (", { \"key\": \"edit\", \"value\": \"" + array4[3] + "\" }"));
					string text11 = ((array4[4].Trim() != "TRUE") ? "" : ", { \"key\": \"toggle\" }");
					if (!array4[0].Trim().StartsWith("LV") && !array4[0].Trim().StartsWith("PB") && !array4[0].Trim().StartsWith("EX") && !array4[0].Trim().StartsWith("NPC"))
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + array4[0] + "\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} " + text10 + text11 + "], \"menu\": null },\r\n");
					}
				}
				if (chkCore.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"STR\", \"formula\": \"" + ((Control)lblModSTR).Text.Replace("(", "").Replace(")", "").Replace("+", "") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + ((Control)txtSTR).Text + "\"} ], \"menu\": \"/Info/STR Modifier\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"DEX\", \"formula\": \"" + ((Control)lblModDEX).Text.Replace("(", "").Replace(")", "").Replace("+", "") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + ((Control)txtDEX).Text + "\"} ], \"menu\": \"/Info/DEX Modifier\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"CON\", \"formula\": \"" + ((Control)lblModCON).Text.Replace("(", "").Replace(")", "").Replace("+", "") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + ((Control)txtCON).Text + "\"} ], \"menu\": \"/Info/CON Modifier\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"INT\", \"formula\": \"" + ((Control)lblModINT).Text.Replace("(", "").Replace(")", "").Replace("+", "") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + ((Control)txtINT).Text + "\"} ], \"menu\": \"/Info/INT Modifier\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"WIS\", \"formula\": \"" + ((Control)lblModWIS).Text.Replace("(", "").Replace(")", "").Replace("+", "") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + ((Control)txtWIS).Text + "\"} ], \"menu\": \"/Info/WIS Modifier\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"CHA\", \"formula\": \"" + ((Control)lblModCHA).Text.Replace("(", "").Replace(")", "").Replace("+", "") + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"value\", \"value\": \"" + ((Control)txtCHA).Text + "\"} ], \"menu\": \"/Info/CHA Modifier\" },\r\n");
				}
				if (chkEvasion.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"EVASION_ZERO\", \"formula\": \"\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Evasion (* for Zero Damage)\" } ], \"menu\": null },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"EVASION_HALF\", \"formula\": \"\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Evasion (* for 1/2 Damage)\" } ], \"menu\": null },\r\n");
				}
				if (chkShieldSpell.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"TOGGLE_SS\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Shield Spell (SS)\" }, { \"key\": \"toggle\" } ], \"menu\": null },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"SS\", \"formula\": \"[TOGGLE_SS]*5\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" } ], \"menu\": null },\r\n");
				}
				if (chkBless.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"TOGGLE_BLESS\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Bless Spell (BLESS)\" }, { \"key\": \"toggle\" } ], \"menu\": null },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"BLESS\", \"formula\": \"[TOGGLE_BLESS]*1D4\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" } ], \"menu\": null },\r\n");
				}
				if (chkGuidance.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"TOGGLE_GUIDE\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"Guidance Cantrip (GUIDE)\" }, { \"key\": \"toggle\" } ], \"menu\": null },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"GUIDE\", \"formula\": \"[TOGGLE_GUIDE]*1D4\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" } ], \"menu\": null },\r\n");
				}
				if (chkWM.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"TOGGLE_WM\", \"formula\": \"0\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" }, { \"key\": \"edit\", \"value\": \"-5 ATK / +10 DMG (WM)\" }, { \"key\": \"toggle\" } ], \"menu\": null },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"WM_ATK\", \"formula\": \"[TOGGLE_WM]*5\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" } ], \"menu\": null },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"WM\", \"formula\": \"[TOGGLE_WM]*10\", \"extra\": [ { \"key\": \"type\", \"value\": \"value\" } ], \"menu\": null },\r\n");
				}
				if (chkCore.Checked)
				{
					text3 = "STR";
					text4 = "[" + text3 + "]";
					if (chkSTR.Checked)
					{
						text4 += "+[PB]";
					}
					if (chkBless.Checked)
					{
						text4 += "+[BLESS]";
					}
					if (chkBonusSave.Checked)
					{
						text4 += "+[SVB]";
					}
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
					if (!chkMagicResistance.Checked)
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					else
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20A+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll (Regular)\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					text3 = "DEX";
					text4 = "[" + text3 + "]";
					if (chkDEX.Checked)
					{
						text4 += "+[PB]";
					}
					if (chkBless.Checked)
					{
						text4 += "+[BLESS]";
					}
					if (chkBonusSave.Checked)
					{
						text4 += "+[SVB]";
					}
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
					if (!chkMagicResistance.Checked)
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					else
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20A+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll (Regular)\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					text3 = "CON";
					text4 = "[" + text3 + "]";
					if (chkCON.Checked)
					{
						text4 += "+[PB]";
					}
					if (chkBless.Checked)
					{
						text4 += "+[BLESS]";
					}
					if (chkBonusSave.Checked)
					{
						text4 += "+[SVB]";
					}
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
					if (!chkMagicResistance.Checked)
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					else
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20A+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll (Regular)\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					text3 = "INT";
					text4 = "[" + text3 + "]";
					if (chkINT.Checked)
					{
						text4 += "+[PB]";
					}
					if (chkBless.Checked)
					{
						text4 += "+[BLESS]";
					}
					if (chkBonusSave.Checked)
					{
						text4 += "+[SVB]";
					}
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
					if (!chkMagicResistance.Checked)
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					else
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20A+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll (Regular)\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					text3 = "WIS";
					text4 = "[" + text3 + "]";
					if (chkWIS.Checked)
					{
						text4 += "+[PB]";
					}
					if (chkBless.Checked)
					{
						text4 += "+[BLESS]";
					}
					if (chkBonusSave.Checked)
					{
						text4 += "+[SVB]";
					}
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
					if (!chkMagicResistance.Checked)
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					else
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20A+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll (Regular)\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					text3 = "CHA";
					text4 = "[" + text3 + "]";
					if (chkCHA.Checked)
					{
						text4 += "+[PB]";
					}
					if (chkBless.Checked)
					{
						text4 += "+[BLESS]";
					}
					if (chkBonusSave.Checked)
					{
						text4 += "+[SVB]";
					}
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": null },\r\n");
					if (!chkMagicResistance.Checked)
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					else
					{
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll\", \"formula\": \"1D20A+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + text3 + " Save Roll (Regular)\", \"formula\": \"1D20[ROLL]+[" + text3 + " Save]\", \"extra\": [ {\"key\": \"type\", \"value\": \"value\"} ], \"menu\": \"/Saves/" + text3 + "\" },\r\n");
					}
					for (int num4 = 0; num4 < skills.Length; num4++)
					{
						text4 = "1D20[ROLL]+[" + GetAbilityCode(((Control)skills[num4]).Text) + "]";
						if (ex[num4].Checked)
						{
							text4 += "+[EX]";
						}
						else if (pb[num4].Checked)
						{
							text4 += "+[PB]";
						}
						else if (chkHalfProf.Checked)
						{
							text4 += "+[PH]";
						}
						if (chkGuidance.Checked)
						{
							text4 += "+[GUIDE]";
						}
						if (chkBonusSkill.Checked)
						{
							text4 += "+[SB]";
						}
						string text12 = "";
						if (((Control)skills[num4]).Text == "Deception")
						{
							text12 = ", { \"key\": \"opposed\", \"value\": \"Insight\" }";
						}
						if (((Control)skills[num4]).Text == "Insight")
						{
							text12 = ", { \"key\": \"opposed\", \"value\": \"Deception\" }";
						}
						if (((Control)skills[num4]).Text == "Perception")
						{
							text12 = ", { \"key\": \"opposed\", \"value\": \"Stealth\" }";
						}
						if (((Control)skills[num4]).Text == "Stealth")
						{
							text12 = ", { \"key\": \"opposed\", \"value\": \"Perception\" }";
						}
						if (((Control)skills[num4]).Text == "Sleight Of Hand")
						{
							text12 = ", { \"key\": \"opposed\", \"value\": \"Perception\" }";
						}
						File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + ((Control)skills[num4]).Text + "\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"} " + text12 + "], \"menu\": \"/Skills/" + ((Control)skills[num4]).Text + "\" },\r\n");
					}
				}
				if (chkGrapple.Checked)
				{
					text4 = "1D20[ROLL]+[" + GetAbilityCode(((Control)skills[3]).Text) + "]";
					if (ex[3].Checked)
					{
						text4 += "+[EX]";
					}
					else if (pb[3].Checked)
					{
						text4 += "+[PB]";
					}
					else if (chkHalfProf.Checked)
					{
						text4 += "+[PH]";
					}
					if (chkGuidance.Checked)
					{
						text4 += "+[GUIDE]";
					}
					if (chkBonusSkill.Checked)
					{
						text4 += "+[SB]";
					}
					string text13 = "Athletics,Acrobatics";
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Grapple\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"}, {\"key\": \"opposed\", \"value\": \"" + text13 + "\"} ], \"menu\": \"/Skills/Grapple\" },\r\n");
				}
				foreach (string item9 in lstCustomSkills.Items)
				{
					string[] array5 = item9.Split(new string[1] { ": " }, StringSplitOptions.None);
					text4 = array5[1].Replace("1D20[ROLL]", "1D20").Replace("1D20", "1D20[ROLL]");
					if (chkGuidance.Checked)
					{
						text4 += "+[GUIDE]";
					}
					if (chkBonusSkill.Checked)
					{
						text4 += "+[SB]";
					}
					string text15 = array5[2];
					if (text15.Trim() != "")
					{
						text15 = ", { \"key\": \"opposed\", \"value\": \"" + text15 + "'\" }";
					}
					string text16 = ((!bool.Parse(array5[3])) ? "" : ", { \"key\": \"message\", \"value\": \"private\" }");
					string text17 = ((!bool.Parse(array5[4])) ? "" : ", { \"key\": \"message\", \"value\": \"semiprivate\" }");
					text5 = ((array5[5].Trim() == "") ? (text5 = "/Skills/" + array5[0]) : array5[5]);
					string text18 = ((array5[6].Trim() == "") ? "" : (", { \"key\": \"edit\", \"value\": \"" + array5[6] + "\" }"));
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + array5[0] + "\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"skill\"} " + text15 + text18 + text16 + text17 + "], \"menu\": \"" + text5 + "\" },\r\n");
				}
				foreach (string item10 in lstEffects.Items)
				{
					string[] array6 = item10.Split(new string[1] { ": " }, StringSplitOptions.None);
					text5 = ((array6[2].Trim() == "") ? (text5 = "/Effects/" + array6[0]) : array6[2]);
					string text20 = ((array6[3].Trim() == "") ? "" : (", { \"key\": \"edit\", \"value\": \"" + array6[3] + "\" }"));
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + array6[0] + "\", \"formula\": \"" + array6[1] + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"effect\" " + text20 + "} ], \"menu\": \"" + text5 + "\" },\r\n");
				}
				foreach (string item11 in lstDamages.Items)
				{
					string[] array7 = item11.Split(new string[1] { ": " }, StringSplitOptions.None);
					text4 = array7[1];
					if (chkWM.Checked)
					{
						text4 += "+[WM]";
					}
					string text22 = ((array7[3].Trim() == "") ? (", { \"key\": \"critFormula\", \"value\": \"" + array7[1] + "\" }") : (", { \"key\": \"critFormula\", \"value\": \"" + array7[3] + "\" }"));
					text5 = ((array7[4].Trim() == "") ? (text5 = "/Damages/" + array7[0]) : array7[4]);
					string text23 = ((array7[5].Trim() == "") ? "" : (", { \"key\": \"edit\", \"value\": \"" + array7[5] + "\" }"));
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + array7[0] + "\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"" + array7[2] + "\"}" + text22 + " ], \"menu\": \"" + text5 + "\" },\r\n");
				}
				if (chkFallingDamage.Checked)
				{
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Fall 10'\", \"formula\": \"1D6\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"bludgeoning\"} ], \"menu\": \"/Damages/Fall/10'\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Fall 20'\", \"formula\": \"2D6\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"bludgeoning\"} ], \"menu\": \"/Damages/Fall/20'\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Fall 30'\", \"formula\": \"3D6\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"bludgeoning\"} ], \"menu\": \"/Damages/Fall/30'\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Fall 40'\", \"formula\": \"4D6\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"bludgeoning\"} ], \"menu\": \"/Damages/Fall/40'\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Fall 50'\", \"formula\": \"5D6\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"bludgeoning\"} ], \"menu\": \"/Damages/Fall/50'\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Fall 60'\", \"formula\": \"6D6\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"bludgeoning\"} ], \"menu\": \"/Damages/Fall/60'\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Fall 70'\", \"formula\": \"7D6\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"bludgeoning\"} ], \"menu\": \"/Damages/Fall/70'\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Fall 80'\", \"formula\": \"8D6\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"bludgeoning\"} ], \"menu\": \"/Damages/Fall/80'\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Fall 90'\", \"formula\": \"9D6\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"bludgeoning\"} ], \"menu\": \"/Damages/Fall/90'\" },\r\n");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"Fall 100'\", \"formula\": \"10D6\", \"extra\": [ {\"key\": \"type\", \"value\": \"damage\"}, {\"key\": \"damageType\", \"value\": \"bludgeoning\"} ], \"menu\": \"/Damages/Fall/100'\" },\r\n");
				}
				foreach (string item12 in lstActions.Items)
				{
					string[] array8 = item12.Split(new string[1] { ": " }, StringSplitOptions.None);
					text4 = array8[1].Replace("1D20[ROLL]", "1D20").Replace("1D20", "1D20[ROLL]");
					if (text4.Contains("1D20"))
					{
						if (chkBless.Checked)
						{
							text4 += "+[BLESS]";
						}
						if (chkBonusAttack.Checked)
						{
							text4 += "+[AB]";
						}
						if (chkWM.Checked)
						{
							text4 += "-[WM_ATK]";
						}
					}
					else if (chkBonusDC.Checked)
					{
						text4 += "+[DCB]";
					}
					string text25 = (bool.Parse(array8[10]) ? "spell" : "attack");
					string text26 = array8[2];
					if (text26.Trim() != "")
					{
						text26 = ", { \"key\": \"opposed\", \"value\": \"" + text26 + "\" }";
					}
					string text27 = ((array8[3].Trim() == "") ? "" : (", { \"key\": \"damage\", \"value\": \"['" + array8[3].Replace(",", "','") + "']\" }"));
					string text28 = ((array8[4].Trim() == "") ? "" : (", { \"key\": \"effect\", \"value\": \"['" + array8[4].Replace(",", "','") + "']\" }"));
					string text29 = ((array8[5].Trim() == "") ? "" : (", { \"key\": \"targets\", \"value\": " + array8[5].Replace(",", "','") + " }"));
					string text30 = ((array8[6].Trim() == false.ToString()) ? "" : ", { \"key\": \"half\" }");
					string text31 = ((array8[7].Trim() == "") ? ", { \"key\": \"critOn\", \"value\": 20 }" : (", { \"key\": \"critOn\", \"value\": " + array8[7] + "}"));
					string text32 = ((array8[8].Trim() == "") ? "" : (", { \"key\": \"animOnce\", \"value\": \"" + array8[8] + "\" }"));
					string text33 = ((array8[9].Trim() == "") ? "" : (", { \"key\": \"anim\", \"value\": \"" + array8[9] + "\" }"));
					string text34 = ((array8[11].Trim() == false.ToString()) ? "" : ", { \"key\": \"message\", \"value\": \"private\" }");
					string text35 = ((array8[12].Trim() == false.ToString()) ? "" : ", { \"key\": \"message\", \"value\": \"semiprivate\" }");
					text5 = ((array8[13].Trim() == "") ? (text5 = "/Actions/" + array8[0]) : array8[13]);
					string text36 = ((array8[14].Trim() == "") ? "" : (", { \"key\": \"edit\", \"value\": \"" + array8[14] + "\" }"));
					string text37 = ((array8[15].Trim() == false.ToString()) ? "" : ", { \"key\": \"toggle\" }");
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + array8[0] + "\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"" + text25 + "\"} " + text26 + text27 + text28 + text29 + text30 + text31 + text36 + text37 + text32 + text33 + text34 + text35 + "], \"menu\": \"" + text5 + "\" },\r\n");
				}
				foreach (string item13 in lstHealing.Items)
				{
					string[] array9 = item13.Split(new string[1] { ": " }, StringSplitOptions.None);
					text4 = array9[1];
					if (chkBonusHeal.Checked)
					{
						text4 += "+[HB]";
					}
					text5 = ((array9[2].Trim() == "") ? (text5 = "/Heals/" + array9[0]) : array9[2]);
					string text39 = ((array9[3].Trim() == "") ? "" : (", { \"key\": \"edit\", \"value\": \"" + array9[3] + "\" }"));
					File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "    { \"name\": \"" + array9[0] + "\", \"formula\": \"" + text4 + "\", \"extra\": [ {\"key\": \"type\", \"value\": \"heal\"} " + text39 + "], \"menu\": \"" + text5 + "\" },\r\n");
				}
				string text40 = File.ReadAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json");
				text40 = text40.Substring(0, text40.Length - 3) + "\r\n";
				File.WriteAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", text40);
				File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "  ]\r\n");
				File.AppendAllText(text + "/org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json", "}\r\n");
				MessageBox.Show("Export Character To File 'org.lordashes.plugins.d20." + keyWord + "." + text2 + ".json'");
			}
		}

		public static string GetAbilityCode(string skill)
		{
			if (string.IsNullOrWhiteSpace(skill))
			{
				throw new ArgumentException("Skill name cannot be null or empty.", "skill");
			}
			if (SkillToAbility.TryGetValue(skill.Trim(), out var value))
			{
				return value;
			}
			throw new ArgumentException("Unknown D&D 5e skill: " + skill, "skill");
		}

		private void chkPC_CheckedChanged(object sender, EventArgs e)
		{
			RemoveFromList(lstValues, "NPC");
			lstValues.Items.Add((object)("NPC: " + !chkPC.Checked + ": : : " + false));
		}

		private void btnImport_Click(object sender, EventArgs e)
		{
			//IL_151f: Unknown result type (might be due to invalid IL or missing references)
			//IL_152c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				string path = SelectJsonFile();
				string text = File.ReadAllText(path);
				Characters.CharacterSpecs characterSpecs = JsonConvert.DeserializeObject<Characters.CharacterSpecs>(text);
				Characters.Spec spec = null;
				lstValues.Items.Clear();
				lstCustomSkills.Items.Clear();
				lstDamages.Items.Clear();
				lstEffects.Items.Clear();
				lstHealing.Items.Clear();
				lstActions.Items.Clear();
				((Control)txtName).Text = characterSpecs.name;
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "LV").FirstOrDefault();
				chkCore.Checked = spec != null;
				if (spec != null)
				{
					((Control)txtLevel).Text = spec.formula;
					txtLevel_TextChanged(null, null);
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "STR").FirstOrDefault();
				if (spec != null)
				{
					((Control)txtSTR).Text = spec.Extra("value");
					txtSTR_TextChanged(null, null);
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "DEX").FirstOrDefault();
				if (spec != null)
				{
					((Control)txtDEX).Text = spec.Extra("value");
					txtDEX_TextChanged(null, null);
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "CON").FirstOrDefault();
				if (spec != null)
				{
					((Control)txtCON).Text = spec.Extra("value");
					txtCON_TextChanged(null, null);
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "INT").FirstOrDefault();
				if (spec != null)
				{
					((Control)txtINT).Text = spec.Extra("value");
					txtINT_TextChanged(null, null);
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "WIS").FirstOrDefault();
				if (spec != null)
				{
					((Control)txtWIS).Text = spec.Extra("value");
					txtWIS_TextChanged(null, null);
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "CHA").FirstOrDefault();
				if (spec != null)
				{
					((Control)txtCHA).Text = spec.Extra("value");
					txtCHA_TextChanged(null, null);
				}
				((Control)txtLinkedContent).Text = ((characterSpecs.chainSource != null) ? characterSpecs.chainSource.ToString() : "");
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "STR SAVE").FirstOrDefault();
				if (spec != null && spec.formula.Contains("[PB]"))
				{
					chkSTR.Checked = true;
				}
				else
				{
					chkSTR.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "DEX SAVE").FirstOrDefault();
				if (spec != null && spec.formula.Contains("[PB]"))
				{
					chkDEX.Checked = true;
				}
				else
				{
					chkDEX.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "CON SAVE").FirstOrDefault();
				if (spec != null && spec.formula.Contains("[PB]"))
				{
					chkCON.Checked = true;
				}
				else
				{
					chkCON.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "INT SAVE").FirstOrDefault();
				if (spec != null && spec.formula.Contains("[PB]"))
				{
					chkINT.Checked = true;
				}
				else
				{
					chkINT.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "WIS SAVE").FirstOrDefault();
				if (spec != null && spec.formula.Contains("[PB]"))
				{
					chkWIS.Checked = true;
				}
				else
				{
					chkWIS.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "CHA SAVE").FirstOrDefault();
				if (spec != null && spec.formula.Contains("[PB]"))
				{
					chkCHA.Checked = true;
				}
				else
				{
					chkCHA.Checked = false;
				}
				int s;
				for (s = 0; s < skills.Length; s++)
				{
					spec = characterSpecs.specs.Where((Characters.Spec skill) => skill.name.ToUpper() == ((Control)skills[s]).Text.ToUpper()).FirstOrDefault();
					if (spec != null && spec.formula.Contains("[EX]"))
					{
						this.ex[s].Checked = true;
					}
					else
					{
						this.ex[s].Checked = false;
					}
					if (spec != null && spec.formula.Contains("[PB]"))
					{
						pb[s].Checked = true;
					}
					else
					{
						pb[s].Checked = false;
					}
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "REACTION").FirstOrDefault();
				if (spec != null)
				{
					chkReaction.Checked = true;
				}
				else
				{
					chkReaction.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "BLESS").FirstOrDefault();
				if (spec != null)
				{
					chkBless.Checked = true;
				}
				else
				{
					chkBless.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "GUIDE").FirstOrDefault();
				if (spec != null)
				{
					chkGuidance.Checked = true;
				}
				else
				{
					chkGuidance.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "SS").FirstOrDefault();
				if (spec != null)
				{
					chkShieldSpell.Checked = true;
				}
				else
				{
					chkShieldSpell.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "ACB").FirstOrDefault();
				if (spec != null)
				{
					chkBonusAC.Checked = true;
				}
				else
				{
					chkBonusAC.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name == "AB").FirstOrDefault();
				if (spec != null)
				{
					chkBonusAttack.Checked = true;
				}
				else
				{
					chkBonusAttack.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "DB").FirstOrDefault();
				if (spec != null)
				{
					chkBonusDamage.Checked = true;
				}
				else
				{
					chkBonusDamage.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "DCB").FirstOrDefault();
				if (spec != null)
				{
					chkBonusDC.Checked = true;
				}
				else
				{
					chkBonusDC.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "HB").FirstOrDefault();
				if (spec != null)
				{
					chkBonusHeal.Checked = true;
				}
				else
				{
					chkBonusHeal.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "SB").FirstOrDefault();
				if (spec != null)
				{
					chkBonusSkill.Checked = true;
				}
				else
				{
					chkBonusSkill.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "SVB").FirstOrDefault();
				if (spec != null)
				{
					chkBonusSave.Checked = true;
				}
				else
				{
					chkBonusSave.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "EVASION_ZERO").FirstOrDefault();
				if (spec != null)
				{
					chkEvasion.Checked = true;
				}
				else
				{
					chkEvasion.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "PH").FirstOrDefault();
				if (spec != null)
				{
					chkHalfProf.Checked = true;
				}
				else
				{
					chkHalfProf.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "WM").FirstOrDefault();
				if (spec != null)
				{
					chkWM.Checked = true;
				}
				else
				{
					chkWM.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "GRAPPLE").FirstOrDefault();
				if (spec != null)
				{
					chkGrapple.Checked = true;
				}
				else
				{
					chkGrapple.Checked = false;
				}
				spec = characterSpecs.specs.Where((Characters.Spec spec2) => spec2.name.ToUpper() == "FALL 10'").FirstOrDefault();
				if (spec != null)
				{
					chkFallingDamage.Checked = true;
				}
				else
				{
					chkFallingDamage.Checked = false;
				}
				for (int num = 0; num < characterSpecs.specs.Count; num++)
				{
					if (excludeByNameList.Contains<string>(characterSpecs.specs[num].name, StringComparer.OrdinalIgnoreCase))
					{
						characterSpecs.specs.RemoveAt(num);
						num--;
					}
				}
				for (int num2 = 0; num2 < characterSpecs.specs.Count; num2++)
				{
					foreach (string stripFromFormula in stripFromFormulaList)
					{
						characterSpecs.specs[num2].formula = characterSpecs.specs[num2].formula.Replace("+[" + stripFromFormula + "]", "").Replace("-[" + stripFromFormula + "]", "").Replace("[" + stripFromFormula + "]", "");
					}
				}
				foreach (Characters.Spec spec2 in characterSpecs.specs)
				{
					if (!exclusionList.Contains<string>(spec2.name, StringComparer.OrdinalIgnoreCase))
					{
						string text2 = spec2.Extra("type");
						string text3 = spec2.Extra("opposed");
						if (text3 == null)
						{
							text3 = "";
						}
						string text4 = spec2.Extra("damage");
						if (text4 == null)
						{
							text4 = "";
						}
						text4 = text4.Replace("[", "").Replace("]", "").Replace("'", "");
						string text5 = spec2.Extra("effect");
						if (text5 == null)
						{
							text5 = "";
						}
						text5 = text5.Replace("[", "").Replace("]", "").Replace("'", "");
						string text6 = spec2.Extra("critOn");
						string text7 = ((text6 != null) ? text6 : "20");
						string text8 = spec2.Extra("critFormula");
						string text9 = ((text8 != null) ? text8 : spec2.formula);
						string text10 = spec2.Extra("targets");
						if (text10 == null)
						{
							text10 = "";
						}
						string text11 = spec2.Extra("half");
						text11 = ((text11 != null) ? true.ToString() : false.ToString());
						string text12 = spec2.menu;
						if (text12 == null)
						{
							text12 = "";
						}
						string text13 = spec2.Extra("edit");
						if (text13 == null)
						{
							text13 = "";
						}
						string text14 = spec2.Extra("toggle");
						text14 = ((text14 != null) ? true.ToString() : false.ToString());
						string text15 = spec2.Extra("animOnce");
						string text16 = ((text15 != null) ? text15 : "");
						string text17 = spec2.Extra("anim");
						string text18 = ((text17 != null) ? text17 : "");
						string text19 = (text2.ToUpper() == "SPELL").ToString();
						string text20 = spec2.Extra("message");
						string text21 = ((text20 != null) ? text20 : "public");
						string text22 = (text21.ToUpper() == "PRIVATE").ToString();
						string text23 = (text21.ToUpper() == "SEMIPRIVATE").ToString();
						switch (text2)
						{
						case "attack":
						case "spell":
							lstActions.Items.Add((object)(spec2.name + ": " + spec2.formula + ": " + text3 + ": " + text4 + ": " + text5 + ": " + text10 + ": " + text11 + ": " + text7 + ": " + text16 + ": " + text18 + ": " + text19 + ": " + text22 + ": " + text23 + ": " + text12 + ": " + text13 + ": " + text14));
							break;
						case "damage":
							lstDamages.Items.Add((object)(spec2.name + ": " + spec2.formula + ": " + spec2.Extra("damageType") + ": " + text9 + ": " + text12 + ": " + text13 + ": " + text14));
							break;
						case "effect":
							lstEffects.Items.Add((object)(spec2.name + ": " + spec2.formula + ": " + text12 + ": " + text13 + ": " + text14));
							break;
						case "heal":
							lstHealing.Items.Add((object)(spec2.name + ": " + spec2.formula + ": " + text12 + ": " + text13 + ": " + text14));
							break;
						case "skill":
							lstCustomSkills.Items.Add((object)(spec2.name + ": " + spec2.formula + ": " + text3 + ": " + text22 + ": " + text23 + ": " + text12 + ": " + text13 + ": " + text14));
							break;
						case "value":
							lstValues.Items.Add((object)(spec2.name + ": " + spec2.formula + ": " + text12 + ": " + text13 + ": " + text14));
							break;
						}
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("Cannot find file 'org.lordashes.plugins.d20.character." + ((Control)txtName).Text + ".json'");
				MessageBox.Show(ex.Message);
			}
		}

		private string SelectJsonFile()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Invalid comparison between Unknown and I4
			OpenFileDialog val = new OpenFileDialog();
			try
			{
				((FileDialog)val).Title = "Open File";
				((FileDialog)val).Filter = "JSON Files (*.json)|*.json|All Files (*.*)|*.*";
				((FileDialog)val).FilterIndex = 1;
				val.Multiselect = false;
				try
				{
					((FileDialog)val).InitialDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
				}
				catch (Exception)
				{
				}
				if ((int)((CommonDialog)val).ShowDialog() == 1)
				{
					source = ((FileDialog)val).FileName;
					((Control)Form.ActiveForm).Text = "D20 Editor - " + source;
					return ((FileDialog)val).FileName;
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			return null;
		}

		private string SelectFolder()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Invalid comparison between Unknown and I4
			FolderBrowserDialog val = new FolderBrowserDialog();
			try
			{
				val.Description = "Select a folder to save files";
				val.ShowNewFolderButton = true;
				try
				{
					val.SelectedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
				}
				catch (Exception)
				{
				}
				if ((int)((CommonDialog)val).ShowDialog() == 1)
				{
					return val.SelectedPath;
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			return null;
		}

		private bool ConfirmAction(string message)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			DialogResult val = MessageBox.Show(message, "Confirm", (MessageBoxButtons)4, (MessageBoxIcon)32);
			return (int)val == 6;
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && components != null)
			{
				components.Dispose();
			}
			((Form)this).Dispose(disposing);
		}

		private void InitializeComponent()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Expected O, but got Unknown
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Expected O, but got Unknown
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Expected O, but got Unknown
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Expected O, but got Unknown
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Expected O, but got Unknown
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Expected O, but got Unknown
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Expected O, but got Unknown
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Expected O, but got Unknown
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Expected O, but got Unknown
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Expected O, but got Unknown
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Expected O, but got Unknown
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Expected O, but got Unknown
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Expected O, but got Unknown
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Expected O, but got Unknown
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Expected O, but got Unknown
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Expected O, but got Unknown
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Expected O, but got Unknown
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Expected O, but got Unknown
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Expected O, but got Unknown
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Expected O, but got Unknown
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Expected O, but got Unknown
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Expected O, but got Unknown
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Expected O, but got Unknown
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Expected O, but got Unknown
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0227: Expected O, but got Unknown
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Expected O, but got Unknown
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Expected O, but got Unknown
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Expected O, but got Unknown
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_0253: Expected O, but got Unknown
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Expected O, but got Unknown
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Expected O, but got Unknown
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Expected O, but got Unknown
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Expected O, but got Unknown
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Expected O, but got Unknown
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Expected O, but got Unknown
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Expected O, but got Unknown
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Expected O, but got Unknown
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Expected O, but got Unknown
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Expected O, but got Unknown
			//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Expected O, but got Unknown
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d7: Expected O, but got Unknown
			//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Expected O, but got Unknown
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ed: Expected O, but got Unknown
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Expected O, but got Unknown
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: Expected O, but got Unknown
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_030e: Expected O, but got Unknown
			//IL_030f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0319: Expected O, but got Unknown
			//IL_031a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0324: Expected O, but got Unknown
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_032f: Expected O, but got Unknown
			//IL_0330: Unknown result type (might be due to invalid IL or missing references)
			//IL_033a: Expected O, but got Unknown
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Expected O, but got Unknown
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_0350: Expected O, but got Unknown
			//IL_0351: Unknown result type (might be due to invalid IL or missing references)
			//IL_035b: Expected O, but got Unknown
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Expected O, but got Unknown
			//IL_0367: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Expected O, but got Unknown
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_037c: Expected O, but got Unknown
			//IL_037d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0387: Expected O, but got Unknown
			//IL_0388: Unknown result type (might be due to invalid IL or missing references)
			//IL_0392: Expected O, but got Unknown
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_039d: Expected O, but got Unknown
			//IL_039e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a8: Expected O, but got Unknown
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b3: Expected O, but got Unknown
			//IL_03b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03be: Expected O, but got Unknown
			//IL_03bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c9: Expected O, but got Unknown
			//IL_03ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d4: Expected O, but got Unknown
			//IL_03d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03df: Expected O, but got Unknown
			//IL_03e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ea: Expected O, but got Unknown
			//IL_03eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f5: Expected O, but got Unknown
			//IL_03f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0400: Expected O, but got Unknown
			//IL_0401: Unknown result type (might be due to invalid IL or missing references)
			//IL_040b: Expected O, but got Unknown
			//IL_040c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0416: Expected O, but got Unknown
			//IL_0417: Unknown result type (might be due to invalid IL or missing references)
			//IL_0421: Expected O, but got Unknown
			//IL_0422: Unknown result type (might be due to invalid IL or missing references)
			//IL_042c: Expected O, but got Unknown
			//IL_042d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0437: Expected O, but got Unknown
			//IL_0438: Unknown result type (might be due to invalid IL or missing references)
			//IL_0442: Expected O, but got Unknown
			//IL_0443: Unknown result type (might be due to invalid IL or missing references)
			//IL_044d: Expected O, but got Unknown
			//IL_044e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0458: Expected O, but got Unknown
			//IL_0459: Unknown result type (might be due to invalid IL or missing references)
			//IL_0463: Expected O, but got Unknown
			//IL_0464: Unknown result type (might be due to invalid IL or missing references)
			//IL_046e: Expected O, but got Unknown
			//IL_046f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0479: Expected O, but got Unknown
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0484: Expected O, but got Unknown
			//IL_0485: Unknown result type (might be due to invalid IL or missing references)
			//IL_048f: Expected O, but got Unknown
			//IL_0490: Unknown result type (might be due to invalid IL or missing references)
			//IL_049a: Expected O, but got Unknown
			//IL_049b: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a5: Expected O, but got Unknown
			//IL_04a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b0: Expected O, but got Unknown
			//IL_04b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bb: Expected O, but got Unknown
			//IL_0a3b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a45: Expected O, but got Unknown
			//IL_0ad9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ae3: Expected O, but got Unknown
			//IL_0b6b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b75: Expected O, but got Unknown
			//IL_0bfd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c07: Expected O, but got Unknown
			//IL_0c8f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c99: Expected O, but got Unknown
			//IL_1214: Unknown result type (might be due to invalid IL or missing references)
			//IL_121e: Expected O, but got Unknown
			//IL_1afd: Unknown result type (might be due to invalid IL or missing references)
			//IL_1b07: Expected O, but got Unknown
			//IL_1e69: Unknown result type (might be due to invalid IL or missing references)
			//IL_1e73: Expected O, but got Unknown
			//IL_1f83: Unknown result type (might be due to invalid IL or missing references)
			//IL_1f8d: Expected O, but got Unknown
			//IL_20ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_20b7: Expected O, but got Unknown
			//IL_21d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_21e1: Expected O, but got Unknown
			//IL_2345: Unknown result type (might be due to invalid IL or missing references)
			//IL_234f: Expected O, but got Unknown
			//IL_23cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_23d7: Expected O, but got Unknown
			//IL_2455: Unknown result type (might be due to invalid IL or missing references)
			//IL_245f: Expected O, but got Unknown
			//IL_24dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_24e7: Expected O, but got Unknown
			txtName = new TextBox();
			lblname = new Label();
			lblLevel = new Label();
			txtLevel = new TextBox();
			fraCharacterSheet = new GroupBox();
			frmFeatures2 = new GroupBox();
			chkWM = new CheckBox();
			chkHalfProf = new CheckBox();
			chkEvasion = new CheckBox();
			chkMagicResistance = new CheckBox();
			fraScores = new GroupBox();
			chkCHA = new CheckBox();
			chkWIS = new CheckBox();
			chkINT = new CheckBox();
			chkCON = new CheckBox();
			chkDEX = new CheckBox();
			chkSTR = new CheckBox();
			lblAbilityScores = new Label();
			lblModCHA = new Label();
			lblCHA = new Label();
			txtCHA = new TextBox();
			lblModWIS = new Label();
			lblWIS = new Label();
			txtWIS = new TextBox();
			lblModINT = new Label();
			lblINT = new Label();
			txtINT = new TextBox();
			lblModCON = new Label();
			lblCON = new Label();
			txtCON = new TextBox();
			lblModDEX = new Label();
			lblDEX = new Label();
			txtDEX = new TextBox();
			lblModSTR = new Label();
			lblSTR = new Label();
			txtSTR = new TextBox();
			chkGrapple = new CheckBox();
			lblHealing = new Label();
			lstHealing = new ListBox();
			chkBonusHeal = new CheckBox();
			chkBonusDamage = new CheckBox();
			chkReaction = new CheckBox();
			lstCustomSkills = new ListBox();
			lblCustomSkills = new Label();
			lstActions = new ListBox();
			lblActions = new Label();
			lstDamages = new ListBox();
			lblDamage = new Label();
			lstEffects = new ListBox();
			lblEffects = new Label();
			lstValues = new ListBox();
			lblValues = new Label();
			lblFeatures = new Label();
			lblSkillsLegend = new Label();
			lblSkills = new Label();
			chkBonusDC = new CheckBox();
			chkBonusSkill = new CheckBox();
			chkBonusSave = new CheckBox();
			chkBonusAttack = new CheckBox();
			chkBonusAC = new CheckBox();
			chkShieldSpell = new CheckBox();
			chkGuidance = new CheckBox();
			chkBless = new CheckBox();
			fraSkills = new GroupBox();
			fraFeatures = new GroupBox();
			chkCore = new CheckBox();
			chkFallingDamage = new CheckBox();
			framEdit = new GroupBox();
			chkEditPrivateToggle = new CheckBox();
			chkEditSemiPrivateToggle = new CheckBox();
			chkEditIsSpellToggle = new CheckBox();
			txtEditAnim = new TextBox();
			lblEditAnim = new Label();
			txtEditAnimOnce = new TextBox();
			lblEditAnimOnce = new Label();
			txtEditCritFormula = new TextBox();
			lblEditCritFormula = new Label();
			txtEditCritOn = new TextBox();
			lblEditCritOn = new Label();
			lblHlafDamage = new Label();
			chkEditHalfDamage = new CheckBox();
			txtEditTargets = new TextBox();
			lblTargets = new Label();
			chkEditIsToggle = new CheckBox();
			txtEditDisplayName = new TextBox();
			lblDisplayName = new Label();
			txtEditLocation = new TextBox();
			lblLocation = new Label();
			txtEditDamageType = new TextBox();
			lblEditDamageType = new Label();
			btnAdd = new Button();
			txtEditName = new TextBox();
			lblEditName = new Label();
			txtEditOpposed = new TextBox();
			lblOpposed = new Label();
			txtEditFormula = new TextBox();
			lblFormula = new Label();
			txtEditDamages = new TextBox();
			lblEditDamage = new Label();
			txtEditEffects = new TextBox();
			lblEditEffects = new Label();
			lstEditType = new ListBox();
			lblEditType = new Label();
			lblPB = new Label();
			btnExport = new Button();
			btnImport = new Button();
			chkPC = new CheckBox();
			btnExportCommon = new Button();
			fraLinkedContent = new GroupBox();
			txtLinkedContent = new TextBox();
			((Control)fraCharacterSheet).SuspendLayout();
			((Control)frmFeatures2).SuspendLayout();
			((Control)fraScores).SuspendLayout();
			((Control)fraFeatures).SuspendLayout();
			((Control)framEdit).SuspendLayout();
			((Control)fraLinkedContent).SuspendLayout();
			((Control)this).SuspendLayout();
			((Control)txtName).Location = new Point(56, 13);
			((Control)txtName).Name = "txtName";
			((Control)txtName).Size = new Size(133, 20);
			((Control)txtName).TabIndex = 1;
			((Control)lblname).AutoSize = true;
			((Control)lblname).Location = new Point(12, 17);
			((Control)lblname).Name = "lblname";
			((Control)lblname).Size = new Size(38, 13);
			((Control)lblname).TabIndex = 10;
			((Control)lblname).Text = "Name:";
			((Control)lblLevel).AutoSize = true;
			((Control)lblLevel).Location = new Point(208, 17);
			((Control)lblLevel).Name = "lblLevel";
			((Control)lblLevel).Size = new Size(36, 13);
			((Control)lblLevel).TabIndex = 12;
			((Control)lblLevel).Text = "Level:";
			((Control)txtLevel).Location = new Point(252, 13);
			((Control)txtLevel).Name = "txtLevel";
			((Control)txtLevel).Size = new Size(31, 20);
			((Contr

plugins/Newtonsoft.Json.dll

Decompiled 2 months 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/System.Linq.Dynamic.Core.dll

Decompiled 2 months ago
#define TRACE
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core.Config;
using System.Linq.Dynamic.Core.CustomTypeProviders;
using System.Linq.Dynamic.Core.Exceptions;
using System.Linq.Dynamic.Core.Extensions;
using System.Linq.Dynamic.Core.Parser;
using System.Linq.Dynamic.Core.Parser.SupportedMethods;
using System.Linq.Dynamic.Core.Parser.SupportedOperands;
using System.Linq.Dynamic.Core.Tokenizer;
using System.Linq.Dynamic.Core.TypeConverters;
using System.Linq.Dynamic.Core.Util;
using System.Linq.Dynamic.Core.Util.Cache;
using System.Linq.Dynamic.Core.Validation;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using AnyOfTypes;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("System.Linq.Dynamic.Core.SystemTextJson, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("System.Linq.Dynamic.Core.NewtonsoftJson, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("EntityFramework.DynamicLinq.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("EntityFramework.DynamicLinq.Tests.net452, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("System.Linq.Dynamic.Core.Tests.Net6, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("System.Linq.Dynamic.Core.Tests.Net5, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("System.Linq.Dynamic.Core.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001003daf4f4b7d160b1033de9a4a3275f4667a4558144296c3bb593aa0fd213dadf0ea4df5aa69e21763d409ada2a8f8925081bc2e81362be7916e22c624344309eba764edc4f8f84237ae053d2687ab3b888c9f4f3ff8a804bb5fee61e1ceadec97b08994580ef2df6bd7e077df4ad205c6d2bde479c512ab9be6ecc23c10694597")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("ZZZ Projects")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © ZZZ Projects")]
[assembly: AssemblyDescription("This is a .NETStandard / .NET Core port of the the Microsoft assembly for the .Net 4.0 Dynamic language functionality.")]
[assembly: AssemblyFileVersion("1.7.1.0")]
[assembly: AssemblyInformationalVersion("1.7.1+ed0a3ddf6f7d39c3becff1faf2f6c8cae7515b0a")]
[assembly: AssemblyProduct("System.Linq.Dynamic.Core")]
[assembly: AssemblyTitle("System.Linq.Dynamic.Core")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/zzzprojects/System.Linq.Dynamic.Core")]
[assembly: AssemblyVersion("1.7.1.0")]
[module: RefSafetyRules(11)]
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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace System
{
	internal static class StringExtensions
	{
		public static bool IsNullOrWhiteSpace(this string? value)
		{
			return string.IsNullOrWhiteSpace(value);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Reflection
{
	internal static class CustomIntrospectionExtensions
	{
		public static Type[] GetGenericTypeArguments(this TypeInfo typeInfo)
		{
			return typeInfo.GenericTypeArguments;
		}
	}
	internal static class CustomTypeBuilderExtensions
	{
		public static Type CreateType(this TypeBuilder tb)
		{
			return tb.CreateTypeInfo().AsType();
		}
	}
}
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
	{
		All = -1,
		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
	}
	[AttributeUsage(AttributeTargets.Parameter)]
	[DebuggerNonUserCode]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
}
namespace System.Linq.Expressions
{
	internal static class LambdaExpressionExtensions
	{
		public static Type GetReturnType(this LambdaExpression lambdaExpression)
		{
			return lambdaExpression.ReturnType;
		}
	}
}
namespace System.Linq.Dynamic.Core
{
	internal static class AssemblyBuilderFactory
	{
		public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)
		{
			return AssemblyBuilder.DefineDynamicAssembly(name, access);
		}
	}
	internal class DefaultAssemblyHelper : IAssemblyHelper
	{
		private readonly ParsingConfig _config = Check.NotNull(parsingConfig, "parsingConfig");

		public DefaultAssemblyHelper(ParsingConfig parsingConfig)
		{
		}

		public Assembly[] GetAssemblies()
		{
			List<Assembly> list = AppDomain.CurrentDomain.GetAssemblies().ToList();
			List<string> loadedPaths = new List<string>();
			foreach (Assembly item in list)
			{
				try
				{
					if (!item.IsDynamic)
					{
						loadedPaths.Add(item.Location);
					}
				}
				catch
				{
				}
			}
			if (!_config.LoadAdditionalAssembliesFromCurrentDomainBaseDirectory)
			{
				return list.ToArray();
			}
			string[] source;
			try
			{
				source = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
			}
			catch
			{
				source = Array.Empty<string>();
			}
			string[] array = source.Where((string referencedPath) => !loadedPaths.Contains<string>(referencedPath, StringComparer.InvariantCultureIgnoreCase)).ToArray();
			foreach (string assemblyFile in array)
			{
				try
				{
					list.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(assemblyFile)));
				}
				catch
				{
				}
			}
			return list.ToArray();
		}
	}
	public class DefaultQueryableAnalyzer : IQueryableAnalyzer
	{
		public bool SupportsLinqToObjects(IQueryable query, IQueryProvider? provider = null)
		{
			Check.NotNull(query, "query");
			provider = provider ?? query.Provider;
			Type type = provider.GetType();
			bool flag = type.GetTypeInfo().BaseType == typeof(EnumerableQuery);
			if (!flag)
			{
				if (type.Name.StartsWith("QueryTranslatorProvider"))
				{
					try
					{
						PropertyInfo property = type.GetProperty("OriginalProvider");
						if (property != null)
						{
							return property.GetValue(provider, null) is IQueryProvider provider2 && SupportsLinqToObjects(query, provider2);
						}
						return SupportsLinqToObjects(query);
					}
					catch
					{
						return false;
					}
				}
				if (type.Name.StartsWith("ExpandableQuery"))
				{
					try
					{
						PropertyInfo property2 = query.GetType().GetProperty("InnerQuery", BindingFlags.Instance | BindingFlags.NonPublic);
						if (property2 != null)
						{
							return property2.GetValue(query, null) is IQueryable query2 && SupportsLinqToObjects(query2, provider);
						}
						return SupportsLinqToObjects(query);
					}
					catch
					{
						return false;
					}
				}
			}
			return flag;
		}
	}
	public abstract class DynamicClass : DynamicObject
	{
		internal const string IndexerName = "System_Linq_Dynamic_Core_DynamicClass_Indexer";

		private Dictionary<string, object?>? _propertiesDictionary;

		private Dictionary<string, object?> Properties
		{
			get
			{
				if (_propertiesDictionary == null)
				{
					_propertiesDictionary = new Dictionary<string, object>();
					PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
					foreach (PropertyInfo propertyInfo in properties)
					{
						if (propertyInfo.GetIndexParameters().Length <= 0)
						{
							_propertiesDictionary.Add(propertyInfo.Name, propertyInfo.GetValue(this, null));
						}
					}
				}
				return _propertiesDictionary;
			}
		}

		[IndexerName("System_Linq_Dynamic_Core_DynamicClass_Indexer")]
		public object? this[string name]
		{
			get
			{
				if (!Properties.TryGetValue(name, out object value))
				{
					return null;
				}
				return value;
			}
			set
			{
				if (Properties.ContainsKey(name))
				{
					Properties[name] = value;
				}
				else
				{
					Properties.Add(name, value);
				}
			}
		}

		public T? GetDynamicPropertyValue<T>(string propertyName)
		{
			return (T)(GetType().GetProperty(propertyName)?.GetValue(this, null));
		}

		public object? GetDynamicPropertyValue(string propertyName)
		{
			return GetDynamicPropertyValue<object>(propertyName);
		}

		public void SetDynamicPropertyValue<T>(string propertyName, T value)
		{
			GetType().GetProperty(propertyName)?.SetValue(this, value, null);
		}

		public void SetDynamicPropertyValue(string propertyName, object value)
		{
			this.SetDynamicPropertyValue<object>(propertyName, value);
		}

		public bool ContainsProperty(string name)
		{
			return Properties.ContainsKey(name);
		}

		public override IEnumerable<string> GetDynamicMemberNames()
		{
			return Properties.Keys;
		}

		public override bool TryGetMember(GetMemberBinder binder, out object? result)
		{
			return Properties.TryGetValue(binder.Name, out result);
		}

		public override bool TrySetMember(SetMemberBinder binder, object? value)
		{
			string name = binder.Name;
			if (Properties.ContainsKey(name))
			{
				Properties[name] = value;
			}
			else
			{
				Properties.Add(name, value);
			}
			return true;
		}
	}
	public static class DynamicClassFactory
	{
		private const string DynamicAssemblyName = "System.Linq.Dynamic.Core.DynamicClasses, Version=1.0.0.0";

		private const string DynamicModuleName = "System.Linq.Dynamic.Core.DynamicClasses";

		private static readonly CustomAttributeBuilder CompilerGeneratedAttributeBuilder;

		private static readonly CustomAttributeBuilder DebuggerBrowsableAttributeBuilder;

		private static readonly CustomAttributeBuilder DebuggerHiddenAttributeBuilder;

		private static readonly ConstructorInfo ObjectCtor;

		private static readonly ConstructorInfo StringBuilderCtor;

		private static readonly MethodInfo StringBuilderAppendString;

		private static readonly MethodInfo StringBuilderAppendObject;

		private static readonly Type EqualityComparer;

		private static readonly ConcurrentDictionary<string, Type> GeneratedTypes;

		private static readonly ModuleBuilder ModuleBuilder;

		private static int _index;

		static DynamicClassFactory()
		{
			CompilerGeneratedAttributeBuilder = new CustomAttributeBuilder(typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes), Array.Empty<object>());
			DebuggerBrowsableAttributeBuilder = new CustomAttributeBuilder(typeof(DebuggerBrowsableAttribute).GetConstructor(new Type[1] { typeof(DebuggerBrowsableState) }), new object[1] { DebuggerBrowsableState.Never });
			DebuggerHiddenAttributeBuilder = new CustomAttributeBuilder(typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes), Array.Empty<object>());
			ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes);
			StringBuilderCtor = typeof(StringBuilder).GetConstructor(Type.EmptyTypes);
			StringBuilderAppendString = typeof(StringBuilder).GetMethod("Append", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(string) }, null);
			StringBuilderAppendObject = typeof(StringBuilder).GetMethod("Append", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(object) }, null);
			EqualityComparer = typeof(EqualityComparer<>);
			GeneratedTypes = new ConcurrentDictionary<string, Type>();
			_index = -1;
			ModuleBuilder = AssemblyBuilderFactory.DefineDynamicAssembly(new AssemblyName("System.Linq.Dynamic.Core.DynamicClasses, Version=1.0.0.0"), AssemblyBuilderAccess.RunAndCollect).DefineDynamicModule("System.Linq.Dynamic.Core.DynamicClasses");
		}

		public static Type CreateGenericComparerType(Type comparerGenericType, Type comparerType)
		{
			Check.NotNull(comparerGenericType, "comparerGenericType");
			Check.NotNull(comparerType, "comparerType");
			string text = comparerGenericType.FullName + "_" + comparerType.FullName;
			if (!GeneratedTypes.TryGetValue(text, out Type value))
			{
				lock (GeneratedTypes)
				{
					if (!GeneratedTypes.TryGetValue(text, out value))
					{
						MethodInfo method = comparerGenericType.GetMethod("Compare");
						MethodInfo method2 = typeof(IComparer).GetMethod("Compare");
						ConstructorInfo constructor = comparerType.GetConstructor(Type.EmptyTypes);
						Type cls = comparerGenericType.GetGenericArguments()[0];
						TypeBuilder typeBuilder = ModuleBuilder.DefineType(text, TypeAttributes.Public, typeof(object));
						typeBuilder.AddInterfaceImplementation(comparerGenericType);
						FieldBuilder field = typeBuilder.DefineField("_c", typeof(IComparer), FieldAttributes.Private | FieldAttributes.InitOnly);
						ILGenerator iLGenerator = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, Type.EmptyTypes).GetILGenerator();
						iLGenerator.Emit(OpCodes.Ldarg_0);
						iLGenerator.Emit(OpCodes.Call, ObjectCtor);
						iLGenerator.Emit(OpCodes.Ldarg_0);
						iLGenerator.Emit(OpCodes.Newobj, constructor);
						iLGenerator.Emit(OpCodes.Stfld, field);
						iLGenerator.Emit(OpCodes.Ret);
						ILGenerator iLGenerator2 = typeBuilder.DefineMethod(method.Name, method.Attributes & ~MethodAttributes.Abstract, method.CallingConvention, method.ReturnType, (from p in method.GetParameters()
							select p.ParameterType).ToArray()).GetILGenerator();
						iLGenerator2.Emit(OpCodes.Ldarg_0);
						iLGenerator2.Emit(OpCodes.Ldfld, field);
						iLGenerator2.Emit(OpCodes.Ldarg_1);
						iLGenerator2.Emit(OpCodes.Box, cls);
						iLGenerator2.Emit(OpCodes.Ldarg_2);
						iLGenerator2.Emit(OpCodes.Box, cls);
						iLGenerator2.Emit(OpCodes.Callvirt, method2);
						iLGenerator2.Emit(OpCodes.Ret);
						return GeneratedTypes.GetOrAdd(text, typeBuilder.CreateType());
					}
				}
			}
			return value;
		}

		public static Type CreateType(IList<DynamicProperty> properties, bool createParameterCtor = true)
		{
			IList<DynamicProperty> properties2 = properties;
			Check.HasNoNulls(properties2, "properties");
			string key = GenerateKey(properties2, createParameterCtor);
			if (!GeneratedTypes.TryGetValue(key, out Type value))
			{
				lock (GeneratedTypes)
				{
					return GeneratedTypes.GetOrAdd(key, (string _) => EmitType(properties2, createParameterCtor));
				}
			}
			return value;
		}

		public static DynamicClass CreateInstance(IList<DynamicPropertyWithValue> dynamicPropertiesWithValue, bool createParameterCtor = true)
		{
			DynamicClass dynamicClass = (DynamicClass)Activator.CreateInstance(CreateType(dynamicPropertiesWithValue.Cast<DynamicProperty>().ToArray(), createParameterCtor));
			foreach (DynamicPropertyWithValue item in dynamicPropertiesWithValue.Where((DynamicPropertyWithValue p) => p.Value != null))
			{
				dynamicClass.SetDynamicPropertyValue(item.Name, item.Value);
			}
			return dynamicClass;
		}

		private static Type EmitType(IList<DynamicProperty> properties, bool createParameterCtor)
		{
			int num = Interlocked.Increment(ref _index);
			string name = (properties.Any() ? $"<>f__AnonymousType{num}`{properties.Count}" : $"<>f__AnonymousType{num}");
			TypeBuilder typeBuilder = ModuleBuilder.DefineType(name, TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(DynamicClass));
			typeBuilder.SetCustomAttribute(CompilerGeneratedAttributeBuilder);
			FieldBuilder[] array = new FieldBuilder[properties.Count];
			for (int i = 0; i < properties.Count; i++)
			{
				string name2 = properties[i].Name;
				Type type = properties[i].Type;
				array[i] = typeBuilder.DefineField("<" + name2 + ">i__Field", type, FieldAttributes.Private | FieldAttributes.InitOnly);
				array[i].SetCustomAttribute(DebuggerBrowsableAttributeBuilder);
				PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name2, PropertyAttributes.None, CallingConventions.HasThis, type, Type.EmptyTypes);
				MethodBuilder methodBuilder = typeBuilder.DefineMethod("get_" + name2, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, CallingConventions.HasThis, type, null);
				methodBuilder.SetCustomAttribute(CompilerGeneratedAttributeBuilder);
				ILGenerator iLGenerator = methodBuilder.GetILGenerator();
				iLGenerator.Emit(OpCodes.Ldarg_0);
				iLGenerator.Emit(OpCodes.Ldfld, array[i]);
				iLGenerator.Emit(OpCodes.Ret);
				propertyBuilder.SetGetMethod(methodBuilder);
				MethodBuilder methodBuilder2 = typeBuilder.DefineMethod("set_" + name2, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, CallingConventions.HasThis, null, new Type[1] { type });
				methodBuilder2.SetCustomAttribute(CompilerGeneratedAttributeBuilder);
				methodBuilder2.DefineParameter(1, ParameterAttributes.In, properties[i].Name);
				ILGenerator iLGenerator2 = methodBuilder2.GetILGenerator();
				iLGenerator2.Emit(OpCodes.Ldarg_0);
				iLGenerator2.Emit(OpCodes.Ldarg_1);
				iLGenerator2.Emit(OpCodes.Stfld, array[i]);
				iLGenerator2.Emit(OpCodes.Ret);
				propertyBuilder.SetSetMethod(methodBuilder2);
			}
			MethodBuilder methodBuilder3 = typeBuilder.DefineMethod("ToString", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(string), Type.EmptyTypes);
			methodBuilder3.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
			ILGenerator iLGenerator3 = methodBuilder3.GetILGenerator();
			iLGenerator3.DeclareLocal(typeof(StringBuilder));
			iLGenerator3.Emit(OpCodes.Newobj, StringBuilderCtor);
			iLGenerator3.Emit(OpCodes.Stloc_0);
			MethodBuilder methodBuilder4 = typeBuilder.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(bool), new Type[1] { typeof(object) });
			methodBuilder4.DefineParameter(1, ParameterAttributes.In, "value");
			methodBuilder4.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
			ILGenerator iLGenerator4 = methodBuilder4.GetILGenerator();
			iLGenerator4.DeclareLocal(typeBuilder.AsType());
			iLGenerator4.Emit(OpCodes.Ldarg_1);
			iLGenerator4.Emit(OpCodes.Isinst, typeBuilder.AsType());
			iLGenerator4.Emit(OpCodes.Stloc_0);
			iLGenerator4.Emit(OpCodes.Ldloc_0);
			MethodBuilder methodBuilder5 = typeBuilder.DefineMethod("GetHashCode", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, CallingConventions.HasThis, typeof(int), Type.EmptyTypes);
			methodBuilder5.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
			ILGenerator iLGenerator5 = methodBuilder5.GetILGenerator();
			iLGenerator5.DeclareLocal(typeof(int));
			if (properties.Count == 0)
			{
				iLGenerator5.Emit(OpCodes.Ldc_I4_0);
			}
			else
			{
				int num2 = 0;
				for (int j = 0; j < properties.Count; j++)
				{
					num2 = num2 * -1521134295 + array[j].Name.GetHashCode();
				}
				iLGenerator5.Emit(OpCodes.Ldc_I4, num2);
			}
			Label label = iLGenerator4.DefineLabel();
			for (int k = 0; k < properties.Count; k++)
			{
				string name3 = properties[k].Name;
				Type type2 = properties[k].Type;
				Type type3 = EqualityComparer.MakeGenericType(type2);
				MethodInfo method = type3.GetMethod("get_Default", BindingFlags.Static | BindingFlags.Public);
				MethodInfo method2 = type3.GetMethod("Equals", BindingFlags.Instance | BindingFlags.Public, null, new Type[2] { type2, type2 }, null);
				iLGenerator4.Emit(OpCodes.Brfalse, label);
				iLGenerator4.Emit(OpCodes.Call, method);
				iLGenerator4.Emit(OpCodes.Ldarg_0);
				iLGenerator4.Emit(OpCodes.Ldfld, array[k]);
				iLGenerator4.Emit(OpCodes.Ldloc_0);
				iLGenerator4.Emit(OpCodes.Ldfld, array[k]);
				iLGenerator4.Emit(OpCodes.Callvirt, method2);
				MethodInfo method3 = type3.GetMethod("GetHashCode", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { type2 }, null);
				iLGenerator5.Emit(OpCodes.Stloc_0);
				iLGenerator5.Emit(OpCodes.Ldc_I4, -1521134295);
				iLGenerator5.Emit(OpCodes.Ldloc_0);
				iLGenerator5.Emit(OpCodes.Mul);
				iLGenerator5.Emit(OpCodes.Call, method);
				iLGenerator5.Emit(OpCodes.Ldarg_0);
				iLGenerator5.Emit(OpCodes.Ldfld, array[k]);
				iLGenerator5.Emit(OpCodes.Callvirt, method3);
				iLGenerator5.Emit(OpCodes.Add);
				iLGenerator3.Emit(OpCodes.Ldloc_0);
				iLGenerator3.Emit(OpCodes.Ldstr, (k == 0) ? ("{ " + name3 + " = ") : (", " + name3 + " = "));
				iLGenerator3.Emit(OpCodes.Callvirt, StringBuilderAppendString);
				iLGenerator3.Emit(OpCodes.Pop);
				iLGenerator3.Emit(OpCodes.Ldloc_0);
				iLGenerator3.Emit(OpCodes.Ldarg_0);
				iLGenerator3.Emit(OpCodes.Ldfld, array[k]);
				iLGenerator3.Emit(OpCodes.Box, properties[k].Type);
				iLGenerator3.Emit(OpCodes.Callvirt, StringBuilderAppendObject);
				iLGenerator3.Emit(OpCodes.Pop);
			}
			if (createParameterCtor && properties.Any())
			{
				ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, Type.EmptyTypes);
				constructorBuilder.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
				ILGenerator iLGenerator6 = constructorBuilder.GetILGenerator();
				iLGenerator6.Emit(OpCodes.Ldarg_0);
				iLGenerator6.Emit(OpCodes.Call, ObjectCtor);
				iLGenerator6.Emit(OpCodes.Ret);
				Type[] parameterTypes = properties.Select((DynamicProperty p) => p.Type).ToArray();
				ConstructorBuilder constructorBuilder2 = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, parameterTypes);
				constructorBuilder2.SetCustomAttribute(DebuggerHiddenAttributeBuilder);
				ILGenerator iLGenerator7 = constructorBuilder2.GetILGenerator();
				iLGenerator7.Emit(OpCodes.Ldarg_0);
				iLGenerator7.Emit(OpCodes.Call, ObjectCtor);
				for (int l = 0; l < properties.Count; l++)
				{
					constructorBuilder2.DefineParameter(l + 1, ParameterAttributes.None, properties[l].Name);
					iLGenerator7.Emit(OpCodes.Ldarg_0);
					if (l == 0)
					{
						iLGenerator7.Emit(OpCodes.Ldarg_1);
					}
					else if (l == 1)
					{
						iLGenerator7.Emit(OpCodes.Ldarg_2);
					}
					else if (l == 2)
					{
						iLGenerator7.Emit(OpCodes.Ldarg_3);
					}
					else if (l < 255)
					{
						iLGenerator7.Emit(OpCodes.Ldarg_S, (byte)(l + 1));
					}
					else
					{
						iLGenerator7.Emit(OpCodes.Ldarg, (short)(l + 1));
					}
					iLGenerator7.Emit(OpCodes.Stfld, array[l]);
				}
				iLGenerator7.Emit(OpCodes.Ret);
			}
			if (properties.Count == 0)
			{
				iLGenerator4.Emit(OpCodes.Ldnull);
				iLGenerator4.Emit(OpCodes.Ceq);
				iLGenerator4.Emit(OpCodes.Ldc_I4_0);
				iLGenerator4.Emit(OpCodes.Ceq);
			}
			else
			{
				iLGenerator4.Emit(OpCodes.Ret);
				iLGenerator4.MarkLabel(label);
				iLGenerator4.Emit(OpCodes.Ldc_I4_0);
			}
			iLGenerator4.Emit(OpCodes.Ret);
			iLGenerator5.Emit(OpCodes.Stloc_0);
			iLGenerator5.Emit(OpCodes.Ldloc_0);
			iLGenerator5.Emit(OpCodes.Ret);
			iLGenerator3.Emit(OpCodes.Ldloc_0);
			iLGenerator3.Emit(OpCodes.Ldstr, (properties.Count == 0) ? "{ }" : " }");
			iLGenerator3.Emit(OpCodes.Callvirt, StringBuilderAppendString);
			iLGenerator3.Emit(OpCodes.Pop);
			iLGenerator3.Emit(OpCodes.Ldloc_0);
			iLGenerator3.Emit(OpCodes.Callvirt, PredefinedMethodsHelper.ObjectToString);
			iLGenerator3.Emit(OpCodes.Ret);
			EmitEqualityOperators(typeBuilder, methodBuilder4);
			return typeBuilder.CreateType();
		}

		private static void EmitEqualityOperators(TypeBuilder typeBuilder, MethodBuilder equals)
		{
			MethodBuilder methodBuilder = typeBuilder.DefineMethod("op_Equality", MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName, typeof(bool), new Type[2]
			{
				typeBuilder.AsType(),
				typeBuilder.AsType()
			});
			ILGenerator iLGenerator = methodBuilder.GetILGenerator();
			Label label = iLGenerator.DefineLabel();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Brfalse_S, label);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Brfalse_S, label);
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Callvirt, equals);
			iLGenerator.Emit(OpCodes.Ret);
			iLGenerator.MarkLabel(label);
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Ldarg_1);
			iLGenerator.Emit(OpCodes.Call, typeof(object).GetMethod("ReferenceEquals"));
			iLGenerator.Emit(OpCodes.Ret);
			ILGenerator iLGenerator2 = typeBuilder.DefineMethod("op_Inequality", MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName, typeof(bool), new Type[2]
			{
				typeBuilder.AsType(),
				typeBuilder.AsType()
			}).GetILGenerator();
			iLGenerator2.Emit(OpCodes.Ldarg_0);
			iLGenerator2.Emit(OpCodes.Ldarg_1);
			iLGenerator2.Emit(OpCodes.Call, methodBuilder);
			iLGenerator2.Emit(OpCodes.Ldc_I4_0);
			iLGenerator2.Emit(OpCodes.Ceq);
			iLGenerator2.Emit(OpCodes.Ret);
		}

		private static string GenerateKey(IEnumerable<DynamicProperty> dynamicProperties, bool createParameterCtor)
		{
			return string.Join("|", dynamicProperties.Select((DynamicProperty p) => Escape(p.Name) + "~" + p.Type.FullName).ToArray()) + "_" + (createParameterCtor ? "c" : string.Empty);
		}

		private static string Escape(string str)
		{
			str = str.Replace("\\", "\\\\");
			str = str.Replace("|", "\\|");
			return str;
		}

		internal static void ClearGeneratedTypes()
		{
			lock (GeneratedTypes)
			{
				GeneratedTypes.Clear();
			}
		}
	}
	public static class DynamicEnumerableAsyncExtensions
	{
		private static readonly MethodInfo ToListAsyncGenericMethod;

		static DynamicEnumerableAsyncExtensions()
		{
			ToListAsyncGenericMethod = typeof(DynamicEnumerableAsyncExtensions).GetTypeInfo().GetDeclaredMethods("ToListAsync").First((MethodInfo x) => x.IsGenericMethod);
		}

		public static async Task<dynamic[]> ToDynamicArrayAsync(this IEnumerable source, Type type, CancellationToken cancellationToken = default(CancellationToken))
		{
			return (await Check.NotNull(source, "source").ToDynamicListAsync(Check.NotNull(type, "type"), cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray();
		}

		public static async Task<dynamic[]> ToDynamicArrayAsync(this IEnumerable source, CancellationToken cancellationToken = default(CancellationToken))
		{
			return (await ToListAsync<object>(Check.NotNull(source, "source"), cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray();
		}

		public static async Task<T[]> ToDynamicArrayAsync<T>(this IEnumerable source, CancellationToken cancellationToken = default(CancellationToken))
		{
			return (await ToListAsync<T>(Check.NotNull(source, "source"), cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray();
		}

		public static async Task<List<dynamic>> ToDynamicListAsync(this IEnumerable source, Type type, CancellationToken cancellationToken = default(CancellationToken))
		{
			Check.NotNull(source, "source");
			Check.NotNull(type, "type");
			Task task = (Task)ToListAsyncGenericMethod.MakeGenericMethod(type).Invoke(source, new object[2] { source, cancellationToken });
			await task.ConfigureAwait(continueOnCapturedContext: false);
			return ((IList)task.GetType().GetProperty("Result").GetValue(task)).Cast<object>().ToList();
		}

		public static Task<List<dynamic>> ToDynamicListAsync(this IEnumerable source, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ToListAsync<object>(Check.NotNull(source, "source"), cancellationToken);
		}

		public static Task<List<T>> ToDynamicListAsync<T>(this IEnumerable source, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ToListAsync<T>(Check.NotNull(source, "source"), cancellationToken);
		}

		private static async Task<List<T>> ToListAsync<T>(IEnumerable source, CancellationToken cancellationToken)
		{
			if (source is IEnumerable<T> source2)
			{
				return source2.ToList();
			}
			return source.Cast<T>().ToList();
		}
	}
	public static class DynamicEnumerableExtensions
	{
		private static readonly MethodInfo ToDynamicArrayGenericMethod;

		static DynamicEnumerableExtensions()
		{
			ToDynamicArrayGenericMethod = typeof(DynamicEnumerableExtensions).GetTypeInfo().GetDeclaredMethods("ToDynamicArray").First((MethodInfo x) => x.IsGenericMethod);
		}

		public static dynamic[] ToDynamicArray(this IEnumerable source)
		{
			return CastToArray<object>(Check.NotNull(source, "source"));
		}

		public static T[] ToDynamicArray<T>(this IEnumerable source)
		{
			return CastToArray<T>(Check.NotNull(source, "source"));
		}

		public static dynamic[] ToDynamicArray(this IEnumerable source, Type type)
		{
			Check.NotNull(source, "source");
			Check.NotNull(type, "type");
			return CastToArray<object>((IEnumerable)ToDynamicArrayGenericMethod.MakeGenericMethod(type).Invoke(source, new object[1] { source }));
		}

		public static List<dynamic> ToDynamicList(this IEnumerable source)
		{
			return CastToList<object>(Check.NotNull(source, "source"));
		}

		public static List<dynamic> ToDynamicList(this IEnumerable source, Type type)
		{
			return Check.NotNull(source, "source").ToDynamicArray(Check.NotNull(type, "type")).ToList();
		}

		public static List<T> ToDynamicList<T>(this IEnumerable source)
		{
			return CastToList<T>(Check.NotNull(source, "source"));
		}

		internal static T[] CastToArray<T>(IEnumerable source)
		{
			return source.Cast<T>().ToArray();
		}

		internal static List<T> CastToList<T>(IEnumerable source)
		{
			return source.Cast<T>().ToList();
		}
	}
	public static class DynamicExpressionParser
	{
		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, bool createParameterCtor, Type? resultType, string expression, params object?[] values)
		{
			Check.NotEmpty(expression, "expression");
			return Expression.Lambda(new ExpressionParser(new ParameterExpression[0], expression, values, parsingConfig).Parse(resultType, createParameterCtor));
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, Type? resultType, string expression, params object?[] values)
		{
			Check.NotEmpty(expression, "expression");
			ExpressionParser expressionParser = new ExpressionParser(new ParameterExpression[0], expression, values, parsingConfig);
			return Expression.Lambda(delegateType, expressionParser.Parse(resultType, createParameterCtor));
		}

		public static Expression<Func<TResult>> ParseLambda<TResult>(ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values)
		{
			return (Expression<Func<TResult>>)ParseLambda(parsingConfig, createParameterCtor, typeof(TResult), expression, values);
		}

		public static Expression<Func<TResult>> ParseLambda<TResult>(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			return (Expression<Func<TResult>>)ParseLambda(delegateType, parsingConfig, createParameterCtor, typeof(TResult), expression, values);
		}

		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, Type? resultType, string expression, params object?[]? values)
		{
			return ParseLambda(null, parsingConfig, createParameterCtor, parameters, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type? delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, Type? resultType, string expression, params object?[]? values)
		{
			Check.HasNoNulls(parameters, "parameters");
			Check.NotEmpty(expression, "expression");
			ExpressionParser expressionParser = new ExpressionParser(parameters, expression, values, parsingConfig);
			Expression expression2 = expressionParser.Parse(resultType, createParameterCtor);
			if (expression2 is LambdaExpression result)
			{
				return result;
			}
			if (parsingConfig != null && parsingConfig.RenameParameterExpression && parameters.Length == 1)
			{
				expression2 = new ParameterExpressionRenamer(expressionParser.LastLambdaItName).Rename(expression2, out ParameterExpression parameterExpression);
				if (!(delegateType == null))
				{
					return Expression.Lambda(delegateType, expression2, parameterExpression);
				}
				return Expression.Lambda(expression2, parameterExpression);
			}
			if (!(delegateType == null))
			{
				return Expression.Lambda(delegateType, expression2, parameters);
			}
			return Expression.Lambda(expression2, parameters);
		}

		public static Expression<Func<TResult>> ParseLambda<TResult>(ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, string expression, params object?[] values)
		{
			return (Expression<Func<TResult>>)ParseLambda(parsingConfig, createParameterCtor, parameters, typeof(TResult), expression, values);
		}

		public static Expression<Func<TResult>> ParseLambda<TResult>(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, ParameterExpression[] parameters, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			return (Expression<Func<TResult>>)ParseLambda(delegateType, parsingConfig, createParameterCtor, parameters, typeof(TResult), expression, values);
		}

		public static LambdaExpression ParseLambda(bool createParameterCtor, Type itType, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(itType, "itType");
			Check.NotEmpty(expression, "expression");
			return ParseLambda(createParameterCtor, new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(itType, string.Empty) }, resultType, expression, values);
		}

		public static Expression<Func<T, TResult>> ParseLambda<T, TResult>(ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values)
		{
			Check.NotEmpty(expression, "expression");
			return (Expression<Func<T, TResult>>)ParseLambda(parsingConfig, createParameterCtor, new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(typeof(T), string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, typeof(TResult), expression, values);
		}

		public static Expression<Func<T, TResult>> ParseLambda<T, TResult>(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			Check.NotEmpty(expression, "expression");
			return (Expression<Func<T, TResult>>)ParseLambda(delegateType, parsingConfig, createParameterCtor, new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(typeof(T), string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, typeof(TResult), expression, values);
		}

		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, Type? resultType, string expression, params object?[] values)
		{
			return ParseLambda(parsingConfig, createParameterCtor: true, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			return ParseLambda(delegateType, parsingConfig, createParameterCtor: true, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type? resultType, string expression, params object?[] values)
		{
			Check.NotEmpty(expression, "expression");
			return ParseLambda(null, createParameterCtor: true, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type itType, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(itType, "itType");
			return ParseLambda(createParameterCtor: true, itType, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, Type itType, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(itType, "itType");
			return ParseLambda(parsingConfig, createParameterCtor: true, itType, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, Type itType, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			Check.NotNull(itType, "itType");
			return ParseLambda(delegateType, parsingConfig, createParameterCtor: true, itType, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, bool createParameterCtor, Type itType, Type? resultType, string expression, params object?[]? values)
		{
			Check.NotNull(itType, "itType");
			Check.NotEmpty(expression, "expression");
			return ParseLambda(parsingConfig, createParameterCtor, new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(itType, string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, bool createParameterCtor, Type itType, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			Check.NotNull(itType, "itType");
			Check.NotEmpty(expression, "expression");
			return ParseLambda(delegateType, parsingConfig, createParameterCtor, new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(itType, string.Empty, parsingConfig?.RenameEmptyParameterExpressionNames ?? false) }, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values)
		{
			return ParseLambda(null, createParameterCtor: true, parameters, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			return ParseLambda(delegateType, null, createParameterCtor: true, parameters, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(ParsingConfig? parsingConfig, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values)
		{
			return ParseLambda(parsingConfig, createParameterCtor: true, parameters, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(Type delegateType, ParsingConfig? parsingConfig, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values)
		{
			Check.NotNull(delegateType, "delegateType");
			return ParseLambda(delegateType, parsingConfig, createParameterCtor: true, parameters, resultType, expression, values);
		}

		public static LambdaExpression ParseLambda(bool createParameterCtor, ParameterExpression[] parameters, Type? resultType, string expression, params object?[] values)
		{
			return ParseLambda(null, createParameterCtor, parameters, resultType, expression, values);
		}
	}
	internal class DynamicGetMemberBinder : GetMemberBinder
	{
		private static readonly MethodInfo DynamicGetMemberMethod = typeof(DynamicGetMemberBinder).GetMethod("GetDynamicMember");

		private readonly ConcurrentDictionary<Tuple<Type, string, bool>, DynamicMetaObject> _metaObjectCache = new ConcurrentDictionary<Tuple<Type, string, bool>, DynamicMetaObject>();

		internal DynamicGetMemberBinder(string name, ParsingConfig? config)
			: base(name, config == null || !config.IsCaseSensitive)
		{
		}

		public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject? errorSuggestion)
		{
			DynamicMetaObject target2 = target;
			MethodCallExpression methodCallExpression = Expression.Call(DynamicGetMemberMethod, target2.Expression, Expression.Constant(base.Name), Expression.Constant(base.IgnoreCase));
			if (target2.Value is IDynamicMetaObjectProvider)
			{
				Tuple<Type, string, bool> key = new Tuple<Type, string, bool>(target2.LimitType, base.Name, base.IgnoreCase);
				return _metaObjectCache.GetOrAdd(key, delegate
				{
					BindingRestrictions typeRestriction = BindingRestrictions.GetTypeRestriction(target2.Expression, target2.LimitType);
					return new DynamicMetaObject(methodCallExpression, typeRestriction, target2.Value);
				});
			}
			return DynamicMetaObject.Create(target2.Value, methodCallExpression);
		}

		public static object? GetDynamicMember(object value, string name, bool ignoreCase)
		{
			if (value == null)
			{
				throw new InvalidOperationException();
			}
			if (value is IDictionary<string, object> dictionary)
			{
				return dictionary[name];
			}
			if (value is IDictionary dictionary2)
			{
				return dictionary2[name];
			}
			BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
			if (ignoreCase)
			{
				bindingFlags |= BindingFlags.IgnoreCase;
			}
			Type type = value.GetType();
			PropertyInfo? property = type.GetProperty(name, bindingFlags);
			if (property == null)
			{
				throw new InvalidOperationException($"Unable to find property '{name}' on type '{type}'.");
			}
			return property.GetValue(value, null);
		}
	}
	internal struct DynamicOrdering
	{
		public Expression Selector { get; }

		public bool Ascending { get; }

		public string MethodName { get; }

		public DynamicOrdering(Expression selector, bool ascending, string methodName)
		{
			Selector = selector;
			Ascending = ascending;
			MethodName = methodName;
		}
	}
	public class DynamicProperty
	{
		public string Name { get; }

		public Type Type { get; }

		public DynamicProperty(string name, Type type)
		{
			Name = name;
			Type = type;
		}
	}
	public class DynamicPropertyWithValue : DynamicProperty
	{
		public object? Value { get; }

		public DynamicPropertyWithValue(string name, object? value)
			: base(name, value?.GetType() ?? typeof(object))
		{
			Value = value;
		}
	}
	public static class DynamicQueryableExtensions
	{
		[CompilerGenerated]
		private sealed class <AsDynamicEnumerable>d__16 : IEnumerable<object>, IEnumerable, IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			private int <>l__initialThreadId;

			private IQueryable source;

			public IQueryable <>3__source;

			private IEnumerator <>7__wrap1;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <AsDynamicEnumerable>d__16(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || num == 1)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<>7__wrap1 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				try
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<>7__wrap1 = source.GetEnumerator();
						<>1__state = -3;
						break;
					case 1:
						<>1__state = -3;
						break;
					}
					if (<>7__wrap1.MoveNext())
					{
						object current = <>7__wrap1.Current;
						<>2__current = current;
						<>1__state = 1;
						return true;
					}
					<>m__Finally1();
					<>7__wrap1 = null;
					return false;
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				if (<>7__wrap1 is IDisposable disposable)
				{
					disposable.Dispose();
				}
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<dynamic> IEnumerable<object>.GetEnumerator()
			{
				<AsDynamicEnumerable>d__16 <AsDynamicEnumerable>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<AsDynamicEnumerable>d__ = this;
				}
				else
				{
					<AsDynamicEnumerable>d__ = new <AsDynamicEnumerable>d__16(0);
				}
				<AsDynamicEnumerable>d__.source = <>3__source;
				return <AsDynamicEnumerable>d__;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<object>)this).GetEnumerator();
			}
		}

		private static readonly TraceSource TraceSource = new TraceSource("DynamicQueryableExtensions");

		private static readonly MethodInfo _AllPredicate = QueryableMethodFinder.GetMethod("All", 1);

		private static readonly MethodInfo _any = QueryableMethodFinder.GetMethod("Any");

		private static readonly MethodInfo _anyPredicate = QueryableMethodFinder.GetMethod("Any", 1);

		private static readonly MethodInfo _cast = QueryableMethodFinder.GetGenericMethod("Cast");

		private static readonly MethodInfo _count = QueryableMethodFinder.GetMethod("Count");

		private static readonly MethodInfo _countPredicate = QueryableMethodFinder.GetMethod("Count", 1);

		private static readonly MethodInfo _defaultIfEmpty = QueryableMethodFinder.GetMethod("DefaultIfEmpty");

		private static readonly MethodInfo _defaultIfEmptyWithParam = QueryableMethodFinder.GetMethod("DefaultIfEmpty", 1);

		private static readonly MethodInfo _distinct = QueryableMethodFinder.GetMethod("Distinct");

		private static readonly MethodInfo _first = QueryableMethodFinder.GetMethod("First");

		private static readonly MethodInfo _firstPredicate = QueryableMethodFinder.GetMethod("First", 1);

		private static readonly MethodInfo _firstOrDefault = QueryableMethodFinder.GetMethod("FirstOrDefault");

		private static readonly MethodInfo _firstOrDefaultPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("FirstOrDefault");

		private static readonly MethodInfo _last = QueryableMethodFinder.GetMethod("Last");

		private static readonly MethodInfo _lastPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("Last");

		private static readonly MethodInfo _lastDefault = QueryableMethodFinder.GetMethod("LastOrDefault");

		private static readonly MethodInfo _lastDefaultPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("LastOrDefault");

		private static readonly MethodInfo _longCount = QueryableMethodFinder.GetMethod("LongCount");

		private static readonly MethodInfo _longCountPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("LongCount");

		private static readonly MethodInfo _max = QueryableMethodFinder.GetMethod("Max");

		private static readonly MethodInfo _maxPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("Max");

		private static readonly MethodInfo _min = QueryableMethodFinder.GetMethod("Min");

		private static readonly MethodInfo _minPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("Min");

		private static readonly MethodInfo _ofType = QueryableMethodFinder.GetGenericMethod("OfType");

		private static readonly MethodInfo _singlePredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("Single");

		private static readonly MethodInfo _singleDefaultPredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("SingleOrDefault");

		private static readonly MethodInfo _skip = QueryableMethodFinder.GetMethod("Skip", 1);

		private static readonly MethodInfo _skipWhilePredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("SkipWhile");

		private static readonly MethodInfo _take = QueryableMethodFinder.GetMethodWithIntParameter("Take");

		private static readonly MethodInfo _takeWhilePredicate = QueryableMethodFinder.GetMethodWithExpressionParameter("TakeWhile");

		private static Expression OptimizeExpression(Expression expression)
		{
			if (ExtensibilityPoint.QueryOptimizer != null)
			{
				Expression expression2 = ExtensibilityPoint.QueryOptimizer(expression);
				if (expression2 != expression)
				{
					TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Expression before : {0}", expression);
					TraceSource.TraceEvent(TraceEventType.Verbose, 0, "Expression after  : {0}", expression2);
				}
				return expression2;
			}
			return expression;
		}

		public static object Aggregate(this IQueryable source, string function, string member)
		{
			string function2 = function;
			Check.NotNull(source, "source");
			Check.NotEmpty(function2, "function");
			Check.NotEmpty(member, "member");
			PropertyInfo property = source.ElementType.GetProperty(member);
			ParameterExpression parameterExpression = ParameterExpressionHelper.CreateParameterExpression(source.ElementType, "s");
			Expression expression = Expression.Lambda(Expression.MakeMemberAccess(parameterExpression, property), parameterExpression);
			MethodInfo[] source2 = (from x in typeof(Queryable).GetMethods()
				where x.Name == function2 && x.IsGenericMethod
				select x).ToArray();
			MethodInfo methodInfo = source2.SingleOrDefault(delegate(MethodInfo m)
			{
				ParameterInfo parameterInfo = m.GetParameters().LastOrDefault();
				return parameterInfo != null && TypeHelper.GetUnderlyingType(parameterInfo.ParameterType) == property.PropertyType;
			});
			if (methodInfo != null)
			{
				return source.Provider.Execute(Expression.Call(null, methodInfo.MakeGenericMethod(source.ElementType), new Expression[2]
				{
					source.Expression,
					Expression.Quote(expression)
				}));
			}
			methodInfo = source2.SingleOrDefault((MethodInfo m) => m.Name == function2 && m.GetGenericArguments().Length == 2);
			return source.Provider.Execute(Expression.Call(null, methodInfo.MakeGenericMethod(source.ElementType, property.PropertyType), new Expression[2]
			{
				source.Expression,
				Expression.Quote(expression)
			}));
		}

		public static bool All(this IQueryable source, string predicate, params object?[] args)
		{
			return source.All(ParsingConfig.Default, predicate, args);
		}

		public static bool All(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute<bool>(_AllPredicate, source, Expression.Quote(expression));
		}

		public static bool Any(this IQueryable source)
		{
			return Execute<bool>(_any, Check.NotNull(source, "source"));
		}

		public static bool Any(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute<bool>(_anyPredicate, source, expression);
		}

		public static bool Any(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Any(ParsingConfig.Default, predicate, args);
		}

		public static bool Any(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			Check.NotNull(lambda, "lambda");
			return Execute<bool>(_anyPredicate, source, lambda);
		}

		public static double Average(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute<double>(QueryableMethodFinder.GetMethod("Average", source.ElementType, typeof(double)), source);
		}

		public static double Average(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression lambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return source.Average(lambda);
		}

		public static double Average(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Average(ParsingConfig.Default, predicate, args);
		}

		public static double Average(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			Check.NotNull(lambda, "lambda");
			return Execute<double>(QueryableMethodFinder.GetMethod("Average", lambda.GetReturnType(), typeof(double), 1), source, lambda);
		}

		[IteratorStateMachine(typeof(<AsDynamicEnumerable>d__16))]
		public static IEnumerable<dynamic> AsDynamicEnumerable(this IQueryable source)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <AsDynamicEnumerable>d__16(-2)
			{
				<>3__source = source
			};
		}

		public static IQueryable Cast(this IQueryable source, Type type)
		{
			Check.NotNull(source, "source");
			Check.NotNull(type, "type");
			Expression expression = OptimizeExpression(Expression.Call(null, _cast.MakeGenericMethod(type), source.Expression));
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable Cast(this IQueryable source, ParsingConfig config, string typeName)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(typeName, "typeName");
			if (!new TypeFinder(config, new KeywordsHelper(config)).TryFindTypeByName(typeName, null, forceUseCustomTypeProvider: true, out Type type))
			{
				throw new ParseException(string.Format(CultureInfo.CurrentCulture, "Type '{0}' not found", typeName));
			}
			return source.Cast(type);
		}

		public static IQueryable Cast(this IQueryable source, string typeName)
		{
			return source.Cast(ParsingConfig.Default, typeName);
		}

		public static int Count(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute<int>(_count, source);
		}

		public static int Count(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute<int>(_countPredicate, source, expression);
		}

		public static int Count(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Count(ParsingConfig.Default, predicate, args);
		}

		public static int Count(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			Check.NotNull(lambda, "lambda");
			return Execute<int>(_countPredicate, source, lambda);
		}

		public static IQueryable DefaultIfEmpty(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return CreateQuery(_defaultIfEmpty, source);
		}

		public static IQueryable DefaultIfEmpty(this IQueryable source, object? defaultValue)
		{
			Check.NotNull(source, "source");
			return CreateQuery(_defaultIfEmptyWithParam, source, Expression.Constant(defaultValue));
		}

		public static IQueryable Distinct(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return CreateQuery(_distinct, source);
		}

		public static dynamic First(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_first, source);
		}

		public static dynamic First(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_firstPredicate, source, expression);
		}

		public static dynamic First(this IQueryable source, string predicate, params object?[] args)
		{
			return source.First(ParsingConfig.Default, predicate, args);
		}

		public static dynamic First(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_firstPredicate, source, lambda);
		}

		public static dynamic FirstOrDefault(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_firstOrDefault, source);
		}

		public static dynamic FirstOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_firstOrDefaultPredicate, source, expression);
		}

		public static dynamic FirstOrDefault(this IQueryable source, string predicate, params object?[] args)
		{
			return source.FirstOrDefault(ParsingConfig.Default, predicate, args);
		}

		public static dynamic FirstOrDefault(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_firstOrDefaultPredicate, source, lambda);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector, object[] args)
		{
			return InternalGroupBy(source, config, keySelector, resultSelector, null, args);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector, IEqualityComparer? equalityComparer, object[]? args)
		{
			return InternalGroupBy(source, config, keySelector, resultSelector, equalityComparer, args);
		}

		internal static IQueryable InternalGroupBy(IQueryable source, ParsingConfig config, string keySelector, string resultSelector, IEqualityComparer? equalityComparer, object[]? args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(keySelector, "keySelector");
			Check.NotEmpty(resultSelector, "resultSelector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, keySelector, args);
			LambdaExpression lambdaExpression2 = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, resultSelector, args);
			Expression expression;
			if (equalityComparer == null)
			{
				expression = OptimizeExpression(Expression.Call(typeof(Queryable), "GroupBy", new Type[3]
				{
					source.ElementType,
					lambdaExpression.Body.Type,
					lambdaExpression2.Body.Type
				}, source.Expression, Expression.Quote(lambdaExpression), Expression.Quote(lambdaExpression2)));
			}
			else
			{
				Type type = typeof(IEqualityComparer<>).MakeGenericType(lambdaExpression.Body.Type);
				expression = OptimizeExpression(Expression.Call(typeof(Queryable), "GroupBy", new Type[3]
				{
					source.ElementType,
					lambdaExpression.Body.Type,
					lambdaExpression2.Body.Type
				}, source.Expression, Expression.Quote(lambdaExpression), Expression.Quote(lambdaExpression2), Expression.Constant(equalityComparer, type)));
			}
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector, object[] args)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, resultSelector, args);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector, IEqualityComparer equalityComparer, object[] args)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, resultSelector, equalityComparer, args);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector)
		{
			return source.GroupBy(config, keySelector, resultSelector, null, null);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, resultSelector);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, string resultSelector, IEqualityComparer equalityComparer)
		{
			return InternalGroupBy(source, config, keySelector, resultSelector, equalityComparer, null);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, string resultSelector, IEqualityComparer equalityComparer)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, resultSelector, equalityComparer);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, params object[]? args)
		{
			return InternalGroupBy(source, config, keySelector, null, args);
		}

		public static IQueryable GroupBy(this IQueryable source, ParsingConfig config, string keySelector, IEqualityComparer equalityComparer, params object[]? args)
		{
			return InternalGroupBy(source, config, keySelector, equalityComparer, args);
		}

		internal static IQueryable InternalGroupBy(IQueryable source, ParsingConfig config, string keySelector, IEqualityComparer? equalityComparer, params object[]? args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(keySelector, "keySelector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, keySelector, args);
			Expression expression;
			if (equalityComparer == null)
			{
				expression = OptimizeExpression(Expression.Call(typeof(Queryable), "GroupBy", new Type[2]
				{
					source.ElementType,
					lambdaExpression.Body.Type
				}, source.Expression, Expression.Quote(lambdaExpression)));
			}
			else
			{
				Type type = typeof(IEqualityComparer<>).MakeGenericType(lambdaExpression.Body.Type);
				expression = OptimizeExpression(Expression.Call(typeof(Queryable), "GroupBy", new Type[2]
				{
					source.ElementType,
					lambdaExpression.Body.Type
				}, source.Expression, Expression.Quote(lambdaExpression), Expression.Constant(equalityComparer, type)));
			}
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, params object[]? args)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, args);
		}

		public static IQueryable GroupBy(this IQueryable source, string keySelector, IEqualityComparer equalityComparer, params object[]? args)
		{
			return source.GroupBy(ParsingConfig.Default, keySelector, equalityComparer, args);
		}

		public static IEnumerable<GroupResult> GroupByMany<TElement>(this IEnumerable<TElement> source, ParsingConfig config, params string[] keySelectors)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.HasNoNulls(keySelectors, "keySelectors");
			List<Func<TElement, object>> list = new List<Func<TElement, object>>(keySelectors.Length);
			foreach (string expression in keySelectors)
			{
				LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, true, typeof(TElement), null, expression);
				list.Add((Func<TElement, object>)EnsureLambdaExpressionReturnsObject(lambdaExpression).Compile());
			}
			return GroupByManyInternal(source, list.ToArray(), 0);
		}

		public static IEnumerable<GroupResult> GroupByMany<TElement>(this IEnumerable<TElement> source, params string[] keySelectors)
		{
			return source.GroupByMany(ParsingConfig.Default, keySelectors);
		}

		public static IEnumerable<GroupResult> GroupByMany<TElement>(this IEnumerable<TElement> source, params Func<TElement, object>[] keySelectors)
		{
			Check.NotNull(source, "source");
			Check.HasNoNulls(keySelectors, "keySelectors");
			return GroupByManyInternal(source, keySelectors, 0);
		}

		private static IEnumerable<GroupResult> GroupByManyInternal<TElement>(IEnumerable<TElement> source, Func<TElement, object>[] keySelectors, int currentSelector)
		{
			Func<TElement, object>[] keySelectors2 = keySelectors;
			if (currentSelector >= keySelectors2.Length)
			{
				return null;
			}
			Func<TElement, object> keySelector = keySelectors2[currentSelector];
			return from g in source.GroupBy(keySelector)
				select new GroupResult
				{
					Key = g.Key,
					Count = g.Count(),
					Items = g,
					Subgroups = GroupByManyInternal(g, keySelectors2, currentSelector + 1)
				};
		}

		public static IQueryable GroupJoin(this IQueryable outer, ParsingConfig config, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			Check.NotNull(outer, "outer");
			Check.NotNull(config, "config");
			Check.NotNull(inner, "inner");
			Check.NotEmpty(outerKeySelector, "outerKeySelector");
			Check.NotEmpty(innerKeySelector, "innerKeySelector");
			Check.NotEmpty(resultSelector, "resultSelector");
			Check.Args(args, "args");
			Type elementType = outer.ElementType;
			Type elementType2 = inner.AsQueryable().ElementType;
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, outer);
			LambdaExpression outerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, elementType, null, outerKeySelector, args);
			LambdaExpression innerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, elementType2, null, innerKeySelector, args);
			CheckOuterAndInnerTypes(config, createParameterCtor, elementType, elementType2, outerKeySelector, innerKeySelector, ref outerSelectorLambda, ref innerSelectorLambda, args);
			ParameterExpression[] parameters = new ParameterExpression[2]
			{
				ParameterExpressionHelper.CreateParameterExpression(elementType, "outer"),
				ParameterExpressionHelper.CreateParameterExpression(typeof(IEnumerable<>).MakeGenericType(elementType2), "inner")
			};
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, parameters, null, resultSelector, args);
			return outer.Provider.CreateQuery(Expression.Call(typeof(Queryable), "GroupJoin", new Type[4]
			{
				outer.ElementType,
				elementType2,
				outerSelectorLambda.Body.Type,
				lambdaExpression.Body.Type
			}, outer.Expression, inner.AsQueryable().Expression, Expression.Quote(outerSelectorLambda), Expression.Quote(innerSelectorLambda), Expression.Quote(lambdaExpression)));
		}

		public static IQueryable GroupJoin(this IQueryable outer, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			return outer.GroupJoin(ParsingConfig.Default, inner, outerKeySelector, innerKeySelector, resultSelector, args);
		}

		public static IQueryable Join(this IQueryable outer, ParsingConfig config, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			Check.NotNull(outer, "outer");
			Check.NotNull(config, "config");
			Check.NotNull(inner, "inner");
			Check.NotEmpty(outerKeySelector, "outerKeySelector");
			Check.NotEmpty(innerKeySelector, "innerKeySelector");
			Check.NotEmpty(resultSelector, "resultSelector");
			Check.Args(args, "args");
			Type elementType = outer.ElementType;
			Type elementType2 = inner.AsQueryable().ElementType;
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, outer);
			LambdaExpression outerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, elementType, null, outerKeySelector, args);
			LambdaExpression innerSelectorLambda = DynamicExpressionParser.ParseLambda(config, createParameterCtor, elementType2, null, innerKeySelector, args);
			CheckOuterAndInnerTypes(config, createParameterCtor, elementType, elementType2, outerKeySelector, innerKeySelector, ref outerSelectorLambda, ref innerSelectorLambda, args);
			ParameterExpression[] parameters = new ParameterExpression[2]
			{
				ParameterExpressionHelper.CreateParameterExpression(elementType, "outer"),
				ParameterExpressionHelper.CreateParameterExpression(elementType2, "inner")
			};
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, parameters, null, resultSelector, args);
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "Join", new Type[4]
			{
				elementType,
				elementType2,
				outerSelectorLambda.Body.Type,
				lambdaExpression.Body.Type
			}, outer.Expression, inner.AsQueryable().Expression, Expression.Quote(outerSelectorLambda), Expression.Quote(innerSelectorLambda), Expression.Quote(lambdaExpression)));
			return outer.Provider.CreateQuery(expression);
		}

		public static IQueryable Join(this IQueryable outer, IEnumerable inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			return outer.Join(ParsingConfig.Default, inner, outerKeySelector, innerKeySelector, resultSelector, args);
		}

		public static IQueryable<TElement> Join<TElement>(this IQueryable<TElement> outer, ParsingConfig config, IEnumerable<TElement> inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			return (IQueryable<TElement>)((IQueryable)outer).Join(config, (IEnumerable)inner, outerKeySelector, innerKeySelector, resultSelector, args);
		}

		public static IQueryable<TElement> Join<TElement>(this IQueryable<TElement> outer, IEnumerable<TElement> inner, string outerKeySelector, string innerKeySelector, string resultSelector, params object?[] args)
		{
			return outer.Join(ParsingConfig.Default, inner, outerKeySelector, innerKeySelector, resultSelector, args);
		}

		public static dynamic Last(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_last, source);
		}

		public static dynamic Last(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_lastPredicate, source, expression);
		}

		public static dynamic Last(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Last(ParsingConfig.Default, predicate, args);
		}

		public static dynamic Last(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_lastPredicate, source, lambda);
		}

		public static dynamic LastOrDefault(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_lastDefault, source);
		}

		public static dynamic LastOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_lastDefaultPredicate, source, expression);
		}

		public static dynamic LastOrDefault(this IQueryable source, string predicate, params object?[] args)
		{
			return source.LastOrDefault(ParsingConfig.Default, predicate, args);
		}

		public static dynamic LastOrDefault(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_lastDefaultPredicate, source, lambda);
		}

		public static long LongCount(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute<long>(_longCount, source);
		}

		public static long LongCount(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute<long>(_longCountPredicate, source, expression);
		}

		public static long LongCount(this IQueryable source, string predicate, params object?[] args)
		{
			return source.LongCount(ParsingConfig.Default, predicate, args);
		}

		public static long LongCount(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			Check.NotNull(lambda, "lambda");
			return Execute<long>(_longCountPredicate, source, lambda);
		}

		public static object Max(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_max, source);
		}

		public static object Max(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, typeof(object), predicate, args);
			return Execute(_maxPredicate, source, expression);
		}

		public static object Max(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Max(ParsingConfig.Default, predicate, args);
		}

		public static object Max(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_maxPredicate, source, lambda);
		}

		public static object Min(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute(_min, source);
		}

		public static object Min(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, typeof(object), predicate, args);
			return Execute(_minPredicate, source, expression);
		}

		public static object Min(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Min(ParsingConfig.Default, predicate, args);
		}

		public static object Min(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_minPredicate, source, lambda);
		}

		public static IQueryable OfType(this IQueryable source, Type type)
		{
			Check.NotNull(source, "source");
			Check.NotNull(type, "type");
			Expression expression = OptimizeExpression(Expression.Call(null, _ofType.MakeGenericMethod(type), source.Expression));
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable OfType(this IQueryable source, ParsingConfig config, string typeName)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(typeName, "typeName");
			if (!new TypeFinder(config, new KeywordsHelper(config)).TryFindTypeByName(typeName, null, forceUseCustomTypeProvider: true, out Type type))
			{
				throw new ParseException(string.Format(CultureInfo.CurrentCulture, "Type '{0}' not found", typeName));
			}
			return source.OfType(type);
		}

		public static IQueryable OfType(this IQueryable source, string typeName)
		{
			return source.OfType(ParsingConfig.Default, typeName);
		}

		public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, ParsingConfig config, string ordering, params object?[] args)
		{
			return (IOrderedQueryable<TSource>)((IQueryable)source).OrderBy(config, ordering, args);
		}

		public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string ordering, params object?[] args)
		{
			return source.OrderBy(ParsingConfig.Default, ordering, args);
		}

		public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, ParsingConfig config, string ordering, IComparer comparer, params object?[] args)
		{
			return (IOrderedQueryable<TSource>)InternalOrderBy(source, config, ordering, comparer, args);
		}

		public static IOrderedQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string ordering, IComparer comparer, params object?[] args)
		{
			return source.OrderBy(ParsingConfig.Default, ordering, comparer, args);
		}

		public static IOrderedQueryable OrderBy(this IQueryable source, ParsingConfig config, string ordering, params object?[] args)
		{
			Check.Args(args, "args");
			if (args.Length != 0 && args[0] != null && args[0].GetType().GetInterfaces().Any((Type i) => i.Name.Contains("IComparer`1")))
			{
				return InternalOrderBy(source, config, ordering, args[0], args);
			}
			return InternalOrderBy(source, config, ordering, null, args);
		}

		public static IOrderedQueryable OrderBy(this IQueryable source, ParsingConfig config, string ordering, IComparer comparer, params object?[] args)
		{
			return InternalOrderBy(source, config, ordering, comparer, args);
		}

		public static IOrderedQueryable OrderBy(this IQueryable source, string ordering, params object?[] args)
		{
			return source.OrderBy(ParsingConfig.Default, ordering, args);
		}

		public static IOrderedQueryable OrderBy(this IQueryable source, string ordering, IComparer comparer, params object?[] args)
		{
			return source.OrderBy(ParsingConfig.Default, ordering, comparer, args);
		}

		internal static IOrderedQueryable InternalOrderBy(IQueryable source, ParsingConfig config, string ordering, object? comparer, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(ordering, "ordering");
			Check.Args(args, "args");
			ParameterExpression[] parameters = new ParameterExpression[1] { ParameterExpressionHelper.CreateParameterExpression(source.ElementType, string.Empty, config.RenameEmptyParameterExpressionNames) };
			IList<DynamicOrdering> list = new ExpressionParser(parameters, ordering, args, config, usedForOrderBy: true).ParseOrdering();
			Expression expression = source.Expression;
			foreach (DynamicOrdering item in list)
			{
				if (comparer == null)
				{
					expression = Expression.Call(typeof(Queryable), item.MethodName, new Type[2]
					{
						source.ElementType,
						item.Selector.Type
					}, expression, Expression.Quote(Expression.Lambda(item.Selector, parameters)));
				}
				else
				{
					Type type = typeof(IComparer<>).MakeGenericType(item.Selector.Type);
					ConstantExpression constantExpression = ((!type.IsInstanceOfType(comparer)) ? Expression.Constant(Activator.CreateInstance(DynamicClassFactory.CreateGenericComparerType(type, comparer.GetType())), type) : Expression.Constant(comparer, type));
					expression = Expression.Call(typeof(Queryable), item.MethodName, new Type[2]
					{
						source.ElementType,
						item.Selector.Type
					}, expression, Expression.Quote(Expression.Lambda(item.Selector, parameters)), constantExpression);
				}
			}
			Expression expression2 = OptimizeExpression(expression);
			return (IOrderedQueryable)source.Provider.CreateQuery(expression2);
		}

		public static IQueryable Page(this IQueryable source, int page, int pageSize)
		{
			Check.NotNull(source, "source");
			Check.Condition(page, (int p) => p > 0, "page");
			Check.Condition(pageSize, (int ps) => ps > 0, "pageSize");
			return source.Skip((page - 1) * pageSize).Take(pageSize);
		}

		public static IQueryable<TSource> Page<TSource>(this IQueryable<TSource> source, int page, int pageSize)
		{
			Check.NotNull(source, "source");
			Check.Condition(page, (int p) => p > 0, "page");
			Check.Condition(pageSize, (int ps) => ps > 0, "pageSize");
			return Queryable.Take(Queryable.Skip(source, (page - 1) * pageSize), pageSize);
		}

		public static PagedResult PageResult(this IQueryable source, int page, int pageSize, int? rowCount = null)
		{
			Check.NotNull(source, "source");
			Check.Condition(page, (int p) => p > 0, "page");
			Check.Condition(pageSize, (int ps) => ps > 0, "pageSize");
			Check.Condition(rowCount, (int? rc) => !rc.HasValue || rc >= 0, "rowCount");
			PagedResult obj = new PagedResult
			{
				CurrentPage = page,
				PageSize = pageSize,
				RowCount = (rowCount ?? source.Count())
			};
			obj.PageCount = (int)Math.Ceiling((double)obj.RowCount / (double)pageSize);
			obj.Queryable = source.Page(page, pageSize);
			return obj;
		}

		public static PagedResult<TSource> PageResult<TSource>(this IQueryable<TSource> source, int page, int pageSize, int? rowCount = null)
		{
			Check.NotNull(source, "source");
			Check.Condition(page, (int p) => p > 0, "page");
			Check.Condition(pageSize, (int ps) => ps > 0, "pageSize");
			Check.Condition(rowCount, (int? rc) => !rc.HasValue || rc >= 0, "rowCount");
			PagedResult<TSource> obj = new PagedResult<TSource>
			{
				CurrentPage = page,
				PageSize = pageSize,
				RowCount = (rowCount ?? Queryable.Count(source))
			};
			obj.PageCount = (int)Math.Ceiling((double)obj.RowCount / (double)pageSize);
			obj.Queryable = source.Page(page, pageSize);
			return obj;
		}

		public static IQueryable Reverse(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Queryable.Reverse((IQueryable<object>)source);
		}

		public static IQueryable Select(this IQueryable source, ParsingConfig config, string selector, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(selector, "selector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, selector, args);
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "Select", new Type[2]
			{
				source.ElementType,
				lambdaExpression.Body.Type
			}, source.Expression, Expression.Quote(lambdaExpression)));
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable Select(this IQueryable source, string selector, params object?[] args)
		{
			return source.Select(ParsingConfig.Default, selector, args);
		}

		public static IQueryable<TResult> Select<TResult>(this IQueryable source, ParsingConfig config, string selector, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(selector, "selector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, typeof(TResult), selector, args);
			Expression expression2 = OptimizeExpression(Expression.Call(typeof(Queryable), "Select", new Type[2]
			{
				source.ElementType,
				typeof(TResult)
			}, source.Expression, Expression.Quote(expression)));
			return source.Provider.CreateQuery<TResult>(expression2);
		}

		public static IQueryable<TResult> Select<TResult>(this IQueryable source, string selector, params object?[] args)
		{
			return source.Select<TResult>(ParsingConfig.Default, selector, args);
		}

		public static IQueryable Select(this IQueryable source, ParsingConfig config, Type resultType, string selector, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotNull(resultType, "resultType");
			Check.NotEmpty(selector, "selector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, resultType, selector, args);
			Expression expression2 = OptimizeExpression(Expression.Call(typeof(Queryable), "Select", new Type[2] { source.ElementType, resultType }, source.Expression, Expression.Quote(expression)));
			return source.Provider.CreateQuery(expression2);
		}

		public static IQueryable Select(this IQueryable source, Type resultType, string selector, params object?[] args)
		{
			return source.Select(ParsingConfig.Default, resultType, selector, args);
		}

		public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, string selector, params object?[] args)
		{
			return SelectManyInternal(source, config, null, selector, args);
		}

		public static IQueryable SelectMany(this IQueryable source, string selector, params object?[] args)
		{
			return source.SelectMany(ParsingConfig.Default, selector, args);
		}

		public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, Type resultType, string selector, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotNull(resultType, "resultType");
			Check.NotEmpty(selector, "selector");
			Check.Args(args, "args");
			return SelectManyInternal(source, config, resultType, selector, args);
		}

		public static IQueryable SelectMany(this IQueryable source, Type resultType, string selector, params object?[] args)
		{
			return source.SelectMany(ParsingConfig.Default, resultType, selector, args);
		}

		private static IQueryable SelectManyInternal(IQueryable source, ParsingConfig config, Type? resultType, string selector, params object?[] args)
		{
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, selector, args);
			if (resultType == null)
			{
				if (lambdaExpression.Body.Type.IsArray)
				{
					resultType = lambdaExpression.Body.Type.GetElementType();
				}
				else
				{
					Type[] genericArguments = lambdaExpression.Body.Type.GetGenericArguments();
					resultType = (genericArguments.Any() ? genericArguments[0] : typeof(object));
				}
			}
			Type type = typeof(IEnumerable<>).MakeGenericType(resultType);
			Type type2 = source.Expression.Type.GetTypeInfo().GetGenericTypeArguments()[0];
			lambdaExpression = Expression.Lambda(typeof(Func<, >).MakeGenericType(type2, type), lambdaExpression.Body, lambdaExpression.Parameters);
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "SelectMany", new Type[2] { source.ElementType, resultType }, source.Expression, Expression.Quote(lambdaExpression)));
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable<TResult> SelectMany<TResult>(this IQueryable source, ParsingConfig config, string selector, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(selector, "selector");
			Check.Args(args, "args");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, selector, args);
			Type type = source.Expression.Type.GetTypeInfo().GetGenericTypeArguments()[0];
			Type type2 = typeof(IEnumerable<>).MakeGenericType(typeof(TResult));
			lambdaExpression = Expression.Lambda(typeof(Func<, >).MakeGenericType(type, type2), lambdaExpression.Body, lambdaExpression.Parameters);
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "SelectMany", new Type[2]
			{
				source.ElementType,
				typeof(TResult)
			}, source.Expression, Expression.Quote(lambdaExpression)));
			return source.Provider.CreateQuery<TResult>(expression);
		}

		public static IQueryable<TResult> SelectMany<TResult>(this IQueryable source, string selector, params object?[] args)
		{
			return source.SelectMany<TResult>(ParsingConfig.Default, selector, args);
		}

		public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, string collectionSelector, string resultSelector, object?[]? collectionSelectorArgs = null, params object?[]? resultSelectorArgs)
		{
			return source.SelectMany(collectionSelector, resultSelector, "x", "y", collectionSelectorArgs, resultSelectorArgs);
		}

		public static IQueryable SelectMany(this IQueryable source, string collectionSelector, string resultSelector, object[]? collectionSelectorArgs = null, params object[]? resultSelectorArgs)
		{
			return source.SelectMany(ParsingConfig.Default, collectionSelector, resultSelector, "x", "y", collectionSelectorArgs, resultSelectorArgs);
		}

		public static IQueryable SelectMany(this IQueryable source, ParsingConfig config, string collectionSelector, string resultSelector, string collectionParameterName, string resultParameterName, object?[]? collectionSelectorArgs = null, params object[]? resultSelectorArgs)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(collectionSelector, "collectionSelector");
			Check.NotEmpty(collectionParameterName, "collectionParameterName");
			Check.NotEmpty(resultSelector, "resultSelector");
			Check.NotEmpty(resultParameterName, "resultParameterName");
			Check.Args(collectionSelectorArgs, "collectionSelectorArgs");
			Check.Args(resultSelectorArgs, "resultSelectorArgs");
			bool createParameterCtor = config.EvaluateGroupByAtDatabase || SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, collectionSelector, collectionSelectorArgs);
			Type type = source.Expression.Type.GetGenericArguments()[0];
			Type type2 = lambdaExpression.Body.Type.GetGenericArguments()[0];
			Type type3 = typeof(IEnumerable<>).MakeGenericType(type2);
			lambdaExpression = Expression.Lambda(typeof(Func<, >).MakeGenericType(type, type3), lambdaExpression.Body, lambdaExpression.Parameters);
			ParameterExpression parameterExpression = ParameterExpressionHelper.CreateParameterExpression(source.ElementType, collectionParameterName, config.RenameEmptyParameterExpressionNames);
			ParameterExpression parameterExpression2 = ParameterExpressionHelper.CreateParameterExpression(type2, resultParameterName, config.RenameEmptyParameterExpressionNames);
			LambdaExpression lambdaExpression2 = DynamicExpressionParser.ParseLambda(config, createParameterCtor, new ParameterExpression[2] { parameterExpression, parameterExpression2 }, null, resultSelector, resultSelectorArgs);
			Type type4 = lambdaExpression2.Body.Type;
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "SelectMany", new Type[3] { source.ElementType, type2, type4 }, source.Expression, Expression.Quote(lambdaExpression), Expression.Quote(lambdaExpression2)));
			return source.Provider.CreateQuery(expression);
		}

		public static IQueryable SelectMany(this IQueryable source, string collectionSelector, string resultSelector, string collectionParameterName, string resultParameterName, object?[]? collectionSelectorArgs = null, params object?[]? resultSelectorArgs)
		{
			return source.SelectMany(ParsingConfig.Default, collectionSelector, resultSelector, collectionParameterName, resultParameterName, collectionSelectorArgs, resultSelectorArgs);
		}

		public static dynamic Single(this IQueryable source)
		{
			Check.NotNull(source, "source");
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "Single", new Type[1] { source.ElementType }, source.Expression));
			return source.Provider.Execute(expression);
		}

		public static dynamic Single(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_singlePredicate, source, expression);
		}

		public static dynamic Single(this IQueryable source, string predicate, params object?[] args)
		{
			return source.Single(ParsingConfig.Default, predicate, args);
		}

		public static dynamic Single(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			return Execute(_singlePredicate, source, lambda);
		}

		public static dynamic SingleOrDefault(this IQueryable source)
		{
			Check.NotNull(source, "source");
			Expression expression = OptimizeExpression(Expression.Call(typeof(Queryable), "SingleOrDefault", new Type[1] { source.ElementType }, source.Expression));
			return source.Provider.Execute(expression);
		}

		public static dynamic SingleOrDefault(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute(_singleDefaultPredicate, source, expression);
		}

		public static dynamic SingleOrDefault(this IQueryable source, string predicate, params object?[] args)
		{
			return source.SingleOrDefault(ParsingConfig.Default, predicate, args);
		}

		public static dynamic SingleOrDefault(this IQueryable source, LambdaExpression lambda)
		{
			Check.NotNull(source, "source");
			Check.NotNull(lambda, "lambda");
			return Execute(_singleDefaultPredicate, source, lambda);
		}

		public static IQueryable Skip(this IQueryable source, int count)
		{
			Check.NotNull(source, "source");
			Check.Condition(count, (int x) => x >= 0, "count");
			if (count == 0)
			{
				return source;
			}
			return CreateQuery(_skip, source, Expression.Constant(count));
		}

		public static IQueryable SkipWhile(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotNull(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression expression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return CreateQuery(_skipWhilePredicate, source, expression);
		}

		public static IQueryable SkipWhile(this IQueryable source, string predicate, params object?[] args)
		{
			return source.SkipWhile(ParsingConfig.Default, predicate, args);
		}

		public static object Sum(this IQueryable source)
		{
			Check.NotNull(source, "source");
			return Execute<object>(QueryableMethodFinder.GetMethod("Sum", source.ElementType), source);
		}

		public static object Sum(this IQueryable source, ParsingConfig config, string predicate, params object?[] args)
		{
			Check.NotNull(source, "source");
			Check.NotNull(config, "config");
			Check.NotEmpty(predicate, "predicate");
			Check.Args(args, "args");
			bool createParameterCtor = SupportsLinqToObjects(config, source);
			LambdaExpression lambdaExpression = DynamicExpressionParser.ParseLambda(config, createParameterCtor, source.ElementType, null, predicate, args);
			return Execute<object>(QueryableMethodFinder.GetMethod("Sum", lambdaExpression.GetReturnType(), 1), source, lambdaExpression);
		}

		public static object Sum(this IQueryable source