Decompiled source of CityPlanner v1.9.0

CityPlanner.dll

Decompiled 3 weeks ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("CityPlanner")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.9.0.0")]
[assembly: AssemblyInformationalVersion("1.9.0+231716aa3a4f8cc5b6abc418c9c4a3e5a9584e86")]
[assembly: AssemblyProduct("CityPlanner")]
[assembly: AssemblyTitle("CityPlanner")]
[assembly: AssemblyVersion("1.9.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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]
	[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]
	[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 CityPlanner
{
	internal static class AddressIds
	{
		public static void SortBuildings()
		{
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			try
			{
				Dictionary<IntPtr, int> order = new Dictionary<IntPtr, int>();
				int num = 0;
				Enumerator<Vector2Int, CityTile> enumerator = HighlanderSingleton<CityBoundaryAndTiles>.Instance.cityTiles.GetEnumerator();
				while (enumerator.MoveNext())
				{
					KeyValuePair<Vector2Int, CityTile> current = enumerator.Current;
					order[((Il2CppObjectBase)current.Value).Pointer] = num++;
				}
				List<NewBuilding> buildingDirectory = HighlanderSingleton<CityBuildings>.Instance.buildingDirectory;
				List<NewBuilding> list = new List<NewBuilding>();
				for (int i = 0; i < buildingDirectory.Count; i++)
				{
					list.Add(buildingDirectory[i]);
				}
				List<NewBuilding> list2 = new List<NewBuilding>(list);
				list2.Sort((NewBuilding a, NewBuilding b) => Rank(a).CompareTo(Rank(b)));
				int num2 = 0;
				for (int num3 = 0; num3 < list2.Count; num3++)
				{
					if (((Il2CppObjectBase)list2[num3]).Pointer != ((Il2CppObjectBase)list[num3]).Pointer)
					{
						num2++;
					}
				}
				if (num2 == 0)
				{
					return;
				}
				buildingDirectory.Clear();
				foreach (NewBuilding item in list2)
				{
					buildingDirectory.Add(item);
				}
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(62, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Buildings put in map order before numbering addresses (");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num2);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" moved)");
				}
				logger.LogInfo(val);
				int Rank(NewBuilding nb)
				{
					if (!((Object)(object)((nb != null) ? nb.cityTile : null) != (Object)null) || !order.TryGetValue(((Il2CppObjectBase)nb.cityTile).Pointer, out var value))
					{
						return int.MaxValue;
					}
					return value;
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)("Sorting buildings failed: " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(CityConstructor), "Update")]
	internal static class LoadAddressIdsPatch
	{
		private static bool done;

		private static void Prefix(CityConstructor __instance)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Expected O, but got Unknown
			try
			{
				if (__instance.generateNew || (int)__instance.loadState == 0)
				{
					done = false;
				}
				else
				{
					if (done)
					{
						return;
					}
					CitySaveData currentData = __instance.currentData;
					if (((currentData != null) ? currentData.cityTiles : null) == null)
					{
						return;
					}
					done = true;
					int num = 0;
					Enumerator<CityTileCitySave> enumerator = __instance.currentData.cityTiles.GetEnumerator();
					while (enumerator.MoveNext())
					{
						CityTileCitySave current = enumerator.Current;
						object obj;
						if (current == null)
						{
							obj = null;
						}
						else
						{
							BuildingCitySave building = current.building;
							obj = ((building != null) ? building.floors : null);
						}
						List<FloorCitySave> val = (List<FloorCitySave>)obj;
						if (val == null)
						{
							continue;
						}
						Enumerator<FloorCitySave> enumerator2 = val.GetEnumerator();
						while (enumerator2.MoveNext())
						{
							FloorCitySave current2 = enumerator2.Current;
							if (((current2 != null) ? current2.addresses : null) == null)
							{
								continue;
							}
							Enumerator<AddressCitySave> enumerator3 = current2.addresses.GetEnumerator();
							while (enumerator3.MoveNext())
							{
								AddressCitySave current3 = enumerator3.Current;
								if (current3 != null)
								{
									num = Math.Max(num, current3.id);
								}
							}
						}
					}
					if (num + 1 > NewAddress.assignID)
					{
						NewAddress.assignID = num + 1;
						ManualLogSource logger = Plugin.Logger;
						bool flag = default(bool);
						BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(77, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Loading city: rebuilt addresses are numbered from ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num + 1);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", above every saved address");
						}
						logger.LogInfo(val2);
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)("Setting address numbers for loading failed: " + ex));
			}
		}
	}
	internal static class Basements
	{
		private const float Drained = -10000f;

		private static float? originalLevel;

		public static void Tick()
		{
			CityControls instance = CityControls.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			bool value = Plugin.FloodedBasements.Value;
			Transform basementWaterTransform = instance.basementWaterTransform;
			if (!value)
			{
				if (instance.basementWaterLevel != -10000f)
				{
					float valueOrDefault = originalLevel.GetValueOrDefault();
					if (!originalLevel.HasValue)
					{
						valueOrDefault = instance.basementWaterLevel;
						originalLevel = valueOrDefault;
					}
					instance.basementWaterLevel = -10000f;
				}
				if ((Object)(object)basementWaterTransform != (Object)null && ((Component)basementWaterTransform).gameObject.activeSelf)
				{
					((Component)basementWaterTransform).gameObject.SetActive(false);
				}
			}
			else if (originalLevel.HasValue)
			{
				instance.basementWaterLevel = originalLevel.Value;
				originalLevel = null;
				if ((Object)(object)basementWaterTransform != (Object)null)
				{
					((Component)basementWaterTransform).gameObject.SetActive(true);
				}
			}
		}
	}
	internal static class Businesses
	{
		[HarmonyPatch(typeof(NewAddress), "AssignPurpose")]
		private static class SkipPlanned
		{
			private static bool Prefix(NewAddress __instance)
			{
				if (!assigning && Planned.Count != 0)
				{
					return !Planned.Contains(((Il2CppObjectBase)__instance).Pointer);
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(NewBuilding), "LoadInterior")]
		private static class FloorPlanPatch
		{
			private static readonly List<(List<TextAsset> List, TextAsset[] All)> narrowed = new List<(List<TextAsset>, TextAsset[])>();

			private static void Prefix(NewBuilding __instance)
			{
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				//IL_012d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0134: Expected O, but got Unknown
				narrowed.Clear();
				if (!Plugin.Active || (Object)(object)((__instance != null) ? __instance.cityTile : null) == (Object)null || (SoCustomComparison)(object)__instance.preset == (SoCustomComparison)null)
				{
					return;
				}
				Vector2Int cityCoord = __instance.cityTile.cityCoord;
				if (!Plugin.Plan.Tiles.TryGetValue((((Vector2Int)(ref cityCoord)).x, ((Vector2Int)(ref cityCoord)).y), out var value) || value.Businesses.Count == 0)
				{
					return;
				}
				try
				{
					Dictionary<string, int> dictionary = UnitsNeeded(value);
					if (dictionary.Count == 0)
					{
						return;
					}
					int num = 0;
					List<InteriorFloorSetting>[] array = new List<InteriorFloorSetting>[2]
					{
						__instance.preset.floorLayouts,
						__instance.preset.basementLayouts
					};
					foreach (List<InteriorFloorSetting> val in array)
					{
						if (val == null)
						{
							continue;
						}
						Enumerator<InteriorFloorSetting> enumerator = val.GetEnumerator();
						while (enumerator.MoveNext())
						{
							InteriorFloorSetting current = enumerator.Current;
							if (((current != null) ? current.blueprints : null) != null && current.blueprints.Count > 1 && Narrow(current.blueprints, dictionary))
							{
								num++;
							}
						}
					}
					if (num > 0)
					{
						ManualLogSource logger = Plugin.Logger;
						bool flag = default(bool);
						BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(81, 5, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)__instance.preset).name);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" at tile R");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(Plugin.Plan.Height - 1 - ((Vector2Int)(ref cityCoord)).y);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" C");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(((Vector2Int)(ref cityCoord)).x);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": floor plans narrowed to fit its planned businesses (");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" floor setting");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>((num > 1) ? "s" : "");
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(")");
						}
						logger.LogInfo(val2);
					}
				}
				catch (Exception ex)
				{
					Plugin.Logger.LogError((object)("Choosing floor plans for planned businesses failed: " + ex));
				}
			}

			private static void Finalizer()
			{
				foreach (var (val, array) in narrowed)
				{
					val.Clear();
					TextAsset[] array2 = array;
					foreach (TextAsset val2 in array2)
					{
						val.Add(val2);
					}
				}
				narrowed.Clear();
			}

			private static Dictionary<string, int> UnitsNeeded(PlannedTile tile)
			{
				Dictionary<string, int> dictionary = new Dictionary<string, int>();
				foreach (string business in tile.Businesses)
				{
					AddressPreset val = null;
					Enumerator<AddressPreset> enumerator2 = Toolbox.Instance.allAddressPresets.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						AddressPreset current2 = enumerator2.Current;
						if ((SoCustomComparison)(object)current2 != (SoCustomComparison)null && string.Equals(((Object)current2).name, business, StringComparison.OrdinalIgnoreCase))
						{
							val = current2;
							break;
						}
					}
					LayoutConfiguration val2 = ((val != null && val.compatible.Count > 0) ? val.compatible[0] : null);
					if (!((SoCustomComparison)(object)val2 == (SoCustomComparison)null))
					{
						dictionary[((Object)val2).name] = ((!dictionary.TryGetValue(((Object)val2).name, out var value)) ? 1 : (value + 1));
					}
				}
				return dictionary;
			}

			private static bool Narrow(List<TextAsset> blueprints, Dictionary<string, int> need)
			{
				TextAsset[] array = (TextAsset[])(object)new TextAsset[blueprints.Count];
				int[] array2 = new int[array.Length];
				FloorSaveData val = default(FloorSaveData);
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = blueprints[i];
					if ((Object)(object)array[i] == (Object)null || !CityData.Instance.floorData.TryGetValue(((Object)array[i]).name, ref val) || ((val != null) ? val.a_d : null) == null)
					{
						continue;
					}
					Dictionary<string, int> dictionary = new Dictionary<string, int>();
					Enumerator<AddressSaveData> enumerator = val.a_d.GetEnumerator();
					while (enumerator.MoveNext())
					{
						AddressSaveData current = enumerator.Current;
						if (current != null && current.p_n != null)
						{
							dictionary[current.p_n] = ((!dictionary.TryGetValue(current.p_n, out var value)) ? 1 : (value + 1));
						}
					}
					foreach (var (key, val2) in need)
					{
						array2[i] += Math.Min(val2, dictionary.TryGetValue(key, out var value2) ? value2 : 0);
					}
				}
				int best = array2.Max();
				if (array2.All((int s) => s == best))
				{
					return false;
				}
				narrowed.Add((blueprints, array));
				blueprints.Clear();
				for (int num2 = 0; num2 < array.Length; num2++)
				{
					if (array2[num2] == best)
					{
						blueprints.Add(array[num2]);
					}
				}
				return true;
			}
		}

		internal static readonly HashSet<IntPtr> Planned = new HashSet<IntPtr>();

		private static bool assigning;

		public static void Run()
		{
			Planned.Clear();
			Plan plan = Plugin.Plan;
			if (!plan.Tiles.Values.Any((PlannedTile t) => t.Businesses.Count > 0))
			{
				return;
			}
			try
			{
				Apply(plan);
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)("Placing businesses failed: " + ex));
			}
		}

		private static void Apply(Plan plan)
		{
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Expected O, but got Unknown
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Expected O, but got Unknown
			//IL_031c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0323: Expected O, but got Unknown
			//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b4: Expected O, but got Unknown
			//IL_050e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0515: Expected O, but got Unknown
			//IL_0478: Unknown result type (might be due to invalid IL or missing references)
			//IL_047f: Expected O, but got Unknown
			Dictionary<string, AddressPreset> dictionary = new Dictionary<string, AddressPreset>(StringComparer.OrdinalIgnoreCase);
			Enumerator<AddressPreset> enumerator = Toolbox.Instance.allAddressPresets.GetEnumerator();
			while (enumerator.MoveNext())
			{
				AddressPreset current = enumerator.Current;
				if ((SoCustomComparison)(object)current != (SoCustomComparison)null)
				{
					dictionary[((Object)current).name] = current;
				}
			}
			Dictionary<IntPtr, List<NewAddress>> dictionary2 = new Dictionary<IntPtr, List<NewAddress>>();
			Enumerator<NewAddress> enumerator2 = CityData.Instance.addressDirectory.GetEnumerator();
			while (enumerator2.MoveNext())
			{
				NewAddress current2 = enumerator2.Current;
				if (!((Object)(object)((current2 != null) ? ((NewGameLocation)current2).building : null) == (Object)null) && !((SoCustomComparison)(object)current2.preset == (SoCustomComparison)null) && current2.preset.assignPurpose)
				{
					if (!dictionary2.TryGetValue(((Il2CppObjectBase)((NewGameLocation)current2).building).Pointer, out var value))
					{
						value = (dictionary2[((Il2CppObjectBase)((NewGameLocation)current2).building).Pointer] = new List<NewAddress>());
					}
					value.Add(current2);
				}
			}
			foreach (List<NewAddress> value4 in dictionary2.Values)
			{
				value4.Sort((NewAddress a, NewAddress b) => (Order(a) == Order(b)) ? a.id.CompareTo(b.id) : Order(a).CompareTo(Order(b)));
			}
			int num = 0;
			int num2 = 0;
			CityTile val = default(CityTile);
			bool flag = default(bool);
			foreach (KeyValuePair<(int, int), PlannedTile> tile in plan.Tiles)
			{
				tile.Deconstruct(out var key, out var value2);
				(int, int) tuple = key;
				int item = tuple.Item1;
				int item2 = tuple.Item2;
				PlannedTile plannedTile = value2;
				if (plannedTile.Businesses.Count == 0)
				{
					continue;
				}
				string text = $"tile R{plan.Height - 1 - item2} C{item}";
				if (!HighlanderSingleton<CityBoundaryAndTiles>.Instance.cityTiles.TryGetValue(new Vector2Int(item, item2), ref val) || (Object)(object)val.building == (Object)null || !dictionary2.TryGetValue(((Il2CppObjectBase)val.building).Pointer, out var value3))
				{
					ManualLogSource logger = Plugin.Logger;
					BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(51, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Businesses for ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": its building has no business units");
					}
					logger.LogWarning(val2);
					num2 += plannedTile.Businesses.Count;
					continue;
				}
				NewBuilding building = val.building;
				foreach (string business in plannedTile.Businesses)
				{
					BepInExWarningLogInterpolatedStringHandler val2;
					if (!dictionary.TryGetValue(business, out var preset))
					{
						ManualLogSource logger2 = Plugin.Logger;
						val2 = new BepInExWarningLogInterpolatedStringHandler(51, 2, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Businesses for ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": the game has no business called '");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(business);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("'");
						}
						logger2.LogWarning(val2);
						num2++;
						continue;
					}
					NewAddress val3 = ((IEnumerable<NewAddress>)value3).FirstOrDefault((Func<NewAddress, bool>)((NewAddress a) => !Planned.Contains(((Il2CppObjectBase)a).Pointer) && Fits(preset, a.preset)));
					if ((Object)(object)val3 == (Object)null)
					{
						ManualLogSource logger3 = Plugin.Logger;
						val2 = new BepInExWarningLogInterpolatedStringHandler(57, 3, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Businesses for ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)building.preset).name);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" has no free unit for ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(business);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("; left to the game");
						}
						logger3.LogWarning(val2);
						num2++;
						continue;
					}
					string text2 = WhyNot(preset, val3);
					if (text2 != null)
					{
						ManualLogSource logger4 = Plugin.Logger;
						val2 = new BepInExWarningLogInterpolatedStringHandler(63, 4, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Businesses for ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(business);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" can't go in ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)building.preset).name);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" (");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text2);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("); the unit is left to the game");
						}
						logger4.LogWarning(val2);
						num2++;
						continue;
					}
					Assign(val3, preset);
					Planned.Add(((Il2CppObjectBase)val3).Pointer);
					if ((SoCustomComparison)(object)val3.addressPreset == (SoCustomComparison)(object)preset)
					{
						num++;
						ManualLogSource logger5 = Plugin.Logger;
						BepInExInfoLogInterpolatedStringHandler val4 = new BepInExInfoLogInterpolatedStringHandler(16, 4, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>(business);
							((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" in ");
							((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>(((Object)building.preset).name);
							((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" at ");
							((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>(text);
							((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(", floor ");
							NewFloor floor = ((NewGameLocation)val3).floor;
							((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<int?>((floor != null) ? new int?(floor.floor) : ((int?)null));
						}
						logger5.LogInfo(val4);
						continue;
					}
					num2++;
					ManualLogSource logger6 = Plugin.Logger;
					val2 = new BepInExWarningLogInterpolatedStringHandler(46, 3, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Businesses for ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": asked for ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(business);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", the game made it ");
						BepInExWarningLogInterpolatedStringHandler obj = val2;
						AddressPreset addressPreset = val3.addressPreset;
						((BepInExLogInterpolatedStringHandler)obj).AppendFormatted<string>(((addressPreset != null) ? ((Object)addressPreset).name : null) ?? "nothing");
					}
					logger6.LogWarning(val2);
					if ((SoCustomComparison)(object)val3.addressPreset == (SoCustomComparison)null)
					{
						Planned.Remove(((Il2CppObjectBase)val3).Pointer);
					}
				}
			}
			Plugin.Logger.LogInfo((object)($"Planned businesses: {num} placed" + ((num2 > 0) ? $", {num2} left to the game (see warnings above)" : "")));
			static int Order(NewAddress a)
			{
				if (!((Object)(object)((NewGameLocation)a).floor == (Object)null))
				{
					if (((NewGameLocation)a).floor.floor < 0)
					{
						return 100 - ((NewGameLocation)a).floor.floor;
					}
					return ((NewGameLocation)a).floor.floor;
				}
				return 999;
			}
		}

		private static bool Fits(AddressPreset preset, LayoutConfiguration layout)
		{
			if ((SoCustomComparison)(object)layout == (SoCustomComparison)null)
			{
				return false;
			}
			Enumerator<LayoutConfiguration> enumerator = preset.compatible.GetEnumerator();
			while (enumerator.MoveNext())
			{
				LayoutConfiguration current = enumerator.Current;
				if ((SoCustomComparison)(object)current != (SoCustomComparison)null && ((Il2CppObjectBase)current).Pointer == ((Il2CppObjectBase)layout).Pointer)
				{
					return true;
				}
			}
			return false;
		}

		private static string WhyNot(AddressPreset preset, NewAddress unit)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			if (preset.disableThis)
			{
				return "switched off in the game";
			}
			if ((Object)(object)((NewGameLocation)unit).floor != (Object)null && ((float)((NewGameLocation)unit).floor.floor < preset.minMaxFloors.x || (float)((NewGameLocation)unit).floor.floor > preset.minMaxFloors.y))
			{
				return "not on that floor";
			}
			if (preset.limitToBuildings.Count > 0 && !preset.limitToBuildings.Contains(((NewGameLocation)unit).building.preset))
			{
				return "only in other buildings";
			}
			if (preset.hardSizeLimits && (((NewGameLocation)unit).nodes.Count < preset.fitsUnitSizeMin || ((NewGameLocation)unit).nodes.Count > preset.fitsUnitSizeMax))
			{
				return "unit is the wrong size";
			}
			Dictionary<AddressPreset, List<NewAddress>> addressTypeReference = CityData.Instance.addressTypeReference;
			if (addressTypeReference.ContainsKey(preset) && addressTypeReference[preset].Count >= preset.maxInstances)
			{
				return $"the city already has the most allowed, {preset.maxInstances}";
			}
			return null;
		}

		private static void Assign(NewAddress unit, AddressPreset preset)
		{
			List<AddressPreset> list = new List<AddressPreset>();
			Enumerator<AddressPreset> enumerator = Toolbox.Instance.allAddressPresets.GetEnumerator();
			while (enumerator.MoveNext())
			{
				AddressPreset current = enumerator.Current;
				if (!((SoCustomComparison)(object)current == (SoCustomComparison)null) && !(((Il2CppObjectBase)current).Pointer == ((Il2CppObjectBase)preset).Pointer) && !current.disableThis && Fits(current, unit.preset))
				{
					current.disableThis = true;
					list.Add(current);
				}
			}
			assigning = true;
			try
			{
				unit.CalculateLandValue();
				unit.AssignPurpose();
			}
			finally
			{
				assigning = false;
				foreach (AddressPreset item in list)
				{
					item.disableThis = false;
				}
			}
		}
	}
	internal class DecorChoice
	{
		public string Scheme;

		public string Floor;

		public string Walls;

		public string Ceiling;

		public string Style;

		public string Wood;

		public int? Grime;

		public Dictionary<string, string> Paint = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		public DecorChoice Over(DecorChoice fallback)
		{
			if (fallback == null)
			{
				return this;
			}
			DecorChoice decorChoice = new DecorChoice
			{
				Scheme = (Scheme ?? fallback.Scheme),
				Floor = (Floor ?? fallback.Floor),
				Walls = (Walls ?? fallback.Walls),
				Ceiling = (Ceiling ?? fallback.Ceiling),
				Style = (Style ?? fallback.Style),
				Wood = (Wood ?? fallback.Wood),
				Grime = (Grime ?? fallback.Grime)
			};
			foreach (KeyValuePair<string, string> item in fallback.Paint)
			{
				decorChoice.Paint[item.Key] = item.Value;
			}
			foreach (KeyValuePair<string, string> item2 in Paint)
			{
				decorChoice.Paint[item2.Key] = item2.Value;
			}
			return decorChoice;
		}
	}
	internal static class Decor
	{
		[HarmonyPatch(typeof(NewBuilding), "UpdateColourSchemeAndMaterials")]
		private static class BuildingDecorPatch
		{
			private static void Postfix(NewBuilding __instance)
			{
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				if (!Plugin.Active || (Object)(object)((__instance != null) ? __instance.cityTile : null) == (Object)null)
				{
					return;
				}
				Vector2Int cityCoord = __instance.cityTile.cityCoord;
				DecorChoice decorChoice = For(Plugin.Plan, ((Vector2Int)(ref cityCoord)).x, ((Vector2Int)(ref cityCoord)).y);
				if (decorChoice == null)
				{
					return;
				}
				try
				{
					DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(7, 3);
					BuildingPreset preset = __instance.preset;
					defaultInterpolatedStringHandler.AppendFormatted((preset != null) ? ((Object)preset).name : null);
					defaultInterpolatedStringHandler.AppendLiteral(" at R");
					defaultInterpolatedStringHandler.AppendFormatted(Plugin.Plan.Height - 1 - ((Vector2Int)(ref cityCoord)).y);
					defaultInterpolatedStringHandler.AppendLiteral(" C");
					defaultInterpolatedStringHandler.AppendFormatted(((Vector2Int)(ref cityCoord)).x);
					Apply(__instance, decorChoice, defaultInterpolatedStringHandler.ToStringAndClear());
				}
				catch (Exception ex)
				{
					Plugin.Logger.LogError((object)("Decor: " + ex));
				}
			}
		}

		[HarmonyPatch(typeof(NewRoom), "UpdateColourSchemeAndMaterials")]
		private static class RoomDecorPatch
		{
			private static void Postfix(NewRoom __instance)
			{
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_003b: Invalid comparison between Unknown and I4
				if (planned.Count == 0 || (Object)(object)((__instance != null) ? __instance.building : null) == (Object)null || (SoCustomComparison)(object)__instance.preset == (SoCustomComparison)null || (int)__instance.preset.decorSetting != 2 || !planned.TryGetValue(((Il2CppObjectBase)__instance.building).Pointer, out var value))
				{
					return;
				}
				NewBuilding building = __instance.building;
				if (!Game.Instance.allowEchelons || !building.preset.buildingFeaturesEchelonFloors || !((Object)(object)__instance.floor != (Object)null) || __instance.floor.floor < building.preset.echelonFloorStart)
				{
					bool flag = (Object)(object)InteriorCreator.Instance == (Object)null || !InteriorCreator.Instance.threadedInteriorCreationActive;
					if (value.Floor != null && (SoCustomComparison)(object)__instance.floorMaterial != (SoCustomComparison)(object)building.floorMaterial)
					{
						__instance.floorMatKey = building.floorMatKey;
						__instance.SetFloorMaterial(building.floorMaterial, (MaterialVariation)null, false, flag);
					}
					if (value.Walls != null && (SoCustomComparison)(object)__instance.defaultWallMaterial != (SoCustomComparison)(object)building.defaultWallMaterial)
					{
						__instance.defaultWallKey = building.defaultWallKey;
						__instance.SetWallMaterialDefault(building.defaultWallMaterial, (MaterialVariation)null, false, flag);
					}
					if (value.Ceiling != null && (SoCustomComparison)(object)__instance.ceilingMaterial != (SoCustomComparison)(object)building.ceilingMaterial)
					{
						__instance.ceilingMatKey = building.ceilingMatKey;
						__instance.SetCeilingMaterial(building.ceilingMaterial, (MaterialVariation)null, false, flag);
					}
				}
			}
		}

		[HarmonyPatch(typeof(MaterialsController), "GenerateMaterialKey")]
		private static class GrimePatch
		{
			private static void Postfix(NewRoom room, bool useGrubiness, NewBuilding building, MaterialKey __result)
			{
				//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00db: Unknown result type (might be due to invalid IL or missing references)
				//IL_015f: Unknown result type (might be due to invalid IL or missing references)
				if (!useGrubiness || __result == (MaterialKey)null || !Plugin.Active || (Object)(object)SessionData.Instance == (Object)null || SessionData.Instance.startedGame)
				{
					return;
				}
				NewBuilding val = building ?? ((room != null) ? room.building : null);
				if (!((Object)(object)((val != null) ? val.cityTile : null) == (Object)null) && (!((Object)(object)room != (Object)null) || !((Object)(object)room.gameLocation != (Object)null) || !room.gameLocation.isOutside) && (!((Object)(object)room != (Object)null) || !((SoCustomComparison)(object)val.preset != (SoCustomComparison)null) || !Game.Instance.allowEchelons || !val.preset.buildingFeaturesEchelonFloors || !((Object)(object)room.floor != (Object)null) || room.floor.floor < val.preset.echelonFloorStart))
				{
					Vector2Int cityCoord = val.cityTile.cityCoord;
					int? num = For(Plugin.Plan, ((Vector2Int)(ref cityCoord)).x, ((Vector2Int)(ref cityCoord)).y)?.Grime;
					if (num.HasValue)
					{
						__result.grubiness = (float)Mathf.Clamp(num.Value, 0, 10) / 10f;
					}
					else if ((Object)(object)room == (Object)null && ((SoCustomComparison)(object)val.preset == (SoCustomComparison)null || !val.preset.overrideGrubiness))
					{
						__result.grubiness = Mathf.Clamp01(1f - (float)val.cityTile.landValue * 0.25f);
					}
				}
			}
		}

		private static readonly Dictionary<IntPtr, DecorChoice> planned = new Dictionary<IntPtr, DecorChoice>();

		private static Dictionary<string, ColourSchemePreset> schemes;

		public static void Reset()
		{
			planned.Clear();
		}

		internal static DecorChoice For(Plan plan, int x, int y)
		{
			if (!plan.Tiles.ContainsKey((x, y)))
			{
				return null;
			}
			plan.TileDecor.TryGetValue((x, y), out var value);
			PlannedTile plannedTile = plan.Nearest(x, y);
			plan.DistrictDecor.TryGetValue(plannedTile.District.Key, out var value2);
			return value?.Over(value2) ?? value2;
		}

		private static ColourSchemePreset Scheme(string name)
		{
			if (schemes == null)
			{
				schemes = new Dictionary<string, ColourSchemePreset>(StringComparer.OrdinalIgnoreCase);
				foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<ColourSchemePreset>()))
				{
					ColourSchemePreset val = ((Il2CppObjectBase)item).TryCast<ColourSchemePreset>();
					if ((SoCustomComparison)(object)val != (SoCustomComparison)null && !schemes.ContainsKey(((Object)val).name))
					{
						schemes[((Object)val).name] = val;
					}
				}
			}
			if (!schemes.TryGetValue(name, out var value))
			{
				return null;
			}
			return value;
		}

		private static MaterialGroupPreset Material(string name, MaterialType type)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			Enumerator<MaterialGroupPreset> enumerator = Toolbox.Instance.allMaterialGroups.GetEnumerator();
			while (enumerator.MoveNext())
			{
				MaterialGroupPreset current = enumerator.Current;
				if ((SoCustomComparison)(object)current != (SoCustomComparison)null && current.materialType == type && string.Equals(((Object)current).name, name, StringComparison.OrdinalIgnoreCase))
				{
					return current;
				}
			}
			return null;
		}

		private static DesignStylePreset Style(string name)
		{
			Enumerator<DesignStylePreset> enumerator = Toolbox.Instance.allDesignStyles.GetEnumerator();
			while (enumerator.MoveNext())
			{
				DesignStylePreset current = enumerator.Current;
				if ((SoCustomComparison)(object)current != (SoCustomComparison)null && string.Equals(((Object)current).name, name, StringComparison.OrdinalIgnoreCase))
				{
					return current;
				}
			}
			return null;
		}

		private static void Apply(NewBuilding b, DecorChoice want, string where)
		{
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_05c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_05da: Unknown result type (might be due to invalid IL or missing references)
			DecorChoice decorChoice = new DecorChoice();
			List<string> problems = new List<string>();
			if (want.Style != null)
			{
				DesignStylePreset val = Style(want.Style);
				if ((SoCustomComparison)(object)val != (SoCustomComparison)null)
				{
					b.designStyle = val;
					decorChoice.Style = ((Object)val).name;
				}
				else
				{
					problems.Add("no design style '" + want.Style + "'");
				}
			}
			if (want.Scheme != null)
			{
				ColourSchemePreset val2 = Scheme(want.Scheme);
				if ((SoCustomComparison)(object)val2 != (SoCustomComparison)null)
				{
					b.colourScheme = val2;
					decorChoice.Scheme = ((Object)val2).name;
				}
				else
				{
					problems.Add("no colour scheme '" + want.Scheme + "'");
				}
			}
			if (want.Wood != null)
			{
				Color wood = default(Color);
				if (ColorUtility.TryParseHtmlString(want.Wood.StartsWith("#") ? want.Wood : ("#" + want.Wood), ref wood))
				{
					wood.a = 1f;
					b.wood = wood;
					decorChoice.Wood = want.Wood;
				}
				else
				{
					problems.Add("'" + want.Wood + "' isn't a colour like #5A3A22");
				}
			}
			MaterialGroupPreset val3 = Pick(want.Floor, (MaterialType)1);
			MaterialGroupPreset val4 = Pick(want.Walls, (MaterialType)0);
			MaterialGroupPreset val5 = Pick(want.Ceiling, (MaterialType)2);
			BuildingPreset preset = b.preset;
			object obj;
			if (preset == null)
			{
				obj = null;
			}
			else
			{
				AddressPreset lobbyPreset = preset.lobbyPreset;
				obj = ((lobbyPreset != null) ? lobbyPreset.roomConfig : null);
			}
			RoomClassPreset val6 = ((obj != null && b.preset.lobbyPreset.roomConfig.Count > 0) ? b.preset.lobbyPreset.roomConfig[0].roomClass : null);
			if (decorChoice.Style != null && (SoCustomComparison)(object)val6 != (SoCustomComparison)null)
			{
				float normalizedLandValue = Toolbox.Instance.GetNormalizedLandValue(b);
				string text = "decor" + b.buildingID;
				if (val3 == null)
				{
					val3 = Toolbox.Instance.SelectMaterial(val6, normalizedLandValue, b.designStyle, (MaterialType)1, ref text);
				}
				if (val4 == null)
				{
					val4 = Toolbox.Instance.SelectMaterial(val6, normalizedLandValue, b.designStyle, (MaterialType)0, ref text);
				}
				if (val5 == null)
				{
					val5 = Toolbox.Instance.SelectMaterial(val6, normalizedLandValue, b.designStyle, (MaterialType)2, ref text);
				}
			}
			if ((SoCustomComparison)(object)val3 != (SoCustomComparison)null)
			{
				b.floorMaterial = val3;
				if (want.Floor != null)
				{
					decorChoice.Floor = ((Object)val3).name;
				}
			}
			if ((SoCustomComparison)(object)val4 != (SoCustomComparison)null)
			{
				b.defaultWallMaterial = val4;
				if (want.Walls != null)
				{
					decorChoice.Walls = ((Object)val4).name;
				}
			}
			if ((SoCustomComparison)(object)val5 != (SoCustomComparison)null)
			{
				b.ceilingMaterial = val5;
				if (want.Ceiling != null)
				{
					decorChoice.Ceiling = ((Object)val5).name;
				}
			}
			int seed;
			if (decorChoice.Scheme != null || decorChoice.Wood != null || want.Paint.Count > 0 || want.Grime.HasValue || (SoCustomComparison)(object)val3 != (SoCustomComparison)null || (SoCustomComparison)(object)val4 != (SoCustomComparison)null || (SoCustomComparison)(object)val5 != (SoCustomComparison)null)
			{
				seed = b.buildingID * 7919;
				if ((SoCustomComparison)(object)b.floorMaterial != (SoCustomComparison)null)
				{
					b.floorMatKey = Key(b.floorMaterial, 1);
				}
				if ((SoCustomComparison)(object)b.defaultWallMaterial != (SoCustomComparison)null)
				{
					b.defaultWallKey = Key(b.defaultWallMaterial, 2);
				}
				if ((SoCustomComparison)(object)b.ceilingMaterial != (SoCustomComparison)null)
				{
					b.ceilingMatKey = Key(b.ceilingMaterial, 3);
				}
				int num = 0;
				Color val8 = default(Color);
				foreach (KeyValuePair<string, string> item in want.Paint)
				{
					item.Deconstruct(out var key, out var value);
					string text2 = key;
					string text3 = value;
					int num2 = text2.IndexOf('-');
					MaterialKey val7 = (MaterialKey)(((num2 > 0) ? text2.Substring(0, num2).ToLowerInvariant() : "") switch
					{
						"floor" => b.floorMatKey, 
						"walls" => b.defaultWallKey, 
						"ceiling" => b.ceilingMatKey, 
						_ => null, 
					});
					if (val7 == (MaterialKey)null || !ColorUtility.TryParseHtmlString(text3.StartsWith("#") ? text3 : ("#" + text3), ref val8))
					{
						problems.Add($"can't paint '{text2} {text3}'");
						continue;
					}
					val8.a = 1f;
					key = text2;
					int num3 = num2 + 1;
					value = key.Substring(num3, key.Length - num3).ToLowerInvariant();
					switch (value)
					{
					case "main":
						val7.mainColour = val8;
						break;
					case "c1":
						val7.colour1 = val8;
						break;
					case "c2":
						val7.colour2 = val8;
						break;
					case "c3":
						val7.colour3 = val8;
						break;
					default:
						problems.Add("'" + text2 + "' isn't main, c1, c2 or c3");
						continue;
					}
					num++;
				}
				if (num > 0)
				{
					decorChoice.Paint = new Dictionary<string, string>(want.Paint, StringComparer.OrdinalIgnoreCase);
				}
			}
			planned[((Il2CppObjectBase)b).Pointer] = decorChoice;
			Plugin.Logger.LogInfo((object)("Decor: " + where + " shared spaces" + ((decorChoice.Style != null) ? (", style " + decorChoice.Style) : "") + ((decorChoice.Scheme != null) ? (", colours " + decorChoice.Scheme) : "") + ((decorChoice.Floor != null) ? (", floor " + decorChoice.Floor) : "") + ((decorChoice.Walls != null) ? (", walls " + decorChoice.Walls) : "") + ((decorChoice.Ceiling != null) ? (", ceiling " + decorChoice.Ceiling) : "") + ((decorChoice.Wood != null) ? (", wood " + decorChoice.Wood) : "") + (want.Grime.HasValue ? $", grime {want.Grime} on every surface" : "") + ((decorChoice.Paint.Count > 0) ? (", painted " + string.Join(" ", decorChoice.Paint.Select((KeyValuePair<string, string> kv) => kv.Key + " " + kv.Value))) : "") + ((problems.Count > 0) ? (" (left to the game: " + string.Join("; ", problems) + ")") : "")));
			MaterialKey Key(MaterialGroupPreset m, int salt)
			{
				MaterialVariation val9 = ((m.variations.Count > 0) ? m.variations[Math.Abs(seed + salt) % m.variations.Count] : null);
				return MaterialsController.Instance.GenerateMaterialKey(val9, b.colourScheme, (NewRoom)null, true, b);
			}
			MaterialGroupPreset Pick(string name, MaterialType type)
			{
				//IL_0006: 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)
				if (name != null)
				{
					MaterialGroupPreset obj2 = Material(name, type);
					if ((SoCustomComparison)(object)obj2 == (SoCustomComparison)null)
					{
						problems.Add($"no {type} material '{name}'");
					}
					return obj2;
				}
				return null;
			}
		}
	}
	internal static class DecorIcons
	{
		private static bool done;

		internal static string Dir => Path.Combine(Paths.CachePath, "CityPlanner", "icons");

		public static void EnsureExported()
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			if (done)
			{
				return;
			}
			Toolbox instance = Toolbox.Instance;
			if (((instance != null) ? instance.allMaterialGroups : null) == null || Toolbox.Instance.allMaterialGroups.Count == 0)
			{
				return;
			}
			done = true;
			try
			{
				Directory.CreateDirectory(Dir);
				int num = 0;
				Enumerator<MaterialGroupPreset> enumerator = Toolbox.Instance.allMaterialGroups.GetEnumerator();
				while (enumerator.MoveNext())
				{
					MaterialGroupPreset current = enumerator.Current;
					if (!((Object)(object)((current != null) ? current.decorSprite : null) == (Object)null))
					{
						string path = Path.Combine(Dir, FileName(((Object)current).name));
						if (!File.Exists(path) && SavePng((Texture)(object)current.decorSprite.texture, current.decorSprite.textureRect, path, 96))
						{
							num++;
						}
					}
				}
				Plugin.Logger.LogInfo((object)("Decor icons ready in " + Dir + ((num > 0) ? $" ({num} drawn)" : "")));
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("Decor icons couldn't be drawn (the planner shows names instead): " + ex.Message));
			}
		}

		internal static string FileName(string material)
		{
			return string.Concat(string.Concat(material.Select(delegate(char c)
			{
				bool flag = char.IsLetterOrDigit(c);
				if (!flag)
				{
					bool flag2 = ((c == '-' || c == '_') ? true : false);
					flag = flag2;
				}
				return (!flag) ? '_' : c;
			})), ".png");
		}

		private static bool SavePng(Texture source, Rect region, string path, int size)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)source == (Object)null || ((Rect)(ref region)).width < 1f || ((Rect)(ref region)).height < 1f)
			{
				return false;
			}
			float num = Mathf.Min(1f, (float)size / Mathf.Max(((Rect)(ref region)).width, ((Rect)(ref region)).height));
			int num2 = Mathf.Max(1, Mathf.RoundToInt(((Rect)(ref region)).width * num));
			int num3 = Mathf.Max(1, Mathf.RoundToInt(((Rect)(ref region)).height * num));
			RenderTexture temporary = RenderTexture.GetTemporary(num2, num3, 0, (RenderTextureFormat)0);
			RenderTexture active = RenderTexture.active;
			try
			{
				Graphics.Blit(source, temporary, new Vector2(((Rect)(ref region)).width / (float)source.width, ((Rect)(ref region)).height / (float)source.height), new Vector2(((Rect)(ref region)).x / (float)source.width, ((Rect)(ref region)).y / (float)source.height));
				RenderTexture.active = temporary;
				Texture2D val = new Texture2D(num2, num3, (TextureFormat)4, false);
				val.ReadPixels(new Rect(0f, 0f, (float)num2, (float)num3), 0, 0);
				val.Apply();
				File.WriteAllBytes(path, Il2CppArrayBase<byte>.op_Implicit((Il2CppArrayBase<byte>)(object)ImageConversion.EncodeToPNG(val)));
				Object.Destroy((Object)(object)val);
				return true;
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
			}
		}
	}
	internal static class Echelons
	{
		[HarmonyPatch(typeof(EchelonsLaserScreenController), "Setup")]
		private static class LaserScreenPatch
		{
			private static bool Prefix(EchelonsLaserScreenController __instance, InteractableController newController)
			{
				object obj;
				if (newController == null)
				{
					obj = null;
				}
				else
				{
					Interactable interactable = newController.interactable;
					if (interactable == null)
					{
						obj = null;
					}
					else
					{
						NewNode node = interactable.node;
						if (node == null)
						{
							obj = null;
						}
						else
						{
							NewGameLocation gameLocation = node.gameLocation;
							if (gameLocation == null)
							{
								obj = null;
							}
							else
							{
								NewAddress thisAsAddress = gameLocation.thisAsAddress;
								obj = ((thisAsAddress != null) ? ((NewGameLocation)thisAsAddress).floor : null);
							}
						}
					}
				}
				NewFloor val = (NewFloor)obj;
				if ((Object)(object)val == (Object)null || val.isEchelons || (Object)(object)SessionData.Instance == (Object)null || SessionData.Instance.isFloorEdit)
				{
					return true;
				}
				NewBuilding building = newController.interactable.node.building;
				if ((SoCustomComparison)(object)((building != null) ? building.preset : null) == (SoCustomComparison)null || !building.preset.buildingFeaturesEchelonFloors || val.floor < building.preset.echelonFloorStart)
				{
					return true;
				}
				Object.Destroy((Object)(object)((Component)__instance).gameObject);
				return false;
			}
		}

		private static bool switchedOff;

		public static void Tick(CityConstructor constructor)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			if (!Plugin.Active || Plugin.Plan.Echelons)
			{
				Restore();
			}
			else if ((int)constructor.loadState >= 19)
			{
				Restore();
			}
			else if (!switchedOff && !((Object)(object)Game.Instance == (Object)null))
			{
				Game.Instance.allowEchelons = false;
				switchedOff = true;
				Plugin.Logger.LogInfo((object)"Echelons off for this city: the towers' top floors are built as ordinary floors");
			}
		}

		public static void Restore()
		{
			if (switchedOff)
			{
				if ((Object)(object)Game.Instance != (Object)null)
				{
					Game.Instance.allowEchelons = true;
				}
				switchedOff = false;
			}
		}
	}
	internal static class Home
	{
		internal enum Mode
		{
			Own,
			Buy
		}

		[HarmonyPatch(typeof(Player), "SetResidence")]
		private static class PlayerHomePatch
		{
			private static void Prefix(ref ResidenceController newHome)
			{
				if (swapPlayerHome && !((Object)(object)reserved == (Object)null) && !((Object)(object)newHome == (Object)null) && !(((Il2CppObjectBase)newHome).Pointer == ((Il2CppObjectBase)reserved).Pointer))
				{
					swapPlayerHome = false;
					newHome = reserved;
				}
			}
		}

		private static ResidenceController reserved;

		private static ResidencePreset original;

		private static ResidencePreset stand_in;

		private static bool own;

		private static bool swapPlayerHome;

		public static void Prepare()
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Expected O, but got Unknown
			Restore();
			PlannedHome plannedHome = Plugin.Plan?.Home;
			if (plannedHome == null)
			{
				return;
			}
			try
			{
				string text = $"R{plannedHome.Row} C{plannedHome.Col}";
				Plan plan = Plugin.Plan;
				Vector2Int val = default(Vector2Int);
				((Vector2Int)(ref val))..ctor(plannedHome.Col, plan.Height - 1 - plannedHome.Row);
				CityTile val2 = default(CityTile);
				bool flag = default(bool);
				if (!HighlanderSingleton<CityBoundaryAndTiles>.Instance.cityTiles.TryGetValue(val, ref val2) || (Object)(object)val2.building == (Object)null)
				{
					ManualLogSource logger = Plugin.Logger;
					BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(26, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Home: no building at tile ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(text);
					}
					logger.LogWarning(val3);
					return;
				}
				ResidenceController val4 = null;
				List<int> list = new List<int>();
				Enumerator<NewAddress> enumerator = CityData.Instance.addressDirectory.GetEnumerator();
				while (enumerator.MoveNext())
				{
					NewAddress current = enumerator.Current;
					if (!((Object)(object)((current != null) ? ((NewGameLocation)current).building : null) == (Object)null) && !(((Il2CppObjectBase)((NewGameLocation)current).building).Pointer != ((Il2CppObjectBase)val2.building).Pointer) && !((Object)(object)current.residence == (Object)null))
					{
						int residenceNumber = current.residence.GetResidenceNumber();
						if (residenceNumber > 0)
						{
							list.Add(residenceNumber);
						}
						if (residenceNumber == plannedHome.Number)
						{
							val4 = current.residence;
						}
					}
				}
				if ((Object)(object)val4 == (Object)null)
				{
					list.Sort();
					ManualLogSource logger2 = Plugin.Logger;
					DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(28, 3);
					defaultInterpolatedStringHandler.AppendLiteral("Home: ");
					BuildingPreset preset = val2.building.preset;
					defaultInterpolatedStringHandler.AppendFormatted((preset != null) ? ((Object)preset).name : null);
					defaultInterpolatedStringHandler.AppendLiteral(" at ");
					defaultInterpolatedStringHandler.AppendFormatted(text);
					defaultInterpolatedStringHandler.AppendLiteral(" has no apartment ");
					defaultInterpolatedStringHandler.AppendFormatted(plannedHome.Number);
					logger2.LogWarning((object)(defaultInterpolatedStringHandler.ToStringAndClear() + ((list.Count > 0) ? ("; it has " + string.Join(", ", list)) : "; it has no apartments")));
				}
				else if ((SoCustomComparison)(object)val4.preset == (SoCustomComparison)null || !val4.preset.habitable)
				{
					ManualLogSource logger3 = Plugin.Logger;
					BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(52, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Home: apartment ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<int>(plannedHome.Number);
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" at ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(text);
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" isn't a home anyone can live in");
					}
					logger3.LogWarning(val3);
				}
				else
				{
					original = val4.preset;
					stand_in = Object.Instantiate<ResidencePreset>(original);
					((Object)stand_in).name = ((Object)original).name;
					stand_in.habitable = false;
					val4.preset = stand_in;
					reserved = val4;
					own = (swapPlayerHome = Plugin.HomeMode.Value == Mode.Own);
					ManualLogSource logger4 = Plugin.Logger;
					DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(36, 3);
					defaultInterpolatedStringHandler.AppendLiteral("Home: apartment ");
					defaultInterpolatedStringHandler.AppendFormatted(plannedHome.Number);
					defaultInterpolatedStringHandler.AppendLiteral(" in ");
					BuildingPreset preset2 = val2.building.preset;
					defaultInterpolatedStringHandler.AppendFormatted((preset2 != null) ? ((Object)preset2).name : null);
					defaultInterpolatedStringHandler.AppendLiteral(" at ");
					defaultInterpolatedStringHandler.AppendFormatted(text);
					defaultInterpolatedStringHandler.AppendLiteral(" kept empty ");
					logger4.LogInfo((object)(defaultInterpolatedStringHandler.ToStringAndClear() + (own ? "for the player to own" : "and up for sale")));
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)("Home: reserving the apartment failed: " + ex));
				Restore();
			}
		}

		public static void Finish()
		{
			if ((Object)(object)reserved == (Object)null)
			{
				return;
			}
			Player instance = Player.Instance;
			bool flag = (Object)(object)((instance != null) ? ((Human)instance).home : null) != (Object)null && (Object)(object)reserved.address != (Object)null && ((Il2CppObjectBase)((Human)Player.Instance).home).Pointer == ((Il2CppObjectBase)reserved.address).Pointer;
			int num = 0;
			if ((Object)(object)reserved.address != (Object)null)
			{
				Enumerator<Human> enumerator = reserved.address.inhabitants.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Human current = enumerator.Current;
					if ((Object)(object)current != (Object)null)
					{
						IntPtr pointer = ((Il2CppObjectBase)current).Pointer;
						Player instance2 = Player.Instance;
						IntPtr? obj = ((instance2 != null) ? new IntPtr?(((Il2CppObjectBase)instance2).Pointer) : ((IntPtr?)null));
						if (pointer != obj)
						{
							num++;
						}
					}
				}
			}
			Plugin.Logger.LogInfo((object)($"Home: apartment {reserved.GetResidenceNumber()} has {num} residents besides the player" + (flag ? ", and is the player's home" : (own ? ", but the player didn't get it" : ", and goes up for sale"))));
			Restore();
		}

		public static void Restore()
		{
			if ((Object)(object)reserved != (Object)null && (SoCustomComparison)(object)original != (SoCustomComparison)null)
			{
				reserved.preset = original;
			}
			if ((SoCustomComparison)(object)stand_in != (SoCustomComparison)null)
			{
				Object.Destroy((Object)(object)stand_in);
			}
			reserved = null;
			original = (stand_in = null);
			own = (swapPlayerHome = false);
		}
	}
	internal static class Names
	{
		[HarmonyPatch(typeof(Company), "UpdateName")]
		private static class KeepName
		{
			private static void Postfix(Company __instance)
			{
				if (Planned.Count != 0 && !((Object)(object)((__instance != null) ? __instance.address : null) == (Object)null) && Planned.TryGetValue(((Il2CppObjectBase)__instance.address).Pointer, out var value))
				{
					Rename(__instance, value);
				}
			}
		}

		internal static readonly Dictionary<IntPtr, string> Planned = new Dictionary<IntPtr, string>();

		private static readonly HashSet<string> OfficeLayouts = new HashSet<string> { "Office", "OfficeHighrise", "IndustrialOffice" };

		public static void Apply()
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			Plan plan = Plugin.Plan;
			if (plan.BuildingNames.Count == 0 && plan.StreetNames.Count == 0)
			{
				return;
			}
			int num = 0;
			int num2 = 0;
			List<string> list = new List<string>();
			string value;
			CityTile val = default(CityTile);
			foreach (KeyValuePair<(int, int), string> buildingName in plan.BuildingNames)
			{
				buildingName.Deconstruct(out var key, out value);
				(int, int) tuple = key;
				int item = tuple.Item1;
				int item2 = tuple.Item2;
				string playerEditedBuildingName = value;
				if (!HighlanderSingleton<CityBoundaryAndTiles>.Instance.cityTiles.TryGetValue(new Vector2Int(item, item2), ref val) || (Object)(object)val.building == (Object)null)
				{
					list.Add($"building at R{plan.Height - 1 - item2} C{item}");
				}
				else
				{
					val.building.isPlayerEditedName = true;
					val.building.playerEditedBuildingName = playerEditedBuildingName;
					num++;
				}
			}
			if (plan.StreetNames.Count > 0)
			{
				Dictionary<(int, int), StreetController> dictionary = new Dictionary<(int, int), StreetController>();
				Enumerator<StreetController> enumerator2 = CityData.Instance.streetDirectory.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					StreetController current = enumerator2.Current;
					if ((Object)(object)current == (Object)null)
					{
						continue;
					}
					Enumerator<NewTile> enumerator3 = current.tiles.GetEnumerator();
					while (enumerator3.MoveNext())
					{
						NewTile current2 = enumerator3.Current;
						if (current2 != null)
						{
							Vector3Int globalTileCoord = current2.globalTileCoord;
							if (((Vector3Int)(ref globalTileCoord)).z == 0)
							{
								globalTileCoord = current2.globalTileCoord;
								int x = ((Vector3Int)(ref globalTileCoord)).x;
								globalTileCoord = current2.globalTileCoord;
								dictionary[(x, ((Vector3Int)(ref globalTileCoord)).y)] = current;
							}
						}
					}
				}
				int tileMultiplier = CityControls.Instance.tileMultiplier;
				Dictionary<StreetController, string> dictionary2 = new Dictionary<StreetController, string>();
				foreach (KeyValuePair<Gap, string> streetName in plan.StreetNames)
				{
					streetName.Deconstruct(out var key2, out value);
					Gap value2 = key2;
					string value3 = value;
					(int, int)[] obj = ((!value2.Vertical) ? new(int, int)[2]
					{
						(value2.X * tileMultiplier + tileMultiplier / 2, value2.Y * tileMultiplier + tileMultiplier - 1),
						(value2.X * tileMultiplier + tileMultiplier / 2, (value2.Y + 1) * tileMultiplier)
					} : new(int, int)[2]
					{
						(value2.X * tileMultiplier + tileMultiplier - 1, value2.Y * tileMultiplier + tileMultiplier / 2),
						((value2.X + 1) * tileMultiplier, value2.Y * tileMultiplier + tileMultiplier / 2)
					});
					StreetController value4 = null;
					(int, int)[] array = obj;
					foreach ((int, int) key3 in array)
					{
						if (dictionary.TryGetValue(key3, out value4))
						{
							break;
						}
					}
					if ((Object)(object)value4 == (Object)null)
					{
						list.Add($"street at {value2}");
					}
					else
					{
						dictionary2[value4] = value3;
					}
				}
				foreach (KeyValuePair<StreetController, string> item3 in dictionary2)
				{
					item3.Deconstruct(out var key4, out value);
					StreetController obj2 = key4;
					string playerEditedStreetName = value;
					obj2.isPlayerEditedName = true;
					obj2.playerEditedStreetName = playerEditedStreetName;
					num2++;
				}
			}
			Plugin.Logger.LogInfo((object)($"Names: {num} buildings and {num2} streets named" + ((list.Count > 0) ? ("; nothing to name at " + string.Join(", ", list)) : "")));
		}

		private static void Rename(Company company, string name)
		{
			company.name = name;
			company.shortName = name;
			company.nameAltTags?.Clear();
			((Object)company.address).name = name;
			((Object)((Component)company.address).transform).name = name;
		}

		public static void ApplyUnits()
		{
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			Plan plan = Plugin.Plan;
			Planned.Clear();
			if (plan.UnitNames.Count == 0)
			{
				return;
			}
			int num = 0;
			List<string> list = new List<string>();
			Dictionary<IntPtr, List<NewAddress>> dictionary = new Dictionary<IntPtr, List<NewAddress>>();
			Enumerator<NewAddress> enumerator = CityData.Instance.addressDirectory.GetEnumerator();
			while (enumerator.MoveNext())
			{
				NewAddress current = enumerator.Current;
				if (!((Object)(object)((current != null) ? ((NewGameLocation)current).building : null) == (Object)null) && current.company != null && !((SoCustomComparison)(object)current.company.preset == (SoCustomComparison)null) && !current.company.preset.isSelfEmployed)
				{
					if (!dictionary.TryGetValue(((Il2CppObjectBase)((NewGameLocation)current).building).Pointer, out var value))
					{
						value = (dictionary[((Il2CppObjectBase)((NewGameLocation)current).building).Pointer] = new List<NewAddress>());
					}
					value.Add(current);
				}
			}
			foreach (List<NewAddress> value5 in dictionary.Values)
			{
				value5.Sort((NewAddress a, NewAddress b) => (Order(a) == Order(b)) ? a.id.CompareTo(b.id) : Order(a).CompareTo(Order(b)));
			}
			CityTile val = default(CityTile);
			foreach (KeyValuePair<(int, int), List<(string, string)>> unitName in plan.UnitNames)
			{
				unitName.Deconstruct(out var key, out var value2);
				(int, int) tuple = key;
				int item = tuple.Item1;
				int item2 = tuple.Item2;
				List<(string, string)> list3 = value2;
				string value3 = $"R{plan.Height - 1 - item2} C{item}";
				List<NewAddress> value4 = null;
				if (HighlanderSingleton<CityBoundaryAndTiles>.Instance.cityTiles.TryGetValue(new Vector2Int(item, item2), ref val) && (Object)(object)val.building != (Object)null)
				{
					dictionary.TryGetValue(((Il2CppObjectBase)val.building).Pointer, out value4);
				}
				HashSet<IntPtr> used = new HashSet<IntPtr>();
				foreach (var item4 in list3)
				{
					string what = item4.Item1;
					string item3 = item4.Item2;
					NewAddress val2 = null;
					if (value4 != null)
					{
						if (what == "Office")
						{
							val2 = ((IEnumerable<NewAddress>)value4).FirstOrDefault((Func<NewAddress, bool>)((NewAddress a) => Free(a) && (SoCustomComparison)(object)a.preset != (SoCustomComparison)null && OfficeLayouts.Contains(((Object)a.preset).name)));
						}
						else
						{
							bool flag;
							switch (what)
							{
							case "Eatery":
							case "Retail":
							case "Den":
								flag = true;
								break;
							default:
								flag = false;
								break;
							}
							val2 = ((!flag) ? (((IEnumerable<NewAddress>)value4).FirstOrDefault((Func<NewAddress, bool>)delegate(NewAddress a)
							{
								if (Free(a))
								{
									AddressPreset addressPreset = a.addressPreset;
									if (((addressPreset != null) ? ((Object)addressPreset).name : null) == what)
									{
										return Businesses.Planned.Contains(((Il2CppObjectBase)a).Pointer);
									}
								}
								return false;
							}) ?? ((IEnumerable<NewAddress>)value4).FirstOrDefault((Func<NewAddress, bool>)delegate(NewAddress a)
							{
								if (Free(a))
								{
									AddressPreset addressPreset = a.addressPreset;
									return ((addressPreset != null) ? ((Object)addressPreset).name : null) == what;
								}
								return false;
							})) : ((IEnumerable<NewAddress>)value4).FirstOrDefault((Func<NewAddress, bool>)delegate(NewAddress a)
							{
								if (Free(a))
								{
									LayoutConfiguration preset = a.preset;
									if (((preset != null) ? ((Object)preset).name : null) == what)
									{
										return !Businesses.Planned.Contains(((Il2CppObjectBase)a).Pointer);
									}
								}
								return false;
							}));
						}
					}
					if ((Object)(object)val2 == (Object)null)
					{
						list.Add($"{what} '{item3}' at {value3}");
					}
					else
					{
						used.Add(((Il2CppObjectBase)val2).Pointer);
						Planned[((Il2CppObjectBase)val2).Pointer] = item3;
						Rename(val2.company, item3);
						num++;
					}
				}
				bool Free(NewAddress a)
				{
					return !used.Contains(((Il2CppObjectBase)a).Pointer);
				}
			}
			Plugin.Logger.LogInfo((object)($"Names: {num} businesses and offices named" + ((list.Count > 0) ? ("; none to name for " + string.Join(", ", list)) : "")));
			static int Order(NewAddress a)
			{
				if (!((Object)(object)((NewGameLocation)a).floor == (Object)null))
				{
					if (((NewGameLocation)a).floor.floor < 0)
					{
						return 100 - ((NewGameLocation)a).floor.floor;
					}
					return ((NewGameLocation)a).floor.floor;
				}
				return 999;
			}
		}
	}
	internal class PlannedDistrict
	{
		public char Key;

		public string Name;

		public string Type;

		public LandValue LandValue;

		public Density Density;
	}
	internal enum StreetKind
	{
		Alley = 1,
		Back,
		Main
	}
	internal readonly record struct Gap(bool Vertical, int X, int Y);
	internal class PlannedTile
	{
		public PlannedDistrict District;

		public string Building;

		public Direction? Facing;

		public readonly List<string> Businesses = new List<string>();
	}
	internal record PlannedHome(int Row, int Col, int Number);
	internal class Plan
	{
		public int Width;

		public int Height;

		public float Population = 1f;

		public bool Echelons = true;

		public readonly Dictionary<char, PlannedDistrict> Districts = new Dictionary<char, PlannedDistrict>();

		public readonly Dictionary<(int x, int y), PlannedTile> Tiles = new Dictionary<(int, int), PlannedTile>();

		public readonly Dictionary<Gap, StreetKind> Streets = new Dictionary<Gap, StreetKind>();

		public readonly HashSet<Gap> DeadEnds = new HashSet<Gap>();

		public PlannedHome Home;

		public readonly Dictionary<(int x, int y), string> BuildingNames = new Dictionary<(int, int), string>();

		public readonly Dictionary<Gap, string> StreetNames = new Dictionary<Gap, string>();

		public readonly Dictionary<(int x, int y), List<(string What, string Name)>> UnitNames = new Dictionary<(int, int), List<(string, string)>>();

		public readonly Dictionary<char, DecorChoice> DistrictDecor = new Dictionary<char, DecorChoice>();

		public readonly Dictionary<(int x, int y), DecorChoice> TileDecor = new Dictionary<(int, int), DecorChoice>();

		private static readonly Dictionary<string, string> BusinessNames = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
		{
			["Bar"] = "Bar",
			["FastFood"] = "FastFood",
			["ChineseEatery"] = "ChineseEatery",
			["Chinese"] = "ChineseEatery",
			["AsianRestaurant"] = "ChineseEatery",
			["Restaurant"] = "ChineseEatery",
			["Chemist"] = "Chemist",
			["Pharmacy"] = "Chemist",
			["Launderette"] = "Launderette",
			["Laundry"] = "Launderette",
			["HardwareStore"] = "HardwareStore",
			["Hardware"] = "HardwareStore",
			["PawnShop"] = "PawnShop",
			["Pawn"] = "PawnShop",
			["Supermarket"] = "Supermarket",
			["SyncClinic"] = "SyncClinic",
			["GamblingDen"] = "GamblingDen",
			["LoanShark"] = "LoanShark",
			["BlackmarketTrader"] = "BlackmarketTrader",
			["BlackMarket"] = "BlackmarketTrader",
			["BlackmarketSyncClinic"] = "BlackmarketSyncClinic",
			["WeaponsDealer"] = "WeaponsDealer",
			["Slum"] = "Slum",
			["Squat"] = "Slum",
			["EmptyDen"] = "EmptyDen",
			["Empty"] = "EmptyDen"
		};

		private static readonly Dictionary<string, string> UnitKinds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
		{
			["Eatery"] = "Eatery",
			["Retail"] = "Retail",
			["Shop"] = "Retail",
			["Den"] = "Den",
			["Office"] = "Office",
			["Offices"] = "Office"
		};

		public static Plan Load(string path, out string error)
		{
			error = null;
			if (!File.Exists(path))
			{
				error = "no plan file at " + path;
				return null;
			}
			return Parse(File.ReadAllLines(path), out error);
		}

		public static Plan Parse(IEnumerable<string> lines, out string error)
		{
			//IL_0380: Unknown result type (might be due to invalid IL or missing references)
			//IL_0385: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			error = null;
			Plan plan = new Plan();
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			List<string[]> list = new List<string[]>();
			List<string> list2 = new List<string>();
			List<string> list3 = new List<string>();
			string text = null;
			List<string> list4 = new List<string>();
			List<string> list5 = new List<string>();
			string text2 = "";
			foreach (string line in lines)
			{
				string text3 = line.Trim();
				if (text3.Length == 0 || text3.StartsWith("#"))
				{
					continue;
				}
				if (text3.StartsWith("[") && text3.EndsWith("]"))
				{
					string text4 = text3;
					text2 = text4.Substring(1, text4.Length - 1 - 1).Trim().ToLowerInvariant();
					continue;
				}
				switch (text2)
				{
				case "city":
					var (text5, text6) = KeyValue(text3);
					if (text5.Equals("Size", StringComparison.OrdinalIgnoreCase))
					{
						string[] array2 = text6.ToLowerInvariant().Split('x');
						int.TryParse(array2[0], out plan.Width);
						if (array2.Length > 1)
						{
							int.TryParse(array2[1], out plan.Height);
						}
					}
					else if (text5.Equals("Population", StringComparison.OrdinalIgnoreCase))
					{
						float.TryParse(text6, NumberStyles.Float, CultureInfo.InvariantCulture, out plan.Population);
					}
					else if (text5.Equals("Echelons", StringComparison.OrdinalIgnoreCase))
					{
						plan.Echelons = !text6.Equals("off", StringComparison.OrdinalIgnoreCase) && !text6.Equals("false", StringComparison.OrdinalIgnoreCase) && !text6.Equals("no", StringComparison.OrdinalIgnoreCase);
					}
					break;
				case "districts":
				{
					(string, string) tuple2 = KeyValue(text3);
					string item3 = tuple2.Item1;
					string[] array = tuple2.Item2.Split('|');
					if (item3.Length != 1 || array.Length < 4)
					{
						throw new FormatException("bad district line: " + text3);
					}
					plan.Districts[item3[0]] = new PlannedDistrict
					{
						Key = item3[0],
						Name = array[0].Trim(),
						Type = array[1].Trim(),
						LandValue = Enum.Parse<LandValue>(array[2].Trim(), ignoreCase: true),
						Density = Enum.Parse<Density>(array[3].Trim(), ignoreCase: true)
					};
					break;
				}
				case "buildings":
				{
					(string, string) tuple = KeyValue(text3);
					string item = tuple.Item1;
					string item2 = tuple.Item2;
					dictionary[item] = item2;
					break;
				}
				case "map":
					list.Add(text3.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries));
					break;
				case "streets":
					list2.Add(text3);
					break;
				case "businesses":
					list3.Add(text3);
					break;
				case "home":
					text = text3;
					break;
				case "decor":
					list4.Add(text3);
					break;
				case "names":
					list5.Add(text3);
					break;
				}
			}
			if (plan.Width < 5 || plan.Height < 5)
			{
				error = "missing or bad Size";
				return null;
			}
			if (list.Count != plan.Height - 2)
			{
				error = $"map has {list.Count} rows, a {plan.Width}x{plan.Height} city needs {plan.Height - 2}";
				return null;
			}
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].Length != plan.Width - 2)
				{
					error = $"map row {i + 1} has {list[i].Length} cells, needs {plan.Width - 2}";
					return null;
				}
				for (int j = 0; j < list[i].Length; j++)
				{
					string[] array3 = list[i][j].Split(':');
					if (array3.Length != 2 || array3[0].Length != 1 || !plan.Districts.TryGetValue(array3[0][0], out var value))
					{
						error = $"map row {i + 1}, column {j + 1}: '{list[i][j]}' isn't District:Building with a known district";
						return null;
					}
					string text7 = array3[1];
					Direction? facing = null;
					int num = text7.IndexOf('/');
					if (num >= 0)
					{
						string text8 = text7;
						int num2 = num + 1;
						facing = text8.Substring(num2, text8.Length - num2).ToUpperInvariant() switch
						{
							"N" => (Direction)2, 
							"E" => (Direction)3, 
							"S" => (Direction)0, 
							"W" => (Direction)1, 
							_ => null, 
						};
						if (!facing.HasValue)
						{
							error = $"map row {i + 1}, column {j + 1}: facing must be /N, /E, /S or /W in '{list[i][j]}'";
							return null;
						}
						text7 = text7.Substring(0, num);
					}
					string value2 = null;
					if (text7 != "?" && !dictionary.TryGetValue(text7, out value2))
					{
						error = $"map row {i + 1}, column {j + 1}: unknown building code '{text7}'";
						return null;
					}
					plan.Tiles[(j + 1, plan.Height - 2 - i)] = new PlannedTile
					{
						District = value,
						Building = value2,
						Facing = facing
					};
				}
			}
			foreach (string item4 in list2)
			{
				if (!plan.ParseStreetLine(item4, out error))
				{
					error = "[Streets] '" + item4 + "': " + error;
					return null;
				}
			}
			if (text != null && !plan.ParseHomeLine(text, out error))
			{
				error = "[Home] '" + text + "': " + error;
				return null;
			}
			foreach (string item5 in list5)
			{
				if (!plan.ParseNameLine(item5, out error))
				{
					error = "[Names] '" + item5 + "': " + error;
					return null;
				}
			}
			foreach (string item6 in list4)
			{
				if (!plan.ParseDecorLine(item6, out error))
				{
					error = "[Decor] '" + item6 + "': " + error;
					return null;
				}
			}
			foreach (string item7 in list3)
			{
				if (!plan.ParseBusinessLine(item7, out error))
				{
					error = "[Businesses] '" + item7 + "': " + error;
					return null;
				}
			}
			return plan;
		}

		private bool ParseNameLine(string line, out string error)
		{
			error = null;
			(string, string) tuple = KeyValue(line);
			string item = tuple.Item1;
			string text = tuple.Item2.Trim().Trim('"').Trim();
			if (text.Length == 0)
			{
				error = "needs a name after =";
				return false;
			}
			(int, int)? tuple2 = null;
			(int, int)? tuple3 = null;
			string text2 = null;
			string text3 = null;
			string[] array = item.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string text4 in array)
			{
				string text5 = text4.ToUpperInvariant();
				if (text5.StartsWith("R") && TryRange(text5, 'R', out var range))
				{
					tuple2 = range;
					continue;
				}
				if (text5.StartsWith("C") && TryRange(text5, 'C', out var range2))
				{
					tuple3 = range2;
					continue;
				}
				bool flag;
				switch (text5)
				{
				case "N":
				case "E":
				case "S":
				case "W":
					flag = true;
					break;
				default:
					flag = false;
					break;
				}
				if (flag)
				{
					text2 = text5;
					continue;
				}
				if (UnitKinds.TryGetValue(text4, out var value))
				{
					text3 = value;
					continue;
				}
				if (BusinessNames.TryGetValue(text4, out var value2))
				{
					text3 = value2;
					continue;
				}
				error = "don't understand '" + text4 + "' (use R<row> C<column>, a side N, E, S or W for a street, or a business, Eatery, Shop, Den or Offices)";
				return false;
			}
			if (!tuple2.HasValue || !tuple3.HasValue)
			{
				error = "needs a row and a column, like R3 C4";
				return false;
			}
			var (num, num2) = tuple2.Value;
			var (num3, num4) = tuple3.Value;
			if (num < 1 || num2 > Height - 2 || num3 < 1 || num4 > Width - 2)
			{
				error = $"outside the map (rows 1-{Height - 2}, columns 1-{Width - 2})";
				return false;
			}
			if (text3 != null)
			{
				if (text2 != null || num != num2 || num3 != num4)
				{
					error = "a business or office name goes on one tile, with no side";
					return false;
				}
				(int, int) key = (num3, Height - 1 - num);
				if (!UnitNames.TryGetValue(key, out List<(string, string)> value3))
				{
					value3 = (UnitNames[key] = new List<(string, string)>());
				}
				array = ((text3 == "Office") ? text.Split(',') : new string[1] { text });
				foreach (string text6 in array)
				{
					if (text6.Trim().Length > 0)
					{
						value3.Add((text3, text6.Trim()));
					}
				}
				return true;
			}
			if (text2 == null)
			{
				if (num != num2 || num3 != num4)
				{
					error = "a building name goes on one tile (add a side, N, E, S or W, to name a street)";
					return false;
				}
				BuildingNames[(num3, Height - 1 - num)] = text;
				return true;
			}
			for (int j = num; j <= num2; j++)
			{
				for (int k = num3; k <= num4; k++)
				{
					StreetNames[GapBeside(j, k, text2)] = text;
				}
			}
			return true;
		}

		private bool ParseDecorLine(string line, out string error)
		{
			error = null;
			var (text, text2) = KeyValue(line);
			DecorChoice value;
			if (text.Length == 1 && Districts.ContainsKey(text[0]))
			{
				if (!DistrictDecor.TryGetValue(text[0], out value))
				{
					value = (DistrictDecor[text[0]] = new DecorChoice());
				}
			}
			else
			{
				Match match = Regex.Match(text, "^R(\\d+)\\s+C(\\d+)$", RegexOptions.IgnoreCase);
				if (!match.Success)
				{
					error = "start with a district letter or a tile like R3 C4";
					return false;
				}
				int num = int.Parse(match.Groups[1].Value);
				int num2 = int.Parse(match.Groups[2].Value);
				if (num < 1 || num > Height - 2 || num2 < 1 || num2 > Width - 2)
				{
					error = $"needs a tile inside the map (R1-R{Height - 2} C1-C{Width - 2})";
					return false;
				}
				(int, int) key = (num2, Height - 1 - num);
				if (!TileDecor.TryGetValue(key, out value))
				{
					value = (TileDecor[key] = new DecorChoice());
				}
			}
			string[] array = text2.Split(',', StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text3 = array[i].Trim();
				int num3 = text3.IndexOf(' ');
				if (num3 < 0)
				{
					error = "'" + text3 + "' needs a part and a name, like 'floor MarbleFloor'";
					return false;
				}
				string text4 = text3;
				int num4 = num3 + 1;
				string text5 = text4.Substring(num4, text4.Length - num4).Trim();
				string text6 = text3.Substring(0, num3).ToLowerInvariant();
				if (Regex.IsMatch(text6, "^(floor|walls|ceiling)-(main|c1|c2|c3)$"))
				{
					value.Paint[text6] = text5;
					continue;
				}
				switch (text6)
				{
				case "colors":
				case "scheme":
				case "colours":
					value.Scheme = text5;
					break;
				case "floor":
					value.Floor = text5;
					break;
				case "walls":
				case "wall":
					value.Walls = text5;
					break;
				case "ceiling":
					value.Ceiling = text5;
					break;
				case "style":
					value.Style = text5;
					break;
				case "wood":
					value.Wood = text5;
					break;
				case "grime":
				{
					if (!int.TryParse(text5, out var result) || result < 0 || result > 10)
					{
						error = "grime is a number from 0 (spotless) to 10 (filthy)";
						return false;
					}
					value.Grime = result;
					break;
				}
				default:
					error = "'" + text3.Substring(0, num3) + "' isn't scheme, floor, walls, ceiling, style, wood or grime";
					return false;
				}
			}
			return true;
		}

		private bool ParseHomeLine(string line, out string error)
		{
			error = null;
			Match match = Regex.Match(line, "^\\s*Apartment\\s*=\\s*R(\\d+)\\s+C(\\d+)\\s+(\\d+)\\s*$", RegexOptions.IgnoreCase);
			if (!match.Success)
			{
				error = "write it as Apartment = R<row> C<column> <apartment number>, e.g. Apartment = R3 C4 1701";
				return false;
			}
			int num = int.Parse(match.Groups[1].Value);
			int num2 = int.Parse(match.Groups[2].Value);
			int number = int.Parse(match.Groups[3].Value);
			if (num < 1 || num > Height - 2 || num2 < 1 || num2 > Width - 2)
			{
				error = $"needs a tile inside the map (R1-R{Height - 2} C1-C{Width - 2})";
				return false;
			}
			Home = new PlannedHome(num, num2, number);
			return true;
		}

		private bool ParseBusinessLine(string line, out string error)
		{
			error = null;
			(string, string) tuple = KeyValue(line);
			string item = tuple.Item1;
			string item2 = tuple.Item2;
			int num = 0;
			int num2 = 0;
			string[] array = item.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string text in array)
			{
				string text2 = text.ToUpperInvariant();
				if (text2.StartsWith("R"))
				{
					string text3 = text2;
					if (int.TryParse(text3.Substring(1, text3.Length - 1), out var result))
					{
						num = result;
						continue;
					}
				}
				if (text2.StartsWith("C"))
				{
					string text3 = text2;
					if (int.TryParse(text3.Substring(1, text3.Length - 1), out var result2))
					{
						num2 = result2;
						continue;
					}
				}
				error = "don't understand '" + text + "' (use R<row> C<column>)";
				return false;
			}
			if (num < 1 || num > Height - 2 || num2 < 1 || num2 > Width - 2)
			{
				error = $"needs a tile inside the map (R1-R{Height - 2} C1-C{Width - 2})";
				return false;
			}
			PlannedTile plannedTile = Tiles[(num2, Height - 1 - num)];
			plannedTile.Businesses.Clear();
			array = item2.Split(',', StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text4 = array[i].Trim();
				if (text4.Length != 0)
				{
					plannedTile.Businesses.Add(BusinessNames.TryGetValue(text4.Replace(" ", ""), out var value) ? value : text4);
				}
			}
			return true;
		}

		private bool ParseStreetLine(string line, out string error)
		{
			error = null;
			(string, string) tuple = KeyValue(line);
			string item = tuple.Item1;
			string item2 = tuple.Item2;
			bool flag = false;
			StreetKind value;
			switch (item2.ToLowerInvariant())
			{
			case "main":
			case "road":
			case "street":
				value = StreetKind.Main;
				break;
			case "back":
			case "backstreet":
			case "back street":
				value = StreetKind.Back;
				break;
			case "alley":
				value = StreetKind.Alley;
				break;
			case "dead end":
			case "dead-end":
			case "deadend":
				value = StreetKind.Alley;
				flag = true;
				break;
			default:
				error = "the type must be main, back, alley or deadend";
				return false;
			}
			(int, int)? tuple2 = null;
			(int, int)? tuple3 = null;
			string text = null;
			string[] array = item.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string text2 in array)
			{
				string text3 = text2.ToUpperInvariant();
				if (text3.StartsWith("R") && TryRange(text3, 'R', out var range))
				{
					tuple2 = range;
					continue;
				}
				if (text3.StartsWith("C") && TryRange(text3, 'C', out var range2))
				{
					tuple3 = range2;
					continue;
				}
				bool flag2;
				switch (text3)
				{
				case "N":
				case "E":
				case "S":
				case "W":
				case "EDGE":
				case "INSIDE":
					flag2 = true;
					break;
				default:
					flag2 = false;
					break;
				}
				if (flag2)
				{
					text = text3;
					continue;
				}
				error = "don't understand '" + text2 + "' (use R<row>, C<column> and N, E, S, W, edge or inside)";
				return false;
			}
			if (!tuple2.HasValue || !tuple3.HasValue || text == null)
			{
				error = "needs rows (R3 or R3-R5), columns (C1 or C1-C4) and a side (N, E, S, W, edge or inside)";
				return false;
			}
			var (num, num2) = tuple2.Value;
			var (num3, num4) = tuple3.Value;
			if (num < 1 || num2 > Height - 2 || num3 < 1 || num4 > Width - 2)
			{
				error = $"outside the map (rows 1-{Height - 2}, columns 1-{Width - 2})";
				return false;
			}
			for (int j = num; j <= num2; j++)
			{
				for (int k = num3; k <= num4; k++)
				{
					array = ((text == "EDGE") ? new string[4]
					{
						(j == num) ? "N" : null,
						(j == num2) ? "S" : null,
						(k == num3) ? "W" : null,
						(k == num4) ? "E" : null
					} : ((!(text == "INSIDE")) ? new string[1] { text } : new string[2]
					{
						(j < num2) ? "S" : null,
						(k < num4) ? "E" : null
					}));
					array = array;
					foreach (string text4 in array)
					{
						if (text4 != null)
						{
							Gap gap = GapBeside(j, k, text4);
							Streets[gap] = value;
							if (flag)
							{
								DeadEnds.Add(gap);
							}
							else
							{
								DeadEnds.Remove(gap);
							}
						}
					}
				}
			}
			return true;
		}

		public Gap GapBeside(int row, int col, string side)
		{
			int num = Height - 1 - row;
			return side switch
			{
				"N" => new Gap(Vertical: false, col, num), 
				"S" => new Gap(Vertical: false, col, num - 1), 
				"E" => new Gap(Vertical: true, col, num), 
				_ => new Gap(Vertical: true, col - 1, num), 
			};
		}

		private static bool TryRange(string token, char letter, out (int, int) range)
		{
			range = default((int, int));
			string[] array = token.Split('-');
			if (array.Length > 2)
			{
				return false;
			}
			if (!int.TryParse(array[0].TrimStart(letter), out var result))
			{
				return false;
			}
			int result2 = result;
			if (array.Length == 2 && !int.TryParse(array[1].TrimStart(letter), out result2))
			{
				return false;
			}
			range = (Math.Min(result, result2), Math.Max(result, result2));
			return true;
		}

		private static (string, string) KeyValue(string line)
		{
			int num = line.IndexOf('=');
			if (num >= 0)
			{
				string item = line.Substring(0, num).Trim();
				int num2 = num + 1;
				return (item, line.Substring(num2, line.Length - num2).Trim());
			}
			return (line.Trim(), "");
		}

		public PlannedTile Nearest(int x, int y)
		{
			return Tiles[(Math.Clamp(x, 1, Width - 2), Math.Clamp(y, 1, Height - 2))];
		}
	}
	internal static class PlannerLink
	{
		private static int port;

		private static string pagePath;

		private static readonly ConcurrentQueue<Action> mainThread = new ConcurrentQueue<Action>();

		internal static volatile string Status = "{\"ok\":true,\"state\":\"starting\"}";

		internal static volatile bool Generating;

		private static readonly string token = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();

		private static bool listening;

		private const string TokenSlot = "/*PLANNER_TOKEN*/\"\"";

		internal static string PageUrl
		{
			get
			{
				if (!listening)
				{
					if (pagePath == null)
					{
						return null;
					}
					return new Uri(pagePath).AbsoluteUri;
				}
				return $"http://127.0.0.1:{port}/";
			}
		}

		public static void Start(bool enabled, int listenPort)
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			port = listenPort;
			pagePath = FindPage();
			if (!enabled)
			{
				Plugin.Logger.LogInfo((object)"Planner link turned off in the config: no port is opened. The City Planner button opens the page from disk; copy plans into cityplan.txt.");
				return;
			}
			try
			{
				TcpListener listener = new TcpListener(IPAddress.Loopback, port);
				listener.Start();
				listening = true;
				Thread thread = new Thread((ThreadStart)delegate
				{
					Listen(listener);
				});
				thread.IsBackground = true;
				thread.Name = "CityPlannerLink";
				thread.Start();
				Plugin.Logger.LogInfo((object)("Planner page link ready at " + PageUrl + " (this PC only)" + ((pagePath == null) ? "; city-planner.html not found, so the page can't be opened from the game" : "")));
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(133, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Planner page link couldn't use port ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(port);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("). Set another port under [Planner] in the config. Plans can still be pasted into cityplan.txt.");
				}
				logger.LogWarning(val);
			}
		}

		private static string FindPage()
		{
			try
			{
				string text = Directory.GetFiles(Paths.PluginPath, "CityPlanner.dll", SearchOption.AllDirectories).FirstOrDefault();
				return Directory.GetFiles((text == null) ? Paths.PluginPath : Path.GetDirectoryName(text), "city-planner.html", SearchOption.AllDirectories).FirstOrDefault() ?? Directory.GetFiles(Paths.PluginPath, "city-planner.html", SearchOption.AllDirectories).FirstOrDefault();
			}
			catch
			{
				return null;
			}
		}

		public static void OpenPage()
		{
			if (PageUrl == null)
			{
				Plugin.Logger.LogWarning((object)"city-planner.html wasn't found in the City Planner mod folder. Reinstall the mod.");
				return;
			}
			Plugin.Logger.LogInfo((object)("Opening the planner page: " + PageUrl));
			Application.OpenURL(PageUrl);
		}

		private static void Listen(TcpListener listener)
		{
			while (true)
			{
				try
				{
					TcpClient client = listener.AcceptTcpClient();
					ThreadPool.QueueUserWorkItem(delegate
					{
						Serve(client);
					});
				}
				catch (Exception ex)
				{
					Plugin.Logger.LogWarning((object)("Planner page link stopped: " + ex.Message));
					break;
				}
			}
		}

		private static void Serve(TcpClient client)
		{
			using (client)
			{
				try
				{
					int receiveTimeout = (client.SendTimeout = 5000);
					client.ReceiveTimeout = receiveTimeout;
					NetworkStream stream = client.GetStream();
					if (!ReadRequest(stream, out var method, out var target, out var headers, out var body))
					{
						return;
					}
					string value;
					string host = (headers.TryGetValue("host", out value) ? value : "");
					string value2;
					string text = (headers.TryGetValue("origin", out value2) ? value2 : null);
					string[] source = new string[2]
					{
						$"http://127.0.0.1:{port}",
						$"http://localhost:{port}"
					};
					if (!source.Any((string u) => u == "http://" + host) || (text != null && !source.Contains(text)))
					{
						Respond(stream, 403, "text/plain", "Only the City Planner page can talk to the game.");
						return;
					}
					string text2 = target.Split('?')[0];
					string value3;
					if (method == "GET" && (text2 == "/" || text2 == "/city-planner.html"))
					{
						if (pagePath != null && File.Exists(pagePath))
						{
							Respond(stream, 200, "text/html; charset=utf-8", File.ReadAllText(pagePath).Replace("/*PLANNER_TOKEN*/\"\"", "\"" + token + "\""));
						}
						else
						{
							Respond(stream, 404, "text/plain", "city-planner.html wasn't found in the City Planner mod folder. Reinstall the mod.");
						}
					}
					else if (method == "GET" && text2.StartsWith("/decor/icons/"))
					{
						string dir = DecorIcons.Dir;
						string text3 = text2;
						receiveTimeout = "/decor/icons/".Length;
						string path = Path.Combine(dir, DecorIcons.FileName(Path.GetFileNameWithoutExtension(Uri.UnescapeDataString(text3.Substring(receiveTimeout, text3.Length - receiveTimeout)))));
						if (File.Exists(path))
						{
							RespondBytes(stream, 200, "image/png", File.ReadAllBytes(path));
						}
						else
						{
							Respond(stream, 404, "text/plain", "Not found");
						}
					}
					else if (!headers.TryGetValue("x-planner-token", out value3) || !CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(value3), Encoding.ASCII.GetBytes(token)))
					{
						Respond(stream, 403, "text/plain", "This planner page is from an earlier game session. Open it again with the City Planner button.");
					}
					else if (method == "GET" && text2 == "/plan")
					{
						string content = (File.Exists(Plugin.PlanPath) ? File.ReadAllText(Plugin.PlanPath) : "");
						Respond(stream, 200, "text/plain; charset=utf-8", content);
					}
					else if (method == "GET" && text2 == "/status")
					{
						Respond(stream, 200, "application/json", Status);
					}
					else if (method == "POST" && text2 == "/plan")
					{
						Respond(stream, 200, "application/json", ReceivePlan(body));
					}
					else
					{
						Respond(stream, 404, "text/plain", "Not found");
					}
				}
				catch (Exception ex)
				{
					Plugin.Logger.LogWarning((object)("Planner page request failed: " + ex.Message));
				}
			}
		}

		private static string ReceivePlan(string text)
		{
			Plan plan;
			string error;
			try
			{
				plan = Plan.Parse(text.Replace("\r", "").Split('\n'), out error);
			}
			catch (Exception ex)
			{
				plan = null;
				error = ex.Message;
			}
			if (plan == null)
			{
				return "{\"ok\":false,\"error\":" + Json(error ?? "the plan couldn't be read") + "}";
			}
			string text2 = Plugin.PlanPath + ".tmp";
			File.WriteAllText(text2, text);
			File.Move(text2, Plugin.PlanPath, overwrite: true);
			mainThread.Enqueue(delegate
			{
				Plugin.NoteFileWritten();
				Plugin.Use(plan, "sent from the planner page");
			});
			string value = (Generating ? "after" : "now");
			return $"{{\"ok\":true,\"size\":\"{plan.Width}x{plan.Height}\",\"blocks\":{Json(Blocks(plan))},\"label\":{Json(Sizes.Label(plan.Width, plan.Height))},\"streets\":{plan.Streets.Count},\"when\":\"{value}\"}}";
		}

		private static bool ReadRequest(NetworkStream stream, out string method, out string target, out Dictionary<string, string> headers, out string body)
		{
			method = (target = (body = null));
			headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			MemoryStream memoryStream = new MemoryStream();
			byte[] array = new byte[4096];
			int num;
			while ((num = IndexOfBlankLine(memoryStream)) < 0)
			{
				int num2 = stream.Read(array, 0, array.Length);
				if (num2 <= 0 || memoryStream.Length > 32768)
				{
					return false;
				}
				memoryStream.Write(array, 0, num2);
			}
			byte[] array2 = memoryStream.ToArray();
			string[] array3 = Encoding.ASCII.GetString(array2, 0, num).Split("\r\n");
			string[] array4 = array3[0].Split(' ');
			if (array4.Length < 2)
			{
				return false;
			}
			method = array4[0].ToUpperInvariant();
			target = array4[1];
			foreach (string item in array3.Skip(1))
			{
				int num3 = item.IndexOf(':');
				if (num3 > 0)
				{
					Dictionary<string, string> obj = headers;
					string key = item.Substring(0, num3).Trim();
					string text = item;
					int num4 = num3 + 1;
					obj[key] = text.Substring(num4, text.Length - num4).Trim();
				}
			}
			string value;
			int result;
			int num5 = ((headers.TryGetValue("content-length", out value) && int.TryParse(value, out result)) ? result : 0);
			if (num5 < 0 || num5 > 524288)
			{
				return false;
			}
			MemoryStream memoryStream2 = new MemoryStream();
			memoryStream2.Write(array2, num + 4, array2.Length - num - 4);
			while (memoryStream2.Length < num5)
			{
				int num6 = stream.Read(array, 0, array.Length);
				if (num6 <= 0)
				{
					return false;
				}
				memoryStream2.Write(array, 0, num6);
			}
			body = Encoding.UTF8.GetString(memoryStream2.ToArray(), 0, num5);
			return true;
		}

		private static int IndexOfBlankLine(MemoryStream ms)
		{
			byte[] buffer = ms.GetBuffer();
			for (int i = 0; i + 3 < ms.Length; i++)
			{
				if (buffer[i] == 13 && buffer[i + 1] == 10 && buffer[i + 2] == 13 && buffer[i + 3] == 10)
				{
					return i;
				}
			}
			return -1;
		}

		private static void Respond(NetworkStream stream, int code, string type, string content)
		{
			RespondBytes(stream, code, type, Encoding.UTF8.GetBytes(content));
		}

		private static void RespondBytes(NetworkStream stream, int code, string type, byte[] bytes)
		{
			string value = code switch
			{
				200 => "OK", 
				403 => "Forbidden", 
				_ => "Not Found", 
			};
			string text = $"HTTP/1.1 {code} {value}\r\nContent-Type: {type}\r\nContent-Length: {bytes.Length}\r\nCache-Control: no-store\r\nConnection: close\r\n" + "X-Frame-Options: DENY\r\nContent-Security-Policy: frame-ancestors 'none'\r\nX-Content-Type-Options: nosniff\r\n";
			byte[] bytes2 = Encoding.ASCII.GetBytes(text + "\r\n");
			stream.Write(bytes2, 0, bytes2.Length);
			stream.Write(bytes, 0, bytes.Length);
		}

		internal static string Blocks(Plan plan)
		{
			return $"{plan.Width - 2} × {plan.Height - 2} blocks";
		}

		internal static string Json(string s)
		{
			return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", " ")
				.Replace("\r", "") + "\"";
		}

		internal static bool TryDequeue(out Action action)
		{
			return mainThread.TryDequeue(out action);
		}
	}
	public class PlannerPump : MonoBehaviour
	{
		private static float nextCheck;

		private static GameObject button;

		public PlannerPump(IntPtr ptr)
			: base(ptr)
		{
		}

		public void Update()
		{
			Sizes.Ensure();
			DecorIcons.EnsureExported();
			Basements.Tick();
			UpdateGenerating();
			Action action;
			while (!PlannerLink.Generating && PlannerLink.TryDequeue(out action))
			{
				try
				{
					action();
				}
				catch (Exception ex)
				{
					Plugin.Logger.LogError((object)("Applying a plan from the planner page failed: " + ex));
				}
			}
			if (!(Time.unscaledTime < nextCheck))
			{
				nextCheck = Time.unscaledTime + 0.5f;
				UpdateStatus();
				if ((Object)(object)button == (Object)null)
				{
					button = MenuButton.TryCreate();
				}
			}
		}

		private static void UpdateGenerating()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			if (PlannerLink.Generating)
			{
				CityConstructor instance = CityConstructor.Instance;
				if ((Object)(object)instance == (Object)null || (int)instance.loadState >= 19 || ((Object)(object)SessionData.Instance != (Object)null && SessionData.Instance.startedGame))
				{
					PlannerLink.Generating = false;
				}
			}
		}

		private static void UpdateStatus()
		{
			bool flag = (Object)(object)SessionData.Instance != (Object)null && SessionData.Instance.startedGame;
			string value = (PlannerLink.Generating ? "generating" : (flag ? "playing" : "menu"));
			Plan plan = Plugin.Plan;
			string value2 = ((plan == null) ? "null" : $"{{\"size\":\"{plan.Width}x{plan.Height}\",\"blocks\":{PlannerLink.Json(PlannerLink.Blocks(plan))},\"streets\":{plan.Streets.Count}}}");
			PlannerLink.Status = $"{{\"ok\":true,\"state\":\"{value}\",\"plan\":{value2}}}";
		}
	}
	[HarmonyPatch(typeof(CityConstructor), "GenerateNewCity")]
	internal static class GeneratingFlag
	{
		private static void Prefix()
		{
			PlannerLink.Generating = true;
		}
	}
	internal static class MenuButton
	{
		public static GameObject TryCreate()
		{
			//IL_0303: Unknown result type (might be due to invalid IL or missing references)
			//IL_030a: Expected O, but got Unknown
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or miss