Decompiled source of CreatureDiscomforts v1.4.0

CreatureDiscomforts.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CreatureDiscomforts.Effects;
using CreatureDiscomforts.Model;
using CreatureDiscomforts.Survey;
using HarmonyLib;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using SOD.Common;
using SOD.Common.Helpers;
using SOD.Common.Helpers.DialogObjects;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("CreatureDiscomforts")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyInformationalVersion("1.4.0")]
[assembly: AssemblyProduct("CreatureDiscomforts")]
[assembly: AssemblyTitle("CreatureDiscomforts")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.0.0")]
[module: UnverifiableCode]
[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 CreatureDiscomforts
{
	[BepInPlugin("ekem.creaturediscomforts", "Creature Discomforts", "1.4.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BasePlugin
	{
		private Harmony? _harmony;

		public static ManualLogSource Log { get; private set; }

		public static Settings Cfg { get; private set; }

		public override void Load()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			Log = ((BasePlugin)this).Log;
			Cfg = new Settings(((BasePlugin)this).Config);
			_harmony = new Harmony("ekem.creaturediscomforts");
			_harmony.PatchAll();
			InstallHotkeys();
			Illness.Install();
			Doctor.Install();
			ManualLogSource log = Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(9, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("Creature Discomforts");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("1.4.0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded.");
			}
			log.LogInfo(val);
		}

		private static void InstallHotkeys()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			ClassInjector.RegisterTypeInIl2Cpp<Heartbeat>();
			GameObject val = new GameObject("Creature DiscomfortsHotkeys");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<Heartbeat>();
		}
	}
	public class Settings
	{
		public readonly ConfigEntry<float> ThirstToHunger;

		public readonly ConfigEntry<float> SleepNeedsRate;

		public readonly ConfigEntry<float> SleepHoursToRest;

		public readonly ConfigEntry<float> WellRestedAfterHours;

		public readonly ConfigEntry<float> SleepTimeScale;

		public readonly ConfigEntry<bool> PhoneWakesYou;

		public readonly ConfigEntry<bool> Starving;

		public readonly ConfigEntry<float> StarvingBelow;

		public readonly ConfigEntry<float> StarvingDamage;

		public readonly ConfigEntry<bool> Parched;

		public readonly ConfigEntry<float> ParchedBelow;

		public readonly ConfigEntry<float> ParchedDamage;

		public readonly ConfigEntry<float> HealthFloor;

		public readonly ConfigEntry<float> StumbleChance;

		public readonly ConfigEntry<float> BodyLossPerHour;

		public readonly ConfigEntry<float> BodyGainPerHour;

		public readonly ConfigEntry<float> WaterLossPerHour;

		public readonly ConfigEntry<float> WaterGainPerHour;

		public readonly ConfigEntry<float> ThirstHeadachePerHour;

		public readonly ConfigEntry<float> ThirstHeadacheBelow;

		public readonly ConfigEntry<bool> CatchingColds;

		public readonly ConfigEntry<float> ColdThreshold;

		public readonly ConfigEntry<float> CatchFromCold;

		public readonly ConfigEntry<float> CatchFromWet;

		public readonly ConfigEntry<float> CatchFromBoth;

		public readonly ConfigEntry<float> RecoveryPerHour;

		public readonly ConfigEntry<float> RecoverAboveHeat;

		public readonly ConfigEntry<float> SleepRecovery;

		public readonly ConfigEntry<bool> Immunity;

		public readonly ConfigEntry<float> ImmunityLossPerHour;

		public readonly ConfigEntry<float> ImmunityLossStarving;

		public readonly ConfigEntry<float> ImmunityGainPerHour;

		public readonly ConfigEntry<float> ImmunityBaseGain;

		public readonly ConfigEntry<float> LowImmunityCatch;

		public readonly ConfigEntry<float> LowImmunityRecovery;

		public readonly ConfigEntry<float> AlcoholHeatLoss;

		public readonly ConfigEntry<bool> RealisticDrinks;

		public readonly ConfigEntry<float> StrongDrinkThirst;

		public readonly ConfigEntry<float> StrongDrinkTiring;

		public readonly ConfigEntry<float> NauseaFromDrunk;

		public readonly ConfigEntry<float> DrunkNauseaPerHour;

		public readonly ConfigEntry<float> OverdrinkNausea;

		public readonly ConfigEntry<float> RetchAbove;

		public readonly ConfigEntry<float> RetchPerHour;

		public readonly ConfigEntry<float> VomitSobers;

		public readonly ConfigEntry<float> VomitTiring;

		public readonly ConfigEntry<bool> CaffeineKeepsAwake;

		public readonly ConfigEntry<float> SedationWeight;

		public readonly ConfigEntry<float> HospitalClearsTo;

		public readonly ConfigEntry<float> CaffeineHalfLife;

		public readonly ConfigEntry<float> CaffeineWiredAbove;

		public readonly ConfigEntry<float> CaffeineNoSleepAbove;

		public readonly ConfigEntry<float> CaffeineDebt;

		public readonly ConfigEntry<float> EmptyStomachNausea;

		public readonly ConfigEntry<float> OvereatingNausea;

		public readonly ConfigEntry<bool> CaffeineFocus;

		public readonly ConfigEntry<float> CaffeineFocusAbove;

		public readonly ConfigEntry<float> CaffeineOverdoseAbove;

		public readonly ConfigEntry<float> MixingDrunkAbove;

		public readonly ConfigEntry<float> AlcoholCodeineNauseaPerHour;

		public readonly ConfigEntry<float> AlcoholCodeineTiringPerHour;

		public readonly ConfigEntry<bool> AlcoholAndSleepingPills;

		public readonly ConfigEntry<bool> AlcoholPainkiller;

		public readonly ConfigEntry<bool> OneDosePerPress;

		public readonly ConfigEntry<float> CodeineHalfLife;

		public readonly ConfigEntry<float> SleepingPillsHalfLife;

		public readonly ConfigEntry<float> CodeineOverdoseAbove;

		public readonly ConfigEntry<float> CodeineKnockoutAbove;

		public readonly ConfigEntry<float> SleepingPillsKnockoutAbove;

		public readonly ConfigEntry<bool> Addictions;

		public readonly ConfigEntry<float> HabitDecayPerDay;

		public readonly ConfigEntry<float> CaffeineHabitRate;

		public readonly ConfigEntry<float> NicotineHabitRate;

		public readonly ConfigEntry<float> AlcoholHabitRate;

		public readonly ConfigEntry<float> CodeineHabitRate;

		public readonly ConfigEntry<float> SleepingPillsHabitRate;

		public readonly ConfigEntry<bool> FallingAsleep;

		public readonly ConfigEntry<float> FallAsleepMinutes;

		public readonly ConfigEntry<float> CantSleepAfterHours;

		public readonly ConfigEntry<float> HookedAbove;

		public readonly ConfigEntry<float> CravingAt;

		public readonly ConfigEntry<float> WithdrawalAt;

		public readonly ConfigEntry<bool> Tolerance;

		public readonly ConfigEntry<bool> AlcoholWithdrawalDangerous;

		public readonly ConfigEntry<bool> SmokingHungerDebt;

		public readonly ConfigEntry<float> HeadacheFade;

		public readonly ConfigEntry<float> SleeplessHeadacheAfter;

		public readonly ConfigEntry<float> SleeplessHeadachePerHour;

		public readonly ConfigEntry<float> WokenHeadache;

		public readonly ConfigEntry<float> OversleepAfter;

		public readonly ConfigEntry<bool> Sprains;

		public readonly ConfigEntry<float> SprainChance;

		public readonly ConfigEntry<float> SprainFromDrop;

		public readonly ConfigEntry<float> SprainDays;

		public readonly ConfigEntry<int> DoctorFee;

		public readonly ConfigEntry<int> SyncClinicFee;

		public readonly ConfigEntry<float> RunningThirst;

		public readonly ConfigEntry<float> RunningTiring;

		public readonly ConfigEntry<float> RunningWarmth;

		public readonly ConfigEntry<float> RunningSweat;

		public readonly ConfigEntry<BreathMode> BreathMode;

		public readonly ConfigEntry<float> BreathSeconds;

		public readonly ConfigEntry<float> BreathRecovery;

		public readonly ConfigEntry<bool> DebugLogging;

		public readonly ConfigEntry<KeyCode> SurveyKey;

		public readonly ConfigEntry<KeyCode> OverlayKey;

		public readonly ConfigEntry<KeyCode> ShopKey;

		public readonly ConfigEntry<KeyCode> IllnessKey;

		public readonly ConfigEntry<KeyCode> MoneyKey;

		public readonly ConfigEntry<KeyCode> AddictionKey;

		public readonly ConfigEntry<bool> QuickMenu;

		public Settings(ConfigFile config)
		{
			ThirstToHunger = config.Bind<float>("Needs", "ThirstToHunger", 1.5f, "How fast thirst drains compared to hunger. 1.5 means you get thirsty 1.5 times as fast as you get hungry. 0 keeps the game's own rate.");
			Starving = config.Bind<bool>("Needs", "Starving", true, "Running out of food entirely makes you Starving: no health recovery, unsteady on your feet, and slowly losing health. Never down to a hospital visit, see HealthFloor.");
			StarvingBelow = config.Bind<float>("Needs", "StarvingReserves", 0.4f, "You are Starving once your body's reserves are this low (0..1): you stumble and slowly lose health.");
			StarvingDamage = config.Bind<float>("Needs", "StarvingDamage", 0.1f, "How much health you lose per game hour while starving, as a share of your maximum health. 0 turns the damage off.");
			Parched = config.Bind<bool>("Needs", "Parched", true, "Running out of water entirely makes you Parched: the same as Starving, a little harsher.");
			ParchedBelow = config.Bind<float>("Needs", "ParchedReserves", 0.4f, "You are Parched once your water balance is this low (0..1): you stumble and slowly lose health.");
			ParchedDamage = config.Bind<float>("Needs", "ParchedDamage", 0.15f, "How much health you lose per game hour while parched, as a share of your maximum health. 0 turns the damage off.");
			HealthFloor = config.Bind<float>("Needs", "HealthFloor", 0.25f, "Starving and parched never take your health below this share of the maximum, and neither do stumbles while you are starving or parched.");
			BodyLossPerHour = config.Bind<float>("Needs", "BodyLossPerHour", 0.025f, "Your body's reserves (hidden, 0..1) shrink this much per game hour with no food left at all, less while only Hungry. Food runs out in about eight hours; at 0.025 you are Starving about a day after that.");
			BodyGainPerHour = config.Bind<float>("Needs", "BodyGainPerHour", 0.01f, "How fast your body's reserves come back per game hour while you are fed (food at least half). At 0.01 it takes a couple of days to recover from starving: one meal doesn't undo it.");
			WaterLossPerHour = config.Bind<float>("Needs", "WaterLossPerHour", 0.05f, "Your body's water balance (hidden, 0..1) drops this much per game hour with no water left at all, less while only Thirsty. At 0.05 you are Parched about twelve hours after water runs out.");
			WaterGainPerHour = config.Bind<float>("Needs", "WaterGainPerHour", 0.1f, "How fast your water balance comes back per game hour once you have had enough to drink (water at least half).");
			StumbleChance = config.Bind<float>("Needs", "StumbleChance", 0.25f, "How often you stumble and fall while starving or parched, compared to being as drunk as you can get (1 = just as often, about one step in fifty). Both at once add up. 0 turns this off. Takes effect after restarting the game.");
			ThirstHeadachePerHour = config.Bind<float>("Needs", "ThirstHeadachePerHour", 1.2f, "Going thirsty for long gives you a headache: this much per game hour when you are completely dry, less while only a little thirsty. The game eases a headache by about 0.5-0.75 per hour, so it creeps in slowly. Painkillers stop it for a while. 0 turns this off.");
			ThirstHeadacheBelow = config.Bind<float>("Needs", "ThirstHeadacheBelow", 0.1f, "The headache only starts below this much water (0..1). You get the Thirsty status at 0.2, so the first sign of thirst doesn't hurt yet.");
			SleepNeedsRate = config.Bind<float>("Needs", "SleepNeedsRate", 0.25f, "How fast hunger and thirst go while you sleep in a bed, compared to awake. The game's own is 0.5, which with this mod leaves you parched after a night's sleep; 0.25 means a night of eight hours costs about a quarter of your food and water. 0.5 keeps the game's own.");
			SleepHoursToRest = config.Bind<float>("Needs", "SleepHoursToRest", 7f, "Game hours of sleep to go from exhausted to fully rested. The game's own is 4. 0 keeps the game's own.");
			WellRestedAfterHours = config.Bind<float>("Needs", "WellRestedAfterHours", 8f, "You only start getting Well Rested after sleeping this many game hours in one go. A nap restores energy but doesn't make you well rested.");
			SleepTimeScale = config.Bind<float>("Needs", "SleepTimeScale", 2f, "Time passes this many times faster than the game's own fast-forward while you sleep in a bed, so a full night doesn't drag. 1 keeps the game's own.");
			PhoneWakesYou = config.Bind<bool>("Needs", "PhoneWakesYou", true, "A phone ringing where you are sleeping (or waiting) wakes you up, so you can answer it. Each call wakes you only once.");
			CatchingColds = config.Bind<bool>("Illness", "CatchingColds", true, "Being out in the cold or soaking wet can give you a cold, with a stuffy nose, a headache, fever and chills.");
			ColdThreshold = config.Bind<float>("Illness", "ColdThreshold", 0.25f, "Below this body heat (0..1) you count as freezing.");
			CatchFromCold = config.Bind<float>("Illness", "CatchFromCold", 0.1f, "How much of a cold you pick up per game hour when completely frozen but dry.");
			CatchFromWet = config.Bind<float>("Illness", "CatchFromWet", 0.05f, "How much of a cold you pick up per game hour when soaked but warm.");
			CatchFromBoth = config.Bind<float>("Illness", "CatchFromBoth", 0.1f, "Extra per game hour on top of the two above when you are frozen AND soaked. With the defaults that makes 0.25: fever in about two hours.");
			RecoveryPerHour = config.Bind<float>("Illness", "RecoveryPerHour", 0.03f, "How fast a cold wears off per game hour while you are warm and dry and awake. At 0.03 a bad cold takes about a day to pass.");
			RecoverAboveHeat = config.Bind<float>("Illness", "RecoverAboveHeat", 0.5f, "A cold only wears off when your body heat is at least this. Between this and ColdThreshold it neither gets worse nor better.");
			SleepRecovery = config.Bind<float>("Illness", "SleepRecovery", 3f, "How many times faster a cold wears off while you sleep in a bed.");
			Immunity = config.Bind<bool>("Illness", "Immunity", true, "Going hungry, thirsty or without sleep wears down your resistance, and eating, drinking and sleeping well build it back up. It is never shown: you only notice it in how easily you catch a cold and how long it takes to pass.");
			ImmunityLossPerHour = config.Bind<float>("Illness", "ImmunityLossPerHour", 0.01f, "How much resistance (0..1) you lose per game hour for each of Hungry, Thirsty and Tired.");
			ImmunityLossStarving = config.Bind<float>("Illness", "ImmunityLossStarving", 0.01f, "Extra resistance lost per game hour for each of Starving and Parched. With the defaults, a whole day without food or water takes it from full to about 0.4.");
			ImmunityGainPerHour = config.Bind<float>("Illness", "ImmunityGainPerHour", 0.05f, "Resistance regained per game hour for each of Energized, Hydrated and Well Rested.");
			ImmunityBaseGain = config.Bind<float>("Illness", "ImmunityBaseGain", 0.015f, "Resistance regained per game hour while you are neither hungry, thirsty nor tired.");
			LowImmunityCatch = config.Bind<float>("Illness", "LowImmunityCatch", 2f, "How many times faster you catch a cold with no resistance left. In between it scales evenly; 1 means resistance doesn't affect catching a cold.");
			LowImmunityRecovery = config.Bind<float>("Illness", "LowImmunityRecovery", 0.5f, "How fast a cold wears off with no resistance left, compared to full resistance (0.5 = half as fast). 1 means resistance doesn't affect getting better.");
			AlcoholHeatLoss = config.Bind<float>("Alcohol", "AlcoholHeatLoss", 0.5f, "While drunk you lose body heat this much faster (0.5 = one and a half times), and you don't feel the cold: no shivering, no chills. 0 turns this off. Takes effect after restarting the game.");
			RealisticDrinks = config.Bind<bool>("Alcohol", "RealisticDrinks", true, "Spirits dry you out instead of quenching thirst, and coffee or tea no longer sober you up or cancel painkillers. Takes effect after restarting the game.");
			StrongDrinkThirst = config.Bind<float>("Alcohol", "StrongDrinkThirst", 0.3f, "How much thirst a glass of spirits (bourbon, vodka) costs instead of quenching it. Beer, cider and wine are unchanged. Takes effect after restarting the game.");
			StrongDrinkTiring = config.Bind<float>("Alcohol", "StrongDrinkTiring", 0.15f, "How much energy a glass of spirits costs. Takes effect after restarting the game.");
			NauseaFromDrunk = config.Bind<float>("Alcohol", "NauseaFromDrunk", 0.7f, "Above this drunkenness (0..1) you start feeling sick. 0 turns this off.");
			DrunkNauseaPerHour = config.Bind<float>("Alcohol", "DrunkNauseaPerHour", 1.5f, "How fast nausea builds per game hour when completely drunk. The game eases nausea on its own, so a little over the line passes and a lot does not.");
			OverdrinkNausea = config.Bind<float>("Alcohol", "OverdrinkNausea", 0.5f, "Once you are as drunk as you can get, whatever more you drink turns into nausea instead: this much per unit of drunkenness that doesn't fit. A second bottle of vodka will come back up. 0 turns this off.");
			RetchAbove = config.Bind<float>("Needs", "RetchAbove", 0.8f, "Above this nausea (0..1) you may throw up wherever you are, not just over a toilet.");
			RetchPerHour = config.Bind<float>("Needs", "RetchPerHour", 12f, "How likely that is per game hour at full nausea (12 = usually within five minutes). Less likely when only just past RetchAbove. 0 turns this off.");
			VomitSobers = config.Bind<float>("Alcohol", "VomitSobers", 0.6f, "How much a full throw-up sobers you. 0 turns this off.");
			VomitTiring = config.Bind<float>("Needs", "VomitTiring", 0.15f, "How much energy throwing up costs. 0 turns this off.");
			AlcoholPainkiller = config.Bind<bool>("Alcohol", "AlcoholPainkiller", true, "A drink or two dulls pain: while only a little drunk (about 0.05 to 0.4) you take a quarter less damage and headaches ease faster. Any drunker and it stops helping.");
			CaffeineKeepsAwake = config.Bind<bool>("Mixing", "CaffeineKeepsAwake", true, "Caffeine keeps you from sleeping (see CaffeineNoSleepAbove): you get straight back up, with no energy back and no Well Rested.");
			SedationWeight = config.Bind<float>("Mixing", "SedationWeight", 1f, "Sleeping pills cancel out coffee: each pill counts against this much caffeine when deciding whether you are Focused or Wired. Whichever is stronger in your blood wins. 0 turns this off.");
			HospitalClearsTo = config.Bind<float>("Medicine", "HospitalClearsTo", 0.1f, "In hospital you are first stabilised (drugs brought below an overdose), and once you pay the medical fees, whatever is left in your blood is cleared down to this share (alcohol wears off on its own). 1 keeps them.");
			CaffeineHalfLife = config.Bind<float>("Mixing", "CaffeineHalfLife", 2.5f, "Game hours for half the caffeine in you to wear off. Each drink adds its own strength (coffee 1, Starch Kola 0.85, tea 0.6) for as much of it as you actually drink, so two coffees keep you up longer than one, and tea less.");
			CaffeineWiredAbove = config.Bind<float>("Mixing", "CaffeineWiredAbove", 0.25f, "You are Wired while the caffeine in you is above this: you fall asleep slowly and sleep badly. With the defaults one coffee lasts about five hours, a tea about three, two coffees about seven and a half.");
			CaffeineNoSleepAbove = config.Bind<float>("Mixing", "CaffeineNoSleepAbove", 0.5f, "Above this much caffeine you can't fall asleep at all and get straight back up. Between CaffeineWiredAbove and this you can, but it takes long and you sleep badly. A coffee keeps you up for about two and a half hours, then makes sleep hard for as long again. When you're worn out (energy below 0.3) this goes up, to twice as much when exhausted: a coffee can't keep a dead-tired detective up, only make the sleep worse. Without Sleep.FallingAsleep this isn't used and Wired keeps you up throughout.");
			CaffeineFocus = config.Bind<bool>("Mixing", "CaffeineFocus", true, "Coffee, tea and Starch Kola make you Focused through the caffeine in you rather than all at once: Focused lasts while caffeine is above CaffeineFocusAbove. False keeps the game's own one-off boost. Takes effect after restarting the game.");
			CaffeineFocusAbove = config.Bind<float>("Mixing", "CaffeineFocusAbove", 0.65f, "You stay Focused while the caffeine in you is above this. With the defaults a coffee keeps you focused for about an hour and a half, Starch Kola about an hour, and a tea alone not at all.");
			CaffeineDebt = config.Bind<float>("Mixing", "CaffeineDebt", 0.1f, "Caffeine borrows energy (0..1): this much per cup of coffee, less for tea, taken back as the caffeine wears off, most of it two to six game hours later. 0 turns this off.");
			CaffeineOverdoseAbove = config.Bind<float>("Mixing", "CaffeineOverdoseAbove", 2.5f, "Above this much caffeine you are Jittery: shaky vision and a turning stomach. That's about three coffees in a row. 0 turns this off.");
			EmptyStomachNausea = config.Bind<float>("Mixing", "EmptyStomachNausea", 0.25f, "Nausea from coffee, tea or Starch Kola while you are Hungry. 0 turns this off.");
			OvereatingNausea = config.Bind<float>("Mixing", "OvereatingNausea", 0.6f, "Eating when you are full: whatever doesn't fit goes to your stomach as nausea, this much per unit of food, and it builds with every bite. A whole meal on a full stomach will come back up. 0 turns this off.");
			MixingDrunkAbove = config.Bind<float>("Mixing", "MixingDrunkAbove", 0.3f, "Drink only mixes with painkillers, cough syrup or sleeping pills once you are this drunk (0..1): about three beers or most of a bottle of wine. One spoon of cough syrup stays below it.");
			AlcoholCodeineNauseaPerHour = config.Bind<float>("Mixing", "AlcoholCodeineNauseaPerHour", 4f, "Nausea per game hour while you are drunk and painkillers or cough syrup are still in you. This is the worst case, very drunk on two doses; a few drinks and one pill is about a quarter of it. 0 turns this off.");
			AlcoholCodeineTiringPerHour = config.Bind<float>("Mixing", "AlcoholCodeineTiringPerHour", 0.6f, "Energy (0..1) lost per game hour to the same mix, worst case. 0 turns this off.");
			AlcoholAndSleepingPills = config.Bind<bool>("Mixing", "AlcoholAndSleepingPills", true, "Drunk while a sleeping pill is still working (about four game hours), you black out a couple of minutes later, like losing a fight: you may wake up in hospital, with the bill to match.");
			OneDosePerPress = config.Bind<bool>("Medicine", "OneDosePerPress", true, "Pills and cough syrup are taken one dose per press, using the game's own 'take one', instead of the whole bottle in one go. A bottle of painkillers holds ten doses, sleeping pills two. With this off a bottle goes down at once and counts as every dose in it.");
			CodeineHalfLife = config.Bind<float>("Medicine", "CodeineHalfLife", 3f, "Game hours for half the codeine (painkillers, cough syrup) in you to wear off. Each dose adds 1; it mixes with drink while above 0.5.");
			SleepingPillsHalfLife = config.Bind<float>("Medicine", "SleepingPillsHalfLife", 4f, "Game hours for half a sleeping pill to wear off. It mixes with drink while above 0.5.");
			CodeineOverdoseAbove = config.Bind<float>("Medicine", "CodeineOverdoseAbove", 3f, "Above this much codeine you have a Codeine Overdose: dizzy, slower and sick. That's three doses within an hour or two. 0 turns this off.");
			CodeineKnockoutAbove = config.Bind<float>("Medicine", "CodeineKnockoutAbove", 5f, "Above this much codeine you pass out, like losing a fight. 0 turns this off.");
			SleepingPillsKnockoutAbove = config.Bind<float>("Medicine", "SleepingPillsKnockoutAbove", 1.8f, "Above this many sleeping pills in you you pass out on the spot, like losing a fight: two pills within about an hour. 0 turns this off.");
			Addictions = config.Bind<bool>("Addiction", "Addictions", true, "Coffee, cigarettes, drink and codeine (painkillers, cough syrup) can become a habit if you have a lot of them for days. Hooked, you get a Craving once one wears off, then Withdrawal if you hold out: a headache, the shakes, nausea and so on. A dose fixes it; a few days without and the habit fades. False turns habits, withdrawal and tolerance off.");
			HabitDecayPerDay = config.Bind<float>("Addiction", "HabitDecayPerDay", 0.1f, "How much of a habit (hidden, 0..1) fades per game day, all the time. At 0.1 a strong habit takes about four days without to stop causing withdrawal.");
			CaffeineHabitRate = config.Bind<float>("Addiction", "CaffeineHabitRate", 0.02f, "How fast caffeine becomes a habit. At 0.02 a coffee a day never does; three a day get you hooked in two or three days, two a day in about a week.");
			NicotineHabitRate = config.Bind<float>("Addiction", "NicotineHabitRate", 0.02f, "How fast smoking becomes a habit. At 0.02 a cigarette or two a day never does; five a day get you hooked in a day or two, ten in less than a day.");
			AlcoholHabitRate = config.Bind<float>("Addiction", "AlcoholHabitRate", 0.25f, "How fast drinking becomes a habit. At 0.25 a glass or two in the evening never does; getting properly drunk every night gets you hooked in about three days, drinking yourself under the table in less than two.");
			CodeineHabitRate = config.Bind<float>("Addiction", "CodeineHabitRate", 0.015f, "How fast painkillers and cough syrup become a habit. At 0.015 one dose a day never does; three a day get you hooked in about three days.");
			HookedAbove = config.Bind<float>("Addiction", "HookedAbove", 0.3f, "Below this habit (0..1) there is no withdrawal at all.");
			CravingAt = config.Bind<float>("Addiction", "CravingAt", 0.3f, "Withdrawal (hidden, 0..1) at which you get a Craving. It builds once a dose wears off: at full habit in about 6 game hours for caffeine, 3 for nicotine, 11 for alcohol, 5.5 for codeine; slower with a weaker habit.");
			WithdrawalAt = config.Bind<float>("Addiction", "WithdrawalAt", 0.65f, "Withdrawal at which the Craving turns into Withdrawal proper: at full habit about 12 game hours without caffeine, 6 without nicotine, 24 without drink, 12 without codeine. A weak habit never gets this far.");
			Tolerance = config.Bind<bool>("Addiction", "Tolerance", true, "The stronger the habit, the more it takes: coffee focuses you less and keeps you awake for less, drink dulls pain only once you are drunker, painkillers wear off sooner. Overdoses move up much less, so a habit brings you closer to one.");
			AlcoholWithdrawalDangerous = config.Bind<bool>("Addiction", "AlcoholWithdrawalDangerous", true, "With a strong drinking habit, withdrawal turns into Delirium Tremens: no health recovery and slowly losing health, never below HealthFloor. False keeps it to the shakes, sweat and nausea.");
			SmokingHungerDebt = config.Bind<bool>("Addiction", "SmokingHungerDebt", true, "With ImprovedSmoking: the food a cigarette gives you is only a dulled appetite, and the hunger comes back over the next couple of game hours. Does nothing without ImprovedSmoking.");
			HeadacheFade = config.Bind<float>("Pain", "HeadacheFade", 0.25f, "How fast a headache wears off by itself, compared to the game's own (about 0.75 per game hour). 0.25 keeps a hangover with you all morning unless you take a painkiller; while a painkiller works, it wears off at the game's own pace. 1 keeps the game's own.");
			SleeplessHeadacheAfter = config.Bind<float>("Pain", "SleeplessHeadacheAfter", 18f, "After this many game hours without sleep your head starts to ache, worse every hour. Sleep in a bed pays the hours back three times as fast as they build up. Coffee doesn't help. 0 turns this off.");
			SleeplessHeadachePerHour = config.Bind<float>("Pain", "SleeplessHeadachePerHour", 0.8f, "How fast that headache grows at its worst, ten hours past the start, per game hour.");
			WokenHeadache = config.Bind<float>("Pain", "WokenHeadache", 0.5f, "Woken up by the phone soon after falling asleep: this much headache, less the longer you slept. 0 turns this off.");
			OversleepAfter = config.Bind<float>("Pain", "OversleepAfter", 10f, "Sleeping longer than this many game hours in one go leaves you with a headache. 0 turns this off.");
			Sprains = config.Bind<bool>("Pain", "Sprains", true, "A fall can twist your ankle for a day or two: you limp and can't run. A splint lets you run and heals it twice as fast; painkillers let you run, but running on it makes it heal slower.");
			SprainChance = config.Bind<float>("Pain", "SprainChance", 0.6f, "Chance to twist your ankle in a bad fall (0..1): one from about the second floor, or one that costs 15% of your health. Tripping over is half as likely to do it.");
			SprainFromDrop = config.Bind<float>("Pain", "SprainFromDrop", 3f, "Landing from this many metres or more can twist your ankle; the full SprainChance at twice that.");
			SprainDays = config.Bind<float>("Pain", "SprainDays", 1f, "A sprain heals in this many game days, up to half as long again. Running on it makes it longer.");
			DoctorFee = config.Bind<int>("Pain", "DoctorFee", 150, "Crows a clinic charges to strap a sprained ankle: like a splint, but it heals three times as fast. Ask anyone working at the hospital ward. -1 turns this off.");
			SyncClinicFee = config.Bind<int>("Pain", "SyncClinicFee", 400, "Crows a Sync Clinic charges for the same. They install implants, not set ankles, but they will, for a price. -1 means they won't.");
			RunningThirst = config.Bind<float>("Running", "RunningThirst", 0.1f, "Water lost per real minute of running (0..1 of the scale). 0 turns this off.");
			RunningTiring = config.Bind<float>("Running", "RunningTiring", 0.06f, "Energy lost per real minute of running. 0 turns this off.");
			RunningWarmth = config.Bind<float>("Running", "RunningWarmth", 0.4f, "Body heat gained per real minute of running. 0 turns this off.");
			RunningSweat = config.Bind<float>("Running", "SweatPerMinute", 0.05f, "Running flat out for more than about ten seconds makes you sweat once you are warm: this much hygiene per real minute of it. A short dash doesn't. 0 turns this off.");
			BreathMode = config.Bind<BreathMode>("Running", "BreathMode", CreatureDiscomforts.Effects.BreathMode.Conditions, "When you run out of breath. Conditions: only when something holds you back (a smoking habit, being worn out, drink, a cold), and the worse it is, the sooner; rested and sober, you can run as long as you like. Fixed: everyone, after BreathSeconds, sooner when something holds you back. Off: never.");
			BreathSeconds = config.Bind<float>("Running", "BreathSeconds", 20f, "Real seconds you can run without a break before you are Out of Breath, in Fixed mode. In Conditions mode it's the scale: at your very worst you last about a third of it. 0 turns Out of Breath off.");
			BreathRecovery = config.Bind<float>("Running", "BreathRecovery", 12f, "Real seconds to get your breath back from nothing while walking or standing. You can run again at half.");
			SleepingPillsHabitRate = config.Bind<float>("Addiction", "SleepingPillsHabitRate", 0.03f, "How fast sleeping pills become a habit. At 0.03 a pill every other night never does; one every night gets you hooked in four or five days.");
			FallingAsleep = config.Bind<bool>("Sleep", "FallingAsleep", true, "You don't drop off the moment you lie down. Caffeine, pain, hunger, thirst, cold, wet clothes, withdrawal, light and noise make it take longer; being tired, a drink or a sleeping pill shorten it. You only rest once asleep, and pain, drink, cold and noise make the sleep lighter. False: asleep at once.");
			FallAsleepMinutes = config.Bind<float>("Sleep", "FallAsleepMinutes", 15f, "Game minutes to fall asleep with nothing keeping you up and not especially tired.");
			CantSleepAfterHours = config.Bind<float>("Sleep", "CantSleepAfterHours", 1.5f, "Lying awake this many game hours, you give up and get up. 0: you lie there until you fall asleep.");
			DebugLogging = config.Bind<bool>("Debug", "DebugLogging", false, "Logs every change to your own condition, and what the game has switched on.");
			SurveyKey = config.Bind<KeyCode>("Debug", "SurveyKey", (KeyCode)288, "Logs which survival statuses the game has enabled and how you are doing right now.");
			OverlayKey = config.Bind<KeyCode>("Debug", "OverlayKey", (KeyCode)289, "Toggles an on-screen panel with your current needs and how fast they change per game hour.");
			ShopKey = config.Bind<KeyCode>("Debug", "ShopKey", (KeyCode)290, "Logs every item sold in shops and what it does to your needs, and writes the same as a table to BepInEx/CreatureDiscomforts-shop.tsv.");
			IllnessKey = config.Bind<KeyCode>("Debug", "IllnessKey", (KeyCode)0, "Makes your cold 0.2 worse each press; past the worst it cures you. For testing; unbound by default (F10 is handy).");
			MoneyKey = config.Bind<KeyCode>("Debug", "MoneyKey", (KeyCode)0, "Gives you 10000 money. For testing; unbound by default (F11 is handy).");
			AddictionKey = config.Bind<KeyCode>("Debug", "AddictionKey", (KeyCode)0, "Adds 0.35 habit to coffee, cigarettes, drink and codeine each press; past full it clears them. For testing; unbound by default.");
			QuickMenu = config.Bind<bool>("Debug", "QuickMenu", false, "Lists the actions above (survey, overlay, shop survey, cold, money, habits) in Sm3gm's Quick Menu (G or D-pad Down), if you have it. For testing; Quick Menu isn't required.");
		}
	}
	public static class PluginInfo
	{
		public const string Guid = "ekem.creaturediscomforts";

		public const string Name = "Creature Discomforts";

		public const string Version = "1.4.0";
	}
	internal static class QuickMenuHook
	{
		public static string Page = "Creature Discomforts";

		private static Func<string?> Debug(string label)
		{
			return () => (!Plugin.Cfg.QuickMenu.Value) ? null : label;
		}

		public static IEnumerable<(string id, Func<string?> label, Action run)> Entries()
		{
			yield return (id: "cd.survey", label: Debug("Self survey"), run: SelfSurvey.Run);
			yield return (id: "cd.overlay", label: Debug("Needs panel"), run: NeedsOverlay.Toggle);
			yield return (id: "cd.shop", label: Debug("Shop survey"), run: ShopSurvey.Run);
			yield return (id: "cd.wounds", label: Debug("Wounds survey"), run: WoundSurvey.Run);
			yield return (id: "cd.cold", label: Debug("Cold +0.2"), run: Illness.DebugBump);
			yield return (id: "cd.habits", label: Debug("Habits +0.35"), run: Addiction.DebugBump);
			yield return (id: "cd.money", label: Debug("+10000 money"), run: delegate
			{
				if (!((Object)(object)GameplayController.Instance == (Object)null))
				{
					GameplayController.Instance.AddMoney(10000, true, "debug");
					Plugin.Log.LogInfo((object)"[hotkey] +10000 money");
				}
			});
		}
	}
	public static class SleepHook
	{
		public static float MinutesToFallAsleep()
		{
			string keptUpBy;
			return FallingAsleep.EstimateMinutes(out keptUpBy);
		}

		public static string? KeptAwakeBy()
		{
			FallingAsleep.EstimateMinutes(out string keptUpBy);
			return keptUpBy;
		}

		public static string? Napped(float hours, bool woken)
		{
			return FallingAsleep.Napped(hours, woken);
		}

		public static void Dozing(float hours)
		{
			FallingAsleep.Dozing(hours);
		}

		public static string? WokeFromDoze(float totalHours, bool woken)
		{
			return FallingAsleep.WokeFromDoze(totalHours, woken);
		}

		public static bool Asleep()
		{
			return FallingAsleep.Asleep;
		}
	}
}
namespace CreatureDiscomforts.Survey
{
	public static class IconDump
	{
		public static void Run()
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Expected O, but got Unknown
			string text = Path.Combine(Paths.BepInExRootPath, "CreatureDiscomforts-icons");
			Directory.CreateDirectory(text);
			int num = 0;
			bool flag = default(bool);
			foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<StatusPreset>()))
			{
				StatusPreset val = ((Il2CppObjectBase)item).TryCast<StatusPreset>();
				if ((Object)(object)((val != null) ? val.icon : null) == (Object)null)
				{
					continue;
				}
				try
				{
					File.WriteAllBytes(Path.Combine(text, ((Object)val).name + ".png"), Encode(val.icon));
					num++;
				}
				catch (Exception ex)
				{
					ManualLogSource log = Plugin.Log;
					BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(16, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[status] icon ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)val).name);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
					}
					log.LogWarning(val2);
				}
			}
			ManualLogSource log2 = Plugin.Log;
			BepInExInfoLogInterpolatedStringHandler val3 = new BepInExInfoLogInterpolatedStringHandler(34, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("[status] ");
				((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<int>(num);
				((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" status icons written to ");
				((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(text);
			}
			log2.LogInfo(val3);
		}

		private static byte[] Encode(Sprite sprite)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			Texture2D texture = sprite.texture;
			Rect textureRect = sprite.textureRect;
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0);
			RenderTexture active = RenderTexture.active;
			try
			{
				Graphics.Blit((Texture)(object)texture, temporary);
				RenderTexture.active = temporary;
				Texture2D val = new Texture2D((int)((Rect)(ref textureRect)).width, (int)((Rect)(ref textureRect)).height, (TextureFormat)4, false);
				val.ReadPixels(textureRect, 0, 0);
				val.Apply();
				return Il2CppArrayBase<byte>.op_Implicit((Il2CppArrayBase<byte>)(object)ImageConversion.EncodeToPNG(val));
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
			}
		}
	}
	public static class SelfSurvey
	{
		public static void Run()
		{
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Expected O, but got Unknown
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Expected O, but got Unknown
			//IL_0270: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Expected O, but got Unknown
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0351: Expected O, but got Unknown
			Game instance = Game.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				Plugin.Log.LogWarning((object)"[me] no game instance");
				return;
			}
			List<string> on = new List<string>();
			List<string> off = new List<string>();
			Check("cold", instance.coldStatusEnabled);
			Check("smelly", instance.smellyStatusEnabled);
			Check("headache", instance.headacheStatusEnabled);
			Check("injury", instance.injuryStatusEnabled);
			Check("tired", instance.tiredStatusEnabled);
			Check("hunger", instance.hungerStatusEnabled);
			Check("hydration", instance.hydrationStatusEnabled);
			Check("numb", instance.numbStatusEnabled);
			Check("bleeding", instance.bleedingStatusEnabled);
			Check("wet", instance.wetStatusEnabled);
			Check("sick", instance.sickStatusEnabled);
			Check("drunk", instance.drunkStatusEnabled);
			Check("starch addiction", instance.starchAddictionEnabled);
			Check("poison", instance.poisonStatusEnabled);
			Check("blinded", instance.blindedStatusEnabled);
			Check("energized", instance.energizedStatusEnabled);
			Check("hydrated", instance.hydratedStatusEnabled);
			Check("focused", instance.focusedStatusEnabled);
			Check("well rested", instance.wellRestedStatusEnabled);
			ManualLogSource log = Plugin.Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(22, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] statuses ON  (");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(on.Count);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("): ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(string.Join(", ", on));
			}
			log.LogInfo(val);
			ManualLogSource log2 = Plugin.Log;
			val = new BepInExInfoLogInterpolatedStringHandler(22, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] statuses OFF (");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(off.Count);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("): ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(string.Join(", ", off));
			}
			log2.LogInfo(val);
			Player instance2 = Player.Instance;
			Human val2 = ((instance2 != null) ? ((Il2CppObjectBase)instance2).TryCast<Human>() : null);
			if ((Object)(object)val2 == (Object)null)
			{
				Plugin.Log.LogInfo((object)"[me] no player to read");
				return;
			}
			ManualLogSource log3 = Plugin.Log;
			val = new BepInExInfoLogInterpolatedStringHandler(52, 6, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] food ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(val2.nourishment, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", water ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(val2.hydration, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("energy ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(val2.energy, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", alert ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(val2.alertness, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("hygiene ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(val2.hygiene, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", heat ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(val2.heat, "F2");
			}
			log3.LogInfo(val);
			ManualLogSource log4 = Plugin.Log;
			val = new BepInExInfoLogInterpolatedStringHandler(44, 5, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] sick ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(val2.sick, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", wet ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(val2.wet, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", drunk ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(val2.drunk, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("headache ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(val2.headache, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", health ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(((Actor)val2).currentHealth, "F2");
			}
			log4.LogInfo(val);
			StatusEffects();
			IconDump.Run();
			void Check(string name, bool enabled)
			{
				(enabled ? on : off).Add(name);
			}
		}

		private static void StatusEffects()
		{
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_028a: Expected O, but got Unknown
			StatusController instance = StatusController.Instance;
			HashSet<StatusPreset> val = ((instance != null) ? instance.activeStatuses : null);
			bool flag2 = default(bool);
			foreach (StatusPreset item in from o in (IEnumerable<Object>)Resources.FindObjectsOfTypeAll(Il2CppType.Of<StatusPreset>())
				select ((Il2CppObjectBase)o).TryCast<StatusPreset>() into p
				where (SoCustomComparison)(object)p != (SoCustomComparison)null
				orderby ((Object)p).name
				select p)
			{
				List<string> parts = new List<string>();
				Flag("stopsRecovery", item.stopsRecovery);
				Flag("stopsSprint", item.stopsSprint);
				Flag("stopsJump", item.stopsJump);
				Num("recovery", item.recoveryRatePlusMP);
				Num("maxHealth", item.maxHealthPlusMP);
				Num("speed", item.movementSpeedPlusMP);
				Num("tempGain", item.temperatureGainPlusMP);
				Num("dmgIn", item.damageIncomingPlusMP);
				Num("dmgOut", item.damageOutgoingPlusMP);
				Num("drunkControls", item.drunkControls);
				Num("tripWet", item.tripChanceWet);
				Num("tripDrunk", item.tripChanceDrunk);
				Num("drunkVision", item.drunkVision);
				Num("shiver", item.shiverVision);
				Num("headacheVision", item.headacheVision);
				Num("lens", item.drunkLensDistort);
				Num("headBob", item.affectHeadBob);
				Num("bloom", item.bloomIntensityPlusMP);
				Num("blur", item.motionBlurPlusMP);
				Num("chromatic", item.chromaticAbberationAmount);
				Num("vignette", item.vignetteAmount);
				Num("exposure", item.expsosure);
				Flag("channelMixer", item.useChannelMixer);
				bool flag = val?.Contains(item) ?? false;
				string text = ((parts.Count == 0) ? "(nothing)" : string.Join(", ", parts));
				ManualLogSource log = Plugin.Log;
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(11, 3, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[status] ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(flag ? "*" : " ");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)item).name.PadRight(22));
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text);
				}
				log.LogInfo(val2);
				void Flag(string name, bool on)
				{
					if (on)
					{
						parts.Add(name);
					}
				}
				void Num(string name, float v)
				{
					if (v != 0f)
					{
						parts.Add($"{name} {v:+0.##;-0.##}");
					}
				}
			}
		}
	}
	public static class ShopSurvey
	{
		private static readonly (string Name, Func<RetailItemPreset, float> Read)[] Effects = new(string, Func<RetailItemPreset, float>)[24]
		{
			("nourishment", (RetailItemPreset r) => r.nourishment),
			("hydration", (RetailItemPreset r) => r.hydration),
			("alertness", (RetailItemPreset r) => r.alertness),
			("energy", (RetailItemPreset r) => r.energy),
			("wellRested", (RetailItemPreset r) => r.wellRested),
			("excitement", (RetailItemPreset r) => r.excitement),
			("chores", (RetailItemPreset r) => r.chores),
			("hygiene", (RetailItemPreset r) => r.hygiene),
			("bladder", (RetailItemPreset r) => r.bladder),
			("heat", (RetailItemPreset r) => r.heat),
			("wet", (RetailItemPreset r) => r.wet),
			("drunk", (RetailItemPreset r) => r.drunk),
			("sick", (RetailItemPreset r) => r.sick),
			("headache", (RetailItemPreset r) => r.headache),
			("starchAddiction", (RetailItemPreset r) => r.starchAddiction),
			("poisoned", (RetailItemPreset r) => r.poisoned),
			("numb", (RetailItemPreset r) => r.numb),
			("bleeding", (RetailItemPreset r) => r.bleeding),
			("bruised", (RetailItemPreset r) => r.bruised),
			("blackEye", (RetailItemPreset r) => r.blackEye),
			("brokenLeg", (RetailItemPreset r) => r.brokenLeg),
			("blackedOut", (RetailItemPreset r) => r.blackedOut),
			("breath", (RetailItemPreset r) => r.breath),
			("health", (RetailItemPreset r) => r.health)
		};

		private const int ShownSellers = 5;

		private static Dictionary<string, List<string>> Sellers()
		{
			Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
			CityData instance = CityData.Instance;
			List<Company> val = ((instance != null) ? instance.companyDirectory : null);
			if (val == null)
			{
				return dictionary;
			}
			Enumerator<Company> enumerator = val.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Company current = enumerator.Current;
				if (((current != null) ? current.prices : null) == null)
				{
					continue;
				}
				NewAddress address = current.address;
				string text = ((address != null) ? ((Object)address).name : null);
				string value = ((text != null && text.Length > 0 && text != current.name) ? (current.name + " (" + text + ")") : current.name);
				Enumerator<InteractablePreset, int> enumerator2 = current.prices.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					KeyValuePair<InteractablePreset, int> current2 = enumerator2.Current;
					InteractablePreset key = current2.Key;
					string key2 = ((key != null) ? ((SoCustomComparison)key).presetName : null) ?? "";
					if (!dictionary.TryGetValue(key2, out var value2))
					{
						value2 = (dictionary[key2] = new List<string>());
					}
					value2.Add($"{value} cr{current2.Value}");
				}
			}
			return dictionary;
		}

		public static void Run()
		{
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0477: Unknown result type (might be due to invalid IL or missing references)
			//IL_047e: Expected O, but got Unknown
			//IL_05a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ab: Expected O, but got Unknown
			//IL_034c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0351: Unknown result type (might be due to invalid IL or missing references)
			//IL_0369: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			Toolbox instance = Toolbox.Instance;
			Dictionary<string, InteractablePreset> val = ((instance != null) ? instance.objectPresetDictionary : null);
			if (val == null)
			{
				Plugin.Log.LogWarning((object)"[shop] no preset dictionary yet");
				return;
			}
			Dictionary<string, List<string>> dictionary = Sellers();
			List<(string, string, string, string)> list = new List<(string, string, string, string)>();
			Enumerator<string, InteractablePreset> enumerator = val.GetEnumerator();
			bool isConsumable = default(bool);
			while (enumerator.MoveNext())
			{
				KeyValuePair<string, InteractablePreset> current = enumerator.Current;
				InteractablePreset value = current.Value;
				RetailItemPreset retail = ((value != null) ? value.retailItem : null);
				if (!((SoCustomComparison)(object)retail == (SoCustomComparison)null))
				{
					List<(string, float)> list2 = (from e in Effects
						select (Name: e.Name, Value: e.Read(retail)) into e
						where e.Value != 0f
						select e).ToList();
					string text = ((object)retail.menuCategory/*cast due to .constrained prefix*/).ToString();
					string value2 = ((value.value.x == value.value.y) ? $"{value.value.x:0}" : $"{value.value.x:0}-{value.value.y:0}");
					string value3 = (string.IsNullOrEmpty(retail.brandName) ? "" : (" [" + retail.brandName + "]"));
					string value4 = ((list2.Count == 0) ? "(no effect)" : string.Join(", ", list2.Select<(string, float), string>(((string Name, float Value) e) => $"{e.Name} {e.Value:+0.##;-0.##}")));
					dictionary.TryGetValue(((SoCustomComparison)value).presetName ?? "", out var value5);
					if (value5 == null)
					{
						value5 = new List<string>();
					}
					string value6 = ((value5.Count == 0) ? "not sold" : ($"{value5.Count} shops: " + string.Join("; ", value5.Take(5)) + ((value5.Count > 5) ? "; ..." : "")));
					string key = current.Key;
					string item = $"[shop] {text,-10} {current.Key}{value3}  cr{value2}  {value4}\n[shop]            at {value6}";
					string[] obj = new string[9]
					{
						text,
						current.Key,
						retail.brandName ?? "",
						value.value.x.ToString("0"),
						value.value.y.ToString("0"),
						null,
						null,
						null,
						null
					};
					isConsumable = retail.isConsumable;
					obj[5] = isConsumable.ToString();
					obj[6] = value.consumableAmount.ToString("0.##");
					obj[7] = value5.Count.ToString();
					obj[8] = string.Join("; ", value5);
					list.Add((text, key, item, string.Join("\t", obj.Concat(Effects.Select(((string Name, Func<RetailItemPreset, float> Read) e) => e.Read(retail).ToString("0.###"))))));
				}
			}
			list.Sort(delegate((string Category, string Name, string Line, string Tsv) a, (string Category, string Name, string Line, string Tsv) b)
			{
				int num = string.CompareOrdinal(a.Category, b.Category);
				return (num == 0) ? string.CompareOrdinal(a.Name, b.Name) : num;
			});
			foreach (var item2 in list)
			{
				Plugin.Log.LogInfo((object)item2.Item3);
			}
			ManualLogSource log = Plugin.Log;
			BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(20, 1, ref isConsumable);
			if (isConsumable)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[shop] ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(list.Count);
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" retail items");
			}
			log.LogInfo(val2);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine(string.Join("\t", new string[9] { "category", "preset", "brand", "priceMin", "priceMax", "consumable", "amount", "shops", "soldAt" }.Concat(Effects.Select(((string Name, Func<RetailItemPreset, float> Read) e) => e.Name))));
			foreach (var item3 in list)
			{
				stringBuilder.AppendLine(item3.Item4);
			}
			string text2 = Path.Combine(Paths.BepInExRootPath, "CreatureDiscomforts-shop.tsv");
			File.WriteAllText(text2, stringBuilder.ToString());
			ManualLogSource log2 = Plugin.Log;
			val2 = new BepInExInfoLogInterpolatedStringHandler(16, 1, ref isConsumable);
			if (isConsumable)
			{
				((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[shop] table -> ");
				((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text2);
			}
			log2.LogInfo(val2);
		}
	}
	public static class WoundSurvey
	{
		public static void Run()
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			Player instance = Player.Instance;
			GameplayControls instance2 = GameplayControls.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null)
			{
				Plugin.Log.LogInfo((object)"[me] wounds: no game");
				return;
			}
			ManualLogSource log = Plugin.Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(129, 10, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] wounds: bleeding ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(((Human)instance).bleeding, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", bruised ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(((Human)instance).bruised, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", black eye ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(((Human)instance).blackEye, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("broken leg ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(((Human)instance).brokenLeg, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", health ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(((Actor)instance).currentHealth, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("/");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(((Actor)instance).maximumHealth, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("; ");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("per hit chance: bleeding ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(instance2.combatHitChanceOfBleeding, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", bruised ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(instance2.combatHitChanceOfBruised, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("black eye ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(instance2.combatHitChanceOfBlackEye, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", broken leg ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(instance2.combatHitChanceOfBrokenLeg, "F2");
			}
			log.LogInfo(val);
		}
	}
}
namespace CreatureDiscomforts.Model
{
	public static class Addiction
	{
		public sealed class Saved
		{
			public Dictionary<string, float>? Habit { get; set; }

			public Dictionary<string, float>? Withdrawal { get; set; }
		}

		public static readonly Substance[] Tracked = new Substance[5]
		{
			Substance.Caffeine,
			Substance.Nicotine,
			Substance.Alcohol,
			Substance.Codeine,
			Substance.SleepingPills
		};

		private const float ReliefLossAtFull = 0.4f;

		private const float AlcoholCravingAt = 0.1f;

		private const float CeilingAt = 0.7f;

		private const float ClearPerHour = 3f;

		private const float FadePerHour = 0.15f;

		private const float DebugStep = 0.35f;

		private static readonly Dictionary<Substance, float> _habit = new Dictionary<Substance, float>();

		private static readonly Dictionary<Substance, float> _withdrawal = new Dictionary<Substance, float>();

		public static bool Enabled => Plugin.Cfg.Addictions.Value;

		private static bool Tolerant
		{
			get
			{
				if (Enabled)
				{
					return Plugin.Cfg.Tolerance.Value;
				}
				return false;
			}
		}

		private static float Window(Substance s)
		{
			return s switch
			{
				Substance.Caffeine => 12f, 
				Substance.Nicotine => 6f, 
				Substance.Alcohol => 24f, 
				Substance.Codeine => 12f, 
				Substance.SleepingPills => 24f, 
				_ => 0f, 
			};
		}

		private static float EffectAtFull(Substance s)
		{
			return s switch
			{
				Substance.Caffeine => 0.4f, 
				Substance.Alcohol => 0.2f, 
				Substance.Codeine => 0.3f, 
				Substance.Nicotine => 0.25f, 
				Substance.SleepingPills => 0.3f, 
				_ => 0f, 
			};
		}

		private static float OverdoseAtFull(Substance s)
		{
			return s switch
			{
				Substance.Caffeine => 0.1f, 
				Substance.Alcohol => 0.1f, 
				Substance.Codeine => 0.25f, 
				_ => 0f, 
			};
		}

		public static float Habit(Substance s)
		{
			if (!_habit.TryGetValue(s, out var value))
			{
				return 0f;
			}
			return value;
		}

		public static float Withdrawal(Substance s)
		{
			if (!Enabled || !_withdrawal.TryGetValue(s, out var value))
			{
				return 0f;
			}
			return value;
		}

		public static bool Hooked(Substance s)
		{
			return Habit(s) >= Plugin.Cfg.HookedAbove.Value;
		}

		public static float EffectShift(Substance s)
		{
			if (!Tolerant)
			{
				return 0f;
			}
			return EffectAtFull(s) * Habit(s);
		}

		public static float OverdoseShift(Substance s)
		{
			if (!Tolerant)
			{
				return 0f;
			}
			return OverdoseAtFull(s) * Habit(s);
		}

		public static float CodeineRelief()
		{
			return 1f - (Tolerant ? (0.4f * Habit(Substance.Codeine)) : 0f);
		}

		public static float CravingAt(Substance s)
		{
			if (s != Substance.Alcohol)
			{
				return Substances.ActiveAt(s);
			}
			return 0.1f + EffectShift(s);
		}

		private static float Rate(Substance s)
		{
			return s switch
			{
				Substance.Caffeine => Plugin.Cfg.CaffeineHabitRate.Value, 
				Substance.Nicotine => Plugin.Cfg.NicotineHabitRate.Value, 
				Substance.Alcohol => Plugin.Cfg.AlcoholHabitRate.Value, 
				Substance.Codeine => Plugin.Cfg.CodeineHabitRate.Value, 
				Substance.SleepingPills => Plugin.Cfg.SleepingPillsHabitRate.Value, 
				_ => 0f, 
			};
		}

		public static void Tick(float dt, Dictionary<Substance, float> exposure, Player player)
		{
			if (!Enabled || dt <= 0f)
			{
				return;
			}
			Settings cfg = Plugin.Cfg;
			float num = Mathf.Max(0f, cfg.HabitDecayPerDay.Value) / 24f;
			float value = cfg.HookedAbove.Value;
			float value2 = cfg.WithdrawalAt.Value;
			Substance[] tracked = Tracked;
			foreach (Substance substance in tracked)
			{
				float value3;
				float num2 = ((substance == Substance.Alcohol) ? (((Human)player).drunk * Mathf.Min(dt, 1f)) : (exposure.TryGetValue(substance, out value3) ? value3 : 0f));
				float num3 = Mathf.Clamp01(Habit(substance) + Rate(substance) * num2 - num * dt);
				_habit[substance] = num3;
				float num4 = (_withdrawal.TryGetValue(substance, out var value4) ? value4 : 0f);
				if (Substances.Level(substance) >= CravingAt(substance))
				{
					num4 -= 3f * dt;
				}
				else if (num3 >= value && Window(substance) > 0f)
				{
					float num5 = Mathf.Clamp01(num3 / 0.7f);
					num4 = ((!(num4 < num5)) ? Mathf.Max(num5, num4 - 0.15f * dt) : Mathf.Min(num5, num4 + value2 / Window(substance) * num3 * dt));
				}
				else
				{
					num4 -= 0.15f * dt;
				}
				_withdrawal[substance] = Mathf.Clamp01(num4);
			}
		}

		public static void Treated(float left)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			foreach (Substance item in _withdrawal.Keys.ToList())
			{
				_withdrawal[item] *= left;
			}
			ManualLogSource log = Plugin.Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(33, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] hospital: withdrawal eased, ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Describe());
			}
			log.LogInfo(val);
		}

		public static void DebugBump()
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			bool flag = Tracked.Any((Substance s) => Habit(s) >= 0.99f);
			Substance[] tracked = Tracked;
			foreach (Substance substance in tracked)
			{
				_habit[substance] = (flag ? 0f : Mathf.Clamp01(Habit(substance) + 0.35f));
				if (flag)
				{
					_withdrawal[substance] = 0f;
				}
			}
			ManualLogSource log = Plugin.Log;
			bool flag2 = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(20, 1, ref flag2);
			if (flag2)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] addiction set: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Describe());
			}
			log.LogInfo(val);
		}

		public static string Describe()
		{
			return string.Join(", ", Tracked.Select((Substance s) => $"{s.ToString().ToLowerInvariant()} {Habit(s):F2}/{Withdrawal(s):F2}"));
		}

		public static Saved Save()
		{
			return new Saved
			{
				Habit = _habit.Where((KeyValuePair<Substance, float> p) => p.Value > 0f).ToDictionary((KeyValuePair<Substance, float> p) => p.Key.ToString(), (KeyValuePair<Substance, float> p) => p.Value),
				Withdrawal = _withdrawal.Where((KeyValuePair<Substance, float> p) => p.Value > 0f).ToDictionary((KeyValuePair<Substance, float> p) => p.Key.ToString(), (KeyValuePair<Substance, float> p) => p.Value)
			};
		}

		public static void Load(Saved? saved)
		{
			_habit.Clear();
			_withdrawal.Clear();
			Read(saved?.Habit, _habit);
			Read(saved?.Withdrawal, _withdrawal);
		}

		private static void Read(Dictionary<string, float>? from, Dictionary<Substance, float> to)
		{
			if (from == null)
			{
				return;
			}
			foreach (KeyValuePair<string, float> item in from)
			{
				if (Enum.TryParse<Substance>(item.Key, out var result) && Tracked.Contains(result))
				{
					to[result] = Mathf.Clamp01(item.Value);
				}
			}
		}
	}
	public static class Illness
	{
		private sealed class Saved
		{
			public float Illness { get; set; }

			public float? Immunity { get; set; }

			public float? Body { get; set; }

			public float? WaterBalance { get; set; }

			public Dictionary<string, float>? Relieved { get; set; }

			public Dictionary<string, List<float>>? Doses { get; set; }

			public Dictionary<string, List<Substances.SavedDose>>? Substances { get; set; }

			public Substances.Saved? Blood { get; set; }

			public Addiction.Saved? Addiction { get; set; }

			public float? Awake { get; set; }

			public float? SprainedUntil { get; set; }

			public bool? Splinted { get; set; }

			public bool? Strapped { get; set; }

			public Sleeper.Saved? Sleeper { get; set; }
		}

		private const string FileName = "creaturediscomforts.json";

		private const float MaxStep = 1f;

		private static float _lastGameTime = float.NaN;

		private static float _nextReport = float.NaN;

		public static float Level { get; private set; }

		public static void Install()
		{
			Lib.SaveGame.OnBeforeSave += OnBeforeSave;
			Lib.SaveGame.OnAfterLoad += OnAfterLoad;
			Lib.SaveGame.OnBeforeNewGame += delegate
			{
				Reset(0f);
				Remedies.Load(null, null);
				Substances.Load(null, null);
				Addiction.Load(null);
				Mixing.Reset();
				Overdose.Reset();
				Withdrawal.Reset();
				SmokingHunger.Reset();
				Pain.Load(null);
				Ankle.Load(null, null, null);
				Running.Reset();
				FallingAsleep.Reset();
				Sleeper.Roll();
			};
			Lib.SaveGame.OnBeforeDelete += OnBeforeDelete;
		}

		public static float Coldness(Human player)
		{
			float value = Plugin.Cfg.ColdThreshold.Value;
			if (!(value <= 0f))
			{
				return Mathf.Clamp01(1f - player.heat / value);
			}
			return 0f;
		}

		public static bool Asleep()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Invalid comparison between Unknown and I4
			InteractionController instance = InteractionController.Instance;
			Interactable val = ((instance != null) ? instance.lockedInInteraction : null);
			if ((SoCustomComparison)(object)((val != null) ? val.preset : null) != (SoCustomComparison)null)
			{
				return (int)val.preset.specialCaseFlag == 1;
			}
			return false;
		}

		public static void Tick()
		{
			SessionData instance = SessionData.Instance;
			Player instance2 = Player.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null)
			{
				_lastGameTime = float.NaN;
				return;
			}
			float gameTime = instance.gameTime;
			float num = (float.IsNaN(_lastGameTime) ? 0f : (gameTime - _lastGameTime));
			_lastGameTime = gameTime;
			if (num < 0f || num > 1f)
			{
				num = 0f;
			}
			Starvation.Apply(instance2, num);
			Immunity.Tick(instance2, num);
			if (!Plugin.Cfg.CatchingColds.Value)
			{
				Level = 0f;
			}
			else if (num > 0f)
			{
				float num2 = Coldness((Human)(object)instance2);
				float num3 = Mathf.Clamp01(((Human)instance2).wet);
				float num4 = Plugin.Cfg.CatchFromCold.Value * num2 + Plugin.Cfg.CatchFromWet.Value * num3 + Plugin.Cfg.CatchFromBoth.Value * num2 * num3;
				num4 *= Immunity.CatchMultiplier;
				if (num4 > 0f)
				{
					Level = Mathf.Clamp01(Level + num4 * num);
				}
				else if (((Human)instance2).heat >= Plugin.Cfg.RecoverAboveHeat.Value)
				{
					Level = Mathf.Clamp01(Level - Plugin.Cfg.RecoveryPerHour.Value * num * (Asleep() ? Plugin.Cfg.SleepRecovery.Value : 1f) * Immunity.RecoveryMultiplier);
				}
			}
			Symptoms.Apply(instance2, Level, num);
			Hourly(instance2, gameTime);
		}

		private static void Hourly(Player player, float now)
		{
			if (Plugin.Cfg.DebugLogging.Value && (float.IsNaN(_nextReport) || !(now < _nextReport) || !(now > _nextReport - 2f)))
			{
				_nextReport = Mathf.Floor(now) + 1f;
				StatusController instance = StatusController.Instance;
				Plugin.Log.LogInfo((object)($"[me] hourly {now:F1}h: illness {Level:F2}, immunity {Immunity.Level:F2}, heat {((Human)player).heat:F2}, wet {((Human)player).wet:F2}, health {((Actor)player).currentHealth:F2}/{((Actor)player).maximumHealth:F2}, drunk {((Human)player).drunk:F2}, food {((Human)player).nourishment:F2}, water {((Human)player).hydration:F2}, energy {((Human)player).energy:F2}, sick {((Human)player).sick:F2}, body {Reserves.Body:F2}, water balance {Reserves.Water:F2}, caffeine {Substances.Level(Substance.Caffeine):F2}, codeine {Substances.Level(Substance.Codeine):F2}, pills {Substances.Level(Substance.SleepingPills):F2}, nicotine {Substances.Level(Substance.Nicotine):F2}, habit/withdrawal: {Addiction.Describe()}, smoking debt {SmokingHunger.Debt:F2}, heat loss x{((instance != null) ? instance.temperatureGainMultiplier : 1f):F2}, recovery {(((Object)(object)instance != (Object)null && instance.disabledRecovery) ? "off" : "on")}" + (Asleep() ? ", asleep" : "")));
			}
		}

		public static void DebugBump()
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			Level = ((Level >= 0.99f) ? 0f : Mathf.Clamp01(Level + 0.2f));
			ManualLogSource log = Plugin.Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(20, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] illness set to ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(Level, "F2");
			}
			log.LogInfo(val);
		}

		private static void Reset(float level)
		{
			Level = level;
			_lastGameTime = float.NaN;
			Immunity.Reset(1f);
			Reserves.Reset(1f, 1f);
		}

		private static string PathFor(SaveGameArgs args)
		{
			return Lib.SaveGame.GetSaveGameDataPath(args, "creaturediscomforts.json");
		}

		private static void OnBeforeSave(object? sender, SaveGameArgs e)
		{
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Expected O, but got Unknown
			try
			{
				File.WriteAllText(PathFor(e), JsonSerializer.Serialize(new Saved
				{
					Illness = Level,
					Immunity = Immunity.Level,
					Body = Reserves.Body,
					WaterBalance = Reserves.Water,
					Relieved = Remedies.SaveRelief(),
					Doses = Remedies.SaveDoses(),
					Blood = Substances.Save(),
					Addiction = Addiction.Save(),
					Awake = Pain.Awake,
					SprainedUntil = Ankle.SprainedUntil,
					Splinted = Ankle.Splinted,
					Strapped = Ankle.Strapped,
					Sleeper = Sleeper.Save()
				}));
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(21, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] failed to save: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				log.LogError(val);
			}
		}

		private static void OnAfterLoad(object? sender, SaveGameArgs e)
		{
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Expected O, but got Unknown
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Expected O, but got Unknown
			Reset(0f);
			Remedies.Load(null, null);
			Substances.Load(null, null);
			Addiction.Load(null);
			Mixing.Reset();
			Overdose.Reset();
			Withdrawal.Reset();
			SmokingHunger.Reset();
			Pain.Load(null);
			Ankle.Load(null, null, null);
			Running.Reset();
			FallingAsleep.Reset();
			string path = PathFor(e);
			if (!File.Exists(path))
			{
				Sleeper.Roll();
				return;
			}
			bool flag = default(bool);
			try
			{
				Saved saved = JsonSerializer.Deserialize<Saved>(File.ReadAllText(path));
				Reset(Mathf.Clamp01(saved?.Illness ?? 0f));
				Immunity.Reset(saved?.Immunity ?? 1f);
				Reserves.Reset(saved?.Body ?? 1f, saved?.WaterBalance ?? 1f);
				Remedies.Load(saved?.Relieved, saved?.Doses);
				Substances.Load(saved?.Blood, saved?.Substances);
				Addiction.Load(saved?.Addiction);
				Pain.Load(saved?.Awake);
				Ankle.Load(saved?.SprainedUntil, saved?.Splinted, saved?.Strapped);
				Sleeper.Load(saved?.Sleeper);
				Mixing.Reset();
				ManualLogSource log = Plugin.Log;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(62, 4, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] loaded illness ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(Level, "F2");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", immunity ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(Immunity.Level, "F2");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("habit/withdrawal: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Addiction.Describe());
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", sleeper: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Sleeper.Describe());
				}
				log.LogInfo(val);
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = Plugin.Log;
				BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(45, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[me] unreadable save data, starting healthy: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
				}
				log2.LogError(val2);
			}
		}

		private static void OnBeforeDelete(object? sender, SaveGameArgs e)
		{
			string path = PathFor(e);
			if (File.Exists(path))
			{
				File.Delete(path);
			}
		}
	}
	public static class Immunity
	{
		private const float Low = 0.2f;

		private const float High = 0.9f;

		public static float Level { get; private set; } = 1f;

		public static float CatchMultiplier
		{
			get
			{
				if (!Plugin.Cfg.Immunity.Value)
				{
					return 1f;
				}
				return Mathf.Lerp(Mathf.Max(1f, Plugin.Cfg.LowImmunityCatch.Value), 1f, Level);
			}
		}

		public static float RecoveryMultiplier
		{
			get
			{
				if (!Plugin.Cfg.Immunity.Value)
				{
					return 1f;
				}
				return Mathf.Lerp(Mathf.Clamp01(Plugin.Cfg.LowImmunityRecovery.Value), 1f, Level);
			}
		}

		public static void Reset(float level)
		{
			Level = Mathf.Clamp01(level);
		}

		public static void Tick(Player player, float dt)
		{
			Settings cfg = Plugin.Cfg;
			if (!cfg.Immunity.Value)
			{
				Level = 1f;
			}
			else
			{
				if (dt <= 0f || ((Actor)player).isDead || player.playerKOInProgress)
				{
					return;
				}
				Game instance = Game.Instance;
				if (!((Object)(object)instance == (Object)null))
				{
					int num = ((instance.hungerStatusEnabled && ((Human)player).nourishment <= 0.2f) ? 1 : 0) + ((instance.hydrationStatusEnabled && ((Human)player).hydration <= 0.2f) ? 1 : 0) + ((instance.tiredStatusEnabled && ((Human)player).energy <= 0.2f) ? 1 : 0);
					int num2 = (Starvation.IsStarving ? 1 : 0) + (Starvation.IsParched ? 1 : 0);
					float num3 = (float)(((instance.energizedStatusEnabled && ((Human)player).nourishment >= 0.9f) ? 1 : 0) + ((instance.hydratedStatusEnabled && ((Human)player).hydration >= 0.9f) ? 1 : 0) + ((instance.wellRestedStatusEnabled && ((Human)player).wellRested > 0f) ? 1 : 0)) * cfg.ImmunityGainPerHour.Value - (float)num * cfg.ImmunityLossPerHour.Value - (float)num2 * cfg.ImmunityLossStarving.Value;
					if (num == 0)
					{
						num3 += cfg.ImmunityBaseGain.Value;
					}
					Level = Mathf.Clamp01(Level + num3 * dt);
				}
			}
		}
	}
	public static class Knockouts
	{
		public const string CodeineOverdose = "codeine-overdose";

		public const string SleepingPillsOverdose = "sleeping-pills-overdose";

		public const string AlcoholAndSleepingPills = "alcohol-and-sleeping-pills";

		public static string Cause { get; private set; } = "";

		public static float At { get; private set; } = float.NaN;

		public static void Record(string cause, float gameTime)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			Cause = cause;
			At = gameTime;
			ManualLogSource log = Plugin.Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(23, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] knocked out: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(cause);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" at ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(gameTime, "F2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("h");
			}
			log.LogInfo(val);
		}
	}
	public static class Reserves
	{
		private const float EmptyingBelow = 0.2f;

		private const float RefillAbove = 0.5f;

		public static float Body { get; private set; } = 1f;

		public static float Water { get; private set; } = 1f;

		public static void Reset(float body, float water)
		{
			Body = Mathf.Clamp01(body);
			Water = Mathf.Clamp01(water);
		}

		public static void Tick(Player player, float dt)
		{
			if (!(dt <= 0f) && !((Actor)player).isDead)
			{
				Game instance = Game.Instance;
				Settings cfg = Plugin.Cfg;
				if ((Object)(object)instance != (Object)null && instance.hungerStatusEnabled)
				{
					Body = Step(Body, ((Human)player).nourishment, cfg.BodyLossPerHour.Value, cfg.BodyGainPerHour.Value, dt);
				}
				else
				{
					Body = 1f;
				}
				if ((Object)(object)instance != (Object)null && instance.hydrationStatusEnabled)
				{
					Water = Step(Water, ((Human)player).hydration, cfg.WaterLossPerHour.Value, cfg.WaterGainPerHour.Value, dt);
				}
				else
				{
					Water = 1f;
				}
			}
		}

		private static float Step(float reserve, float need, float loss, float gain, float dt)
		{
			if (need < 0.2f)
			{
				reserve -= loss * Mathf.Clamp01((0.2f - need) / 0.2f) * dt;
			}
			else if (need >= 0.5f)
			{
				reserve += gain * dt;
			}
			return Mathf.Clamp01(reserve);
		}
	}
	public enum Chronotype
	{
		Lark,
		Owl
	}
	public static class Sleeper
	{
		public sealed class Saved
		{
			public string? Chronotype { get; set; }

			public bool TvHelps { get; set; }

			public bool MusicHelps { get; set; }
		}

		public static Chronotype Chronotype { get; private set; }

		public static bool TvHelps { get; private set; }

		public static bool MusicHelps { get; private set; }

		public static void Roll()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			Chronotype = ((!(Random.value < 0.5f)) ? Chronotype.Owl : Chronotype.Lark);
			TvHelps = Random.value < 0.5f;
			MusicHelps = Random.value < 0.5f;
			ManualLogSource log = Plugin.Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(14, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] sleeper: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Describe());
			}
			log.LogInfo(val);
		}

		public static string Describe()
		{
			return $"{Chronotype.ToString().ToLowerInvariant()}, TV {(TvHelps ? "helps" : "keeps awake")}, music {(MusicHelps ? "helps" : "keeps awake")}";
		}

		public static float HourFit(float hour)
		{
			if (Chronotype == Chronotype.Lark)
			{
				return (hour >= 20f) ? 1f : ((hour >= 6f && hour < 14f) ? (-1f) : 0f);
			}
			return (hour < 5f) ? 1f : ((hour >= 19f) ? (-1f) : 0f);
		}

		public static Saved Save()
		{
			return new Saved
			{
				Chronotype = Chronotype.ToString(),
				TvHelps = TvHelps,
				MusicHelps = MusicHelps
			};
		}

		public static void Load(Saved? saved)
		{
			if (saved == null || saved.Chronotype == null || !Enum.TryParse<Chronotype>(saved.Chronotype, out var result))
			{
				Roll();
				return;
			}
			Chronotype = result;
			TvHelps = saved.TvHelps;
			MusicHelps = saved.MusicHelps;
		}
	}
	public enum Substance
	{
		Caffeine,
		Alcohol,
		Nicotine,
		Codeine,
		SleepingPills,
		Antidepressants
	}
	public static class Substances
	{
		[HarmonyPatch(typeof(DialogController), "PayMedicalFees")]
		public static class FeesPaid
		{
			[HarmonyPostfix]
			public static void Postfix()
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Expected O, but got Unknown
				try
				{
					TreatmentPaid();
				}
				catch (Exception ex)
				{
					ManualLogSource log = Plugin.Log;
					bool flag = default(bool);
					BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(25, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] hospital treatment: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					}
					log.LogWarning(val);
				}
			}
		}

		[HarmonyPatch(typeof(FirstPersonItemController), "OnConsumableFinished")]
		public static class Finished
		{
			[HarmonyPrefix]
			public static void Prefix(FirstPersonItemController __instance, Interactable consumableFinished)
			{
				//IL_0066: Unknown result type (might be due to invalid IL or missing references)
				//IL_006c: Expected O, but got Unknown
				try
				{
					if (!__instance.takeOneActive && consumableFinished != null && !(((Il2CppObjectBase)consumableFinished).Pointer != _held))
					{
						if (_lastCs > 0f && (SoCustomComparison)(object)consumableFinished.preset != (SoCustomComparison)null)
						{
							Credit(consumableFinished.preset, _lastCs, take: false);
						}
						_lastCs = 0f;
						Flush();
					}
				}
				catch (Exception ex)
				{
					ManualLogSource log = Plugin.Log;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(32, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] could not finish the dose: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					}
					log.LogError(val);
				}
			}
		}

		public sealed class Saved
		{
			public Dictionary<string, float>? Levels { get; set; }

			public float? CaffeineSpent { get; set; }
		}

		public sealed class SavedDose
		{
			public float T { get; set; }

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

			public float? A { get; set; }
		}

		private const float CaffeineAlertness = 0.5f;

		private const float DoseActive = 0.5f;

		private const float NicotineHalfLife = 2f;

		private const float AntidepressantsHalfLife = 24f;

		private const float Trace = 0.001f;

		private static readonly Dictionary<string, Substance[]> ByName = new Dictionary<string, Substance[]>
		{
			["Painkillers"] = new Substance[1] { Substance.Codeine },
			["CoughMedicine"] = new Substance[1] { Substance.Codeine },
			["Sleeping Pills"] = new Substance[1] { Substance.SleepingPills },
			["Antidepressants"] = new Substance[1] { Substance.Antidepressants }
		};

		private static readonly HashSet<string> Medicines = new HashSet<string> { "Painkillers", "CoughMedicine", "Sleeping Pills", "Antispasmodics", "Antidepressants", "CharcoalTablets" };

		private static readonly Dictionary<Substance, float> _levels = new Dictionary<Substance, float>();

		private static float _spent;

		private static float _cleared;

		private const float TiredFrom = 0.3f;

		private const float TiredRaise = 0.5f;

		private static float _lastGameTime = float.NaN;

		private const string HospitalWard = "HospitalWard";

		private static bool _inWard;

		private const float SafeShareOfOverdose = 0.8f;

		private static readonly Dictionary<Substance, float> _exposure = new Dictionary<Substance, float>();

		private static IntPtr _held;

		private static string _heldName = "";

		private static float _lastCs;

		private static readonly Dictionary<Substance, float> _session = new Dictionary<Substance, float>();

		private static int _lastSmoking;

		public static bool IsSmoked(InteractablePreset preset)
		{
			if (((SoCustomComparison)preset).presetName != null)
			{
				return ((SoCustomComparison)preset).presetName.StartsWith("Cigar", StringComparison.Ordinal);
			}
			return false;
		}

		public static bool IsMedicine(InteractablePreset preset)
		{
			if (((SoCustomComparison)preset).presetName != null)
			{
				return Medicines.Contains(((SoCustomComparison)preset).presetName);
			}
			return false;
		}

		public static List<Substance> Classify(InteractablePreset preset)
		{
			List<Substance> list = new List<Substance>();
			if (IsSmoked(preset))
			{
				return list;
			}
			RetailItemPreset retailItem = preset.retailItem;
			if ((SoCustomComparison)(object)retailItem != (SoCustomComparison)null)
			{
				if (Shelf.OriginalAlertness(preset) >= 0.5f)
				{
					list.Add(Substance.Caffeine);
				}
				if (retailItem.drunk > 0f)
				{
					list.Add(Substance.Alcohol);
				}
			}
			if (((SoCustomComparison)preset).presetName != null && ByName.TryGetValue(((SoCustomComparison)preset).presetName, out Substance[] value))
			{
				Substance[] array = value;
				foreach (Substance item in array)
				{
					if (!list.Contains(item))
					{
						list.Add(item);
					}
				}
			}
			return list;
		}

		private static float HalfLife(Substance s)
		{
			return s switch
			{
				Substance.Caffeine => Plugin.Cfg.CaffeineHalfLife.Value, 
				Substance.Codeine => Plugin.Cfg.CodeineHalfLife.Value, 
				Substance.SleepingPills => Plugin.Cfg.SleepingPillsHalfLife.Value, 
				Substance.Nicotine => 2f, 
				Substance.Antidepressants => 24f, 
				_ => 0f, 
			};
		}

		public static float Level(Substance s)
		{
			if (s == Substance.Alcohol)
			{
				Player instance = Player.Instance;
				if (instance == null)
				{
					return 0f;
				}
				return ((Human)instance).drunk;
			}
			if (!_levels.TryGetValue(s, out var value))
			{
				return 0f;
			}
			return value;
		}

		public static float CaffeineLevel()
		{
			return Level(Substance.Caffeine);
		}

		public static float Stimulation()
		{
			return Mathf.Max(0f, CaffeineLevel() - Plugin.Cfg.SedationWeight.Value * Level(Substance.SleepingPills));
		}

		public static float EffectShift(Substance s)
		{
			return Addiction.EffectShift(s);
		}

		public static float OverdoseShift(Substance s)
		{
			return Addiction.OverdoseShift(s);
		}

		public static float ActiveAt(Substance s)
		{
			float num = EffectShift(s);
			return num + s switch
			{
				Substance.Alcohol => Plugin.Cfg.MixingDrunkAbove.Value, 
				Substance.Caffeine => Plugin.Cfg.CaffeineWiredAbove.Value, 
				_ => 0.5f, 
			};
		}

		public static float CaffeineNoSleepAt()
		{
			float num = ActiveAt(Substance.Caffeine);
			if (!Plugin.Cfg.FallingAsleep.Value)
			{
				return num;
			}
			float num2 = (((Object)(object)Player.Instance != (Object)null) ? ((Human)Player.Instance).energy : 1f);
			float num3 = Mathf.Clamp01((0.3f - num2) / 0.3f);
			return Mathf.Max(num, Plugin.Cfg.CaffeineNoSleepAbove.Value + EffectShift(Substance.Caffeine) + 0.5f * num3);
		}

		public static float CaffeineFocusAt()
		{
			return Plugin.Cfg.CaffeineFocusAbove.Value + EffectShift(Substance.Caffeine);
		}

		public static bool Active(Substance s)
		{
			return ((s == Substance.Caffeine) ? Stimulation() : Level(s)) >= ActiveAt(s);
		}

		public static float TakeClearedCaffeine()
		{
			float cleared = _cleared;
			_cleared = 0f;
			return cleared;
		}

		public static void Tick()
		{
			SessionData instance = SessionData.Instance;
			Player instance2 = Player.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null)
			{
				_lastGameTime = float.NaN;
				_lastSmoking = 0;
				Forget();
				return;
			}
			float gameTime = instance.gameTime;
			float num = (float.IsNaN(_lastGameTime) ? 0f : (gameTime - _lastGameTime));
			_lastGameTime = gameTime;
			if (num > 0f)
			{
				Decay(num);
			}
			Addiction.Tick(num, _exposure, instance2);
			_exposure.Clear();
			TrackIntake();
			TrackSmoking();
			Treated(instance2);
		}

		private static void Treated(Player player)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			NewGameLocation currentGameLocation = ((Actor)player).currentGameLocation;
			NewAddress val = ((currentGameLocation != null) ? currentGameLocation.thisAsAddress : null);
			bool flag = (SoCustomComparison)(object)((val != null) ? val.addressPreset : null) != (SoCustomComparison)null && ((Object)val.addressPreset).name == "HospitalWard";
			if (flag == _inWard)
			{
				return;
			}
			_inWard = flag;
			if (flag)
			{
				Settings cfg = Plugin.Cfg;
				Cap(Substance.Caffeine, cfg.CaffeineOverdoseAbove.Value);
				Cap(Substance.Codeine, cfg.CodeineOverdoseAbove.Value);
				Cap(Substance.SleepingPills, cfg.SleepingPillsKnockoutAbove.Value);
				ManualLogSource log = Plugin.Log;
				bool flag2 = default(bool);
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(54, 3, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[me] hospital: stabilised, caffeine ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(Level(Substance.Caffeine), "F2");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", ");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("codeine ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(Level(Substance.Codeine), "F2");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", pills ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(Level(Substance.SleepingPills), "F2");
				}
				log.LogInfo(val2);
			}
		}

		private static void Cap(Substance s, float overdoseAt)
		{
			if (!(overdoseAt <= 0f))
			{
				float num = 0.8f * (overdoseAt + OverdoseShift(s));
				if (Level(s) > num)
				{
					_levels[s] = num;
				}
			}
		}

		public static void TreatmentPaid()
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			float num = Mathf.Clamp01(Plugin.Cfg.HospitalClearsTo.Value);
			foreach (Substance item in _levels.Keys.ToList())
			{
				_levels[item] *= num;
			}
			_spent *= num;
			ManualLogSource log = Plugin.Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(61, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] hospital: treated, substances down to ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(num, "P0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" of what they were");
			}
			log.LogInfo(val);
			Addiction.Treated(num);
		}

		private static void Decay(float dt)
		{
			foreach (Substance item in _levels.Keys.ToList())
			{
				float num = HalfLife(item);
				if (!(num <= 0f))
				{
					float num2 = _levels[item];
					float num3 = num2 * Mathf.Exp((0f - Mathf.Log(2f)) * dt / num);
					if (item == Substance.Caffeine)
					{
						_spent += num2 - num3;
					}
					_exposure[item] = (num2 - num3) * num / Mathf.Log(2f);
					_levels[item] = ((num3 < 0.001f) ? 0f : num3);
				}
			}
			float value = Plugin.Cfg.CaffeineHalfLife.Value;
			if (_spent > 0f && value > 0f)
			{
				float num4 = _spent * (1f - Mathf.Exp((0f - Mathf.Log(2f)) * dt / value));
				_spent -= num4;
				_cleared += num4;
				if (_spent < 0.001f)
				{
					_cleared += _spent;
					_spent = 0f;
				}
			}
		}

		private static void Add(Substance s, float amount, bool logged = true)
		{
			if (s != Substance.Alcohol && !(amount <= 0f))
			{
				_levels[s] = Level(s) + amount;
				if (logged)
				{
					_session[s] = (_session.TryGetValue(s, out var value) ? value : 0f) + amount;
				}
			}
		}

		private static void TrackIntake()
		{
			FirstPersonItemController instance = FirstPersonItemController.Instance;
			object obj;
			if (!((Object)(object)instance != (Object)null))
			{
				obj = null;
			}
			else
			{
				BioScreenController instance2 = BioScreenController.Instance;
				if (instance2 == null)
				{
					obj = null;
				}
				else
				{
					InventorySlot selectedSlot = instance2.selectedSlot;
					obj = ((selectedSlot != null) ? selectedSlot.GetInteractable() : null);
				}
			}
			Interactable val = (Interactable)obj;
			IntPtr intPtr = ((val != null) ? ((Il2CppObjectBase)val).Pointer : IntPtr.Zero);
			if (intPtr != _held)
			{
				Flush();
				_held = intPtr;
				object obj2;
				if (val == null)
				{
					obj2 = null;
				}
				else
				{
					InteractablePreset preset = val.preset;
					obj2 = ((preset != null) ? ((SoCustomComparison)preset).presetName : null);
				}
				if (obj2 == null)
				{
					obj2 = "";
				}
				_heldName = (string)obj2;
				_lastCs = ((val != null) ? val.cs : 0f);
			}
			else if (val != null && !((Object)(object)instance == (Object)null))
			{
				float cs = val.cs;
				if (instance.isConsuming && !instance.takeOneActive && cs < _lastCs && (SoCustomComparison)(object)val.preset != (SoCustomComparison)null)
				{
					Credit(val.preset, _lastCs - cs, take: false);
				}
				_lastCs = cs;
				if (!instance.isConsuming)
				{
					Flush();
				}
			}
		}

		private static void Credit(InteractablePreset preset, float amount, bool take)
		{
			foreach (Substance item in Classify(preset))
			{
				float amount2;
				if (item == Substance.Caffeine)
				{
					float consumableAmount = preset.consumableAmount;
					if (!take && consumableAmount <= 0f)
					{
						continue;
					}
					amount2 = Shelf.OriginalAlertness(preset) * (take ? 1f : (amount / consumableAmount));
				}
				else
				{
					amount2 = (take ? 1f : amount);
				}
				Add(item, amount2);
			}
		}

		private static void Flush()
		{
			if (_session.Count != 0)
			{
				Plugin.Log.LogInfo((object)("[me] intake (" + _heldName + "): " + string.Join(", ", _session.Select((KeyValuePair<Substance, float> p) => $"{p.Key} +{p.Value:F2} -> {Level(p.Key):F2}"))));
				_session.Clear();
			}
		}

		private static void Forget()
		{
			Flush();
			_held = IntPtr.Zero;
			_lastCs = 0f;
		}

		public static void Consumed(Interactable item)
		{
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			try
			{
				InteractablePreset preset = item.preset;
				Player instance = Player.Instance;
				FirstPersonItemController instance2 = FirstPersonItemController.Instance;
				if ((SoCustomComparison)(object)preset == (SoCustomComparison)null || (Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null)
				{
					return;
				}
				Mixing.OnConsumed(instance, item, preset, Classify(preset));
				if (instance2.takeOneActive)
				{
					if (((Il2CppObjectBase)item).Pointer != _held)
					{
						Flush();
						_held = ((Il2CppObjectBase)item).Pointer;
						_heldName = ((SoCustomComparison)preset).presetName ?? "";
					}
					Credit(preset, 1f, take: true);
					Flush();
					_lastCs = item.cs;
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(32, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] could not record the dose: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				log.LogError(val);
			}
		}

		private static void TrackSmoking()
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			FirstPersonItemController instance = FirstPersonItemController.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				_lastSmoking = 0;
				return;
			}
			int smokingActive = instance.smokingActive;
			if (smokingActive > 0 && _lastSmoking <= 0)
			{
				Add(Substance.Nicotine, 1f, logged: false);
				if (Plugin.Cfg.DebugLogging.Value)
				{
					ManualLogSource log = Plugin.Log;
					bool flag = default(bool);
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(37, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[me] intake (cigarette): Nicotine -> ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(Level(Substance.Nicotine), "F2");
					}
					log.LogInfo(val);
				}
			}
			_lastSmoking = smokingActive;
		}

		public static Saved Save()
		{
			return new Saved
			{
				Levels = _levels.Where((KeyValuePair<Substance, float> p) => p.Value > 0f).ToDictionary((KeyValuePair<Substance, float> p) => p.Key.ToString(), (KeyValuePair<Substance, float> p) => p.Value),
				CaffeineSpent = _spent
			};
		}

		public static void Load(Saved? saved, Dictionary<string, List<SavedDose>>? legacy)
		{
			_levels.Clear();
			_session.Clear();
			_exposure.Clear();
			_spent = (_cleared = 0f);
			_lastGameTime = float.NaN;
			_lastSmoking = 0;
			_held = IntPtr.Zero;
			_lastCs = 0f;
			if (saved?.Levels != null)
			{
				foreach (KeyValuePair<string, float> level in saved.Levels)
				{
					if (Enum.TryParse<Substance>(level.Key, out var result) && result != Substance.Alcohol && level.Value > 0f)
					{
						_levels[result] = level.Value;
					}
				}
				_spent = Ma