Decompiled source of Wendigos Voice Cloning v0.1.9

Wendigos.dll

Decompiled 2 weeks ago
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Steamworks;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using Wendigos.NetcodePatcher;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Wendigos")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+60f854d571db55bcca08e61d24858884612589f2")]
[assembly: AssemblyProduct("Wendigos")]
[assembly: AssemblyTitle("Wendigos")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
		NetworkVariableSerializationTypes.InitializeSerializer_FixedString<FixedString128Bytes>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<FixedString128Bytes>();
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public static class SavWav
{
	private const uint HeaderSize = 44u;

	private const float RescaleFactor = 32767f;

	public static void Save(string filename, AudioClip clip, bool trim = false)
	{
		if (!filename.ToLower().EndsWith(".wav"))
		{
			filename += ".wav";
		}
		string path = Path.Combine(Application.persistentDataPath, filename);
		Directory.CreateDirectory(Path.GetDirectoryName(path));
		using FileStream output = new FileStream(path, FileMode.Create);
		using BinaryWriter binaryWriter = new BinaryWriter(output);
		uint length;
		byte[] wav = GetWav(clip, out length, trim);
		binaryWriter.Write(wav, 0, (int)length);
	}

	public static byte[] GetWav(AudioClip clip, out uint length, bool trim = false)
	{
		uint samplesAfterTrimming;
		byte[] array = ConvertAndWrite(clip, out length, out samplesAfterTrimming, trim);
		WriteHeader(array, clip, length, samplesAfterTrimming);
		return array;
	}

	private static byte[] ConvertAndWrite(AudioClip clip, out uint length, out uint samplesAfterTrimming, bool trim)
	{
		float[] array = new float[clip.samples * clip.channels];
		clip.GetData(array, 0);
		int num = array.Length;
		int num2 = 0;
		int num3 = num - 1;
		if (trim)
		{
			for (int i = 0; i < num; i++)
			{
				if ((short)(array[i] * 32767f) != 0)
				{
					num2 = i;
					break;
				}
			}
			for (int num4 = num - 1; num4 >= 0; num4--)
			{
				if ((short)(array[num4] * 32767f) != 0)
				{
					num3 = num4;
					break;
				}
			}
		}
		byte[] array2 = new byte[(long)(num * 2) + 44L];
		uint num5 = 44u;
		for (int j = num2; j <= num3; j++)
		{
			short num6 = (short)(array[j] * 32767f);
			array2[num5++] = (byte)num6;
			array2[num5++] = (byte)(num6 >> 8);
		}
		length = num5;
		samplesAfterTrimming = (uint)(num3 - num2 + 1);
		return array2;
	}

	private static void AddDataToBuffer(byte[] buffer, ref uint offset, byte[] addBytes)
	{
		foreach (byte b in addBytes)
		{
			buffer[offset++] = b;
		}
	}

	private static void WriteHeader(byte[] stream, AudioClip clip, uint length, uint samples)
	{
		uint frequency = (uint)clip.frequency;
		ushort num = (ushort)clip.channels;
		uint offset = 0u;
		byte[] bytes = Encoding.UTF8.GetBytes("RIFF");
		AddDataToBuffer(stream, ref offset, bytes);
		byte[] bytes2 = BitConverter.GetBytes(length - 8);
		AddDataToBuffer(stream, ref offset, bytes2);
		byte[] bytes3 = Encoding.UTF8.GetBytes("WAVE");
		AddDataToBuffer(stream, ref offset, bytes3);
		byte[] bytes4 = Encoding.UTF8.GetBytes("fmt ");
		AddDataToBuffer(stream, ref offset, bytes4);
		byte[] bytes5 = BitConverter.GetBytes(16u);
		AddDataToBuffer(stream, ref offset, bytes5);
		byte[] bytes6 = BitConverter.GetBytes((ushort)1);
		AddDataToBuffer(stream, ref offset, bytes6);
		byte[] bytes7 = BitConverter.GetBytes(num);
		AddDataToBuffer(stream, ref offset, bytes7);
		byte[] bytes8 = BitConverter.GetBytes(frequency);
		AddDataToBuffer(stream, ref offset, bytes8);
		byte[] bytes9 = BitConverter.GetBytes(frequency * num * 2);
		AddDataToBuffer(stream, ref offset, bytes9);
		ushort value = (ushort)(num * 2);
		AddDataToBuffer(stream, ref offset, BitConverter.GetBytes(value));
		ushort value2 = 16;
		byte[] bytes10 = BitConverter.GetBytes(value2);
		AddDataToBuffer(stream, ref offset, bytes10);
		byte[] bytes11 = Encoding.UTF8.GetBytes("data");
		AddDataToBuffer(stream, ref offset, bytes11);
		byte[] bytes12 = BitConverter.GetBytes(samples * 2);
		AddDataToBuffer(stream, ref offset, bytes12);
	}
}
namespace Wendigos
{
	internal class ElevenLabs
	{
		private const string baseDir = ".\\";

		private const string baseURL = "https://api.elevenlabs.io/v1/text-to-speech/";

		public bool requesting = false;

		public string API_KEY { get; }

		public ElevenLabs(string key)
		{
			API_KEY = key;
		}

		public async Task<string> RequestAudio(string prompt, string voice, string fileName, string dir, int fileNum)
		{
			string url = "https://api.elevenlabs.io/v1/text-to-speech/" + voice;
			HttpClient client = new HttpClient();
			client.DefaultRequestHeaders.Add("xi-api-key", API_KEY);
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/mpeg"));
			var data = new
			{
				text = prompt,
				model_id = "eleven_multilingual_v2",
				voice_settings = new
				{
					stability = 0.5f,
					similarity_boost = 0.5f,
					style = 0.3f,
					use_speaker_boost = true
				}
			};
			string json = JsonConvert.SerializeObject((object)data);
			StringContent httpContent = new StringContent(json, Encoding.Default, "application/json");
			HttpResponseMessage response = await client.PostAsync(url, httpContent);
			requesting = false;
			if (response != null)
			{
				int fileNameExtension = fileNum;
				int retries = 0;
				bool fileNameValid = false;
				while (!fileNameValid)
				{
					try
					{
						using (Stream stream = await response.Content.ReadAsStreamAsync())
						{
							using FileStream fileStream = File.Create(dir + fileName + fileNameExtension + ".mp3");
							await stream.CopyToAsync(fileStream);
						}
						fileNameValid = true;
					}
					catch (Exception)
					{
						retries++;
						if (retries >= 50)
						{
							break;
						}
						fileNameExtension++;
					}
				}
				if (fileNameValid)
				{
					return dir + fileName + fileNameExtension + ".mp3";
				}
			}
			return null;
		}
	}
	[BepInPlugin("Wendigos", "Wendigos", "1.1.8")]
	public class Plugin : BaseUnityPlugin
	{
		public class WendigosMessageHandler : NetworkBehaviour
		{
			public static string MessageName = "clipSender";

			private static Dictionary<ulong, List<byte[]>> clipFragmentBuffers = new Dictionary<ulong, List<byte[]>>();

			private static int numberOfFragments = 1;

			public static bool isEveryoneReady = false;

			public static List<ulong> ConnectedClientIDs;

			public NetworkList<FixedString128Bytes> clipNamesArr;

			public static WendigosMessageHandler Instance { get; private set; }

			public override void OnNetworkSpawn()
			{
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Expected O, but got Unknown
				//IL_008d: Unknown result type (might be due to invalid IL or missing references)
				((NetworkBehaviour)this).OnNetworkSpawn();
				((NetworkBehaviour)this).NetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(MessageName, new HandleNamedMessageDelegate(ReceiveMessage));
				ConnectedClientIDs = new List<ulong> { 0uL };
				if (((NetworkBehaviour)this).IsServer)
				{
					((NetworkBehaviour)this).NetworkManager.OnClientConnectedCallback += OnClientConnectedCallback;
					foreach (AudioClip myClip in myClips)
					{
						clipNamesArr.Add(FixedString128Bytes.op_Implicit("0" + ((Object)myClip).name));
					}
				}
				if (!audioClips.Keys.Contains(NetworkManager.Singleton.LocalClientId))
				{
					audioClips.Add(NetworkManager.Singleton.LocalClientId, new List<AudioClip>());
				}
				foreach (AudioClip myClip2 in myClips)
				{
					audioClips[NetworkManager.Singleton.LocalClientId].Add(myClip2);
				}
			}

			internal static void ClientConnectInitializer(Scene sceneName, LoadSceneMode sceneEnum)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Expected O, but got Unknown
				Scene val = sceneName;
				if (((Scene)(ref val)).name == "SampleSceneRelay")
				{
					GameObject val2 = new GameObject("WendigosMessageHandler");
					val2.AddComponent<WendigosMessageHandler>();
					val2.AddComponent<NetworkObject>();
					PropertyInfo property = typeof(NetworkObject).GetProperty("NetworkObjectId", BindingFlags.Instance | BindingFlags.Public);
					WriteToConsole((property == null).ToString() ?? "");
					property.SetValue(val2.GetComponent<NetworkObject>(), 127uL);
					WriteToConsole("NETWORK MANAGER ID IS " + val2.GetComponent<NetworkObject>().NetworkObjectId);
					FieldInfo field = typeof(NetworkObject).GetField("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					WriteToConsole((field == null).ToString() ?? "");
					field.SetValue(val2.GetComponent<NetworkObject>(), 127u);
				}
			}

			private void Awake()
			{
				Instance = this;
				clipNamesArr = new NetworkList<FixedString128Bytes>();
			}

			private void OnClientConnectedCallback(ulong obj)
			{
				if (((NetworkBehaviour)this).IsServer)
				{
					WriteToConsole("Server sending " + get_clips_count() + " clips");
					{
						foreach (ulong connectedClientsId in NetworkManager.Singleton.ConnectedClientsIds)
						{
							if (connectedClientsId != obj)
							{
								try
								{
									List<AudioClip> clips = new List<AudioClip>(audioClips[connectedClientsId]);
									Task task = SendClipListAsync(clips, obj, specificClient: true, shouldSync: false, connectedClientsId);
								}
								catch
								{
								}
							}
						}
						return;
					}
				}
				List<AudioClip> clips2 = new List<AudioClip>(audioClips[NetworkManager.Singleton.LocalClientId]);
				Task task2 = SendClipListAsync(clips2, obj, specificClient: false, shouldSync: true, NetworkManager.Singleton.LocalClientId);
			}

			public override void OnNetworkDespawn()
			{
				foreach (List<AudioClip> value in audioClips.Values)
				{
					value.Clear();
				}
				sent_localID = false;
				ConnectedClientIDs.Clear();
				if (((NetworkBehaviour)this).IsServer)
				{
					sharedMaskedClientDict.Clear();
					serverReadyDict.Clear();
				}
			}

			private void ReceiveMessage(ulong senderId, FastBufferReader messagePayload)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				byte[] item = default(byte[]);
				((FastBufferReader)(ref messagePayload)).ReadValueSafe<byte>(ref item, default(ForPrimitives));
				if (!clipFragmentBuffers.ContainsKey(senderId))
				{
					clipFragmentBuffers.Add(senderId, new List<byte[]>());
				}
				clipFragmentBuffers[senderId].Add(item);
				if (clipFragmentBuffers[senderId].Count == numberOfFragments)
				{
					Task.Factory.StartNew(() => CombineAudioFragments(senderId));
				}
			}

			private async Task CombineAudioFragments(ulong senderId)
			{
				int sizeOfFullMessage = 0;
				foreach (byte[] fragment in clipFragmentBuffers[senderId])
				{
					sizeOfFullMessage += fragment.Length;
				}
				byte[] receivedMessageContent = new byte[sizeOfFullMessage];
				int totalOffset = 0;
				foreach (byte[] fragment2 in clipFragmentBuffers[senderId])
				{
					Buffer.BlockCopy(fragment2, 0, receivedMessageContent, totalOffset, fragment2.Length);
					totalOffset += fragment2.Length;
				}
				clipFragmentBuffers[senderId].Clear();
				receivedMessageContent = Decompress(receivedMessageContent);
				ulong realSenderId = 0uL;
				byte firstChar = receivedMessageContent[7];
				byte num = receivedMessageContent[6];
				string clipN = Convert.ToChar(firstChar).ToString() + num;
				WriteToConsole("ClipN is " + clipN);
				for (int i = 0; i < 6; i++)
				{
					realSenderId |= (ulong)receivedMessageContent[i] << i * 8;
				}
				MonoBehaviour.print((object)("Sender ID is: " + senderId));
				MonoBehaviour.print((object)("Real sender ID is: " + realSenderId));
				byte[] receivedMessageContentNoHeader = new byte[receivedMessageContent.Length - 8];
				Buffer.BlockCopy(receivedMessageContent, 8, receivedMessageContentNoHeader, 0, receivedMessageContentNoHeader.Length);
				AudioClip recievedClip = LoadAudioClip(receivedMessageContentNoHeader, elevenlabs_enabled.Value ? 44100 : 24000);
				((Object)recievedClip).name = clipN;
				bool doWeHaveTheClip = false;
				if (!audioClips.Keys.Contains(realSenderId))
				{
					audioClips.Add(realSenderId, new List<AudioClip>());
				}
				if (((NetworkBehaviour)this).IsServer)
				{
					WriteToConsole($"Sever received ({receivedMessageContentNoHeader}) from client ({realSenderId})");
					foreach (AudioClip clip2 in audioClips[realSenderId])
					{
						if (((Object)clip2).name == ((Object)recievedClip).name || senderId == 0)
						{
							WriteToConsole(((Object)clip2).name);
							WriteToConsole("We already have this clip!");
							doWeHaveTheClip = true;
							WriteToConsole("AudioClip count is now: " + get_clips_count());
						}
					}
					if (!doWeHaveTheClip)
					{
						audioClips[realSenderId].Add(recievedClip);
						clipNamesArr.Add(FixedString128Bytes.op_Implicit(realSenderId + ((Object)recievedClip).name));
						WriteToConsole("Added Clip.");
						WriteToConsole("AudioClip count is now: " + get_clips_count());
					}
					return;
				}
				WriteToConsole($"Client received ({receivedMessageContentNoHeader}) from the server.");
				foreach (AudioClip clip in audioClips[realSenderId])
				{
					if (((Object)clip).name == ((Object)recievedClip).name || realSenderId == NetworkManager.Singleton.LocalClientId)
					{
						WriteToConsole("We already have this clip!");
						doWeHaveTheClip = true;
						WriteToConsole("AudioClip count is now: " + get_clips_count());
					}
				}
				if (!doWeHaveTheClip)
				{
					audioClips[realSenderId].Add(recievedClip);
					WriteToConsole("Added Clip.");
					WriteToConsole("AudioClip count is now: " + get_clips_count());
				}
			}

			private void SendMessage(byte[] audioClipFragment, ulong destClient = 0uL, bool specificClient = false)
			{
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_007d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0069: Unknown result type (might be due to invalid IL or missing references)
				specificClient = false;
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(audioClipFragment.Length, (Allocator)2, 512000);
				CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager;
				FastBufferWriter val2 = val;
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<byte>(audioClipFragment, default(ForPrimitives));
					if (specificClient)
					{
						customMessagingManager.SendNamedMessage(MessageName, destClient, val, (NetworkDelivery)4);
					}
					else if (NetworkManager.Singleton.IsServer)
					{
						customMessagingManager.SendNamedMessageToAll(MessageName, val, (NetworkDelivery)4);
					}
					else
					{
						customMessagingManager.SendNamedMessage(MessageName, 0uL, val, (NetworkDelivery)4);
					}
				}
				finally
				{
					((IDisposable)(FastBufferWriter)(ref val2)).Dispose();
				}
			}

			public void SendFragmentedMessage(AudioClip audioClip, ulong destClient = 0uL, bool specificClient = false, ulong originClient = 0uL)
			{
				MonoBehaviour.print((object)"Compressing...");
				byte[] array = Compress(ConvertToByteArr(audioClip), originClient, ((Object)audioClip).name);
				WriteToConsole($"Sending message of length {array.Length}");
				if ((double)array.Length > Math.Ceiling(512000f * (float)numberOfFragments))
				{
					throw new Exception("clip is too large to send! Try increasing the number of message fragments.");
				}
				int num = (int)Math.Ceiling((float)array.Length / (float)numberOfFragments);
				List<byte[]> list = new List<byte[]>();
				for (int i = 0; i < numberOfFragments; i++)
				{
					if (i != numberOfFragments - 1)
					{
						list.Add(new byte[num]);
						Buffer.BlockCopy(array, num * i, list[i], 0, num);
					}
					else
					{
						list.Add(new byte[array.Length - (numberOfFragments - 1) * num]);
						Buffer.BlockCopy(array, num * i, list[i], 0, array.Length - (numberOfFragments - 1) * num);
					}
				}
				foreach (byte[] item in list)
				{
					SendMessage(item, destClient, specificClient);
				}
			}

			public async Task SendClipListAsync(List<AudioClip> clips, ulong destClient = 0uL, bool specificClient = false, bool shouldSync = false, ulong originClient = 0uL)
			{
				foreach (AudioClip clip in clips)
				{
					WriteToConsole("Sending " + originClient + "'s clips");
					SendFragmentedMessage(clip, destClient, specificClient, originClient);
					await Task.Delay(200);
				}
				if (((NetworkBehaviour)this).IsServer && specificClient)
				{
					ClientRpcParams clientRpcParams = new ClientRpcParams
					{
						Send = new ClientRpcSendParams
						{
							TargetClientIds = new ulong[1] { destClient }
						}
					};
					SendServerMyClipsClientRpc(clientRpcParams);
				}
				else if (!((NetworkBehaviour)this).IsServer && shouldSync)
				{
					WriteToConsole("Sent " + get_clips_count() + " Clips");
					BroadcastAllNewClipsServerRpc(originClient);
				}
			}

			[ServerRpc(RequireOwnership = false)]
			public void UpdateClientListServerRpc(ulong newClient)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
					{
						ServerRpcParams val = default(ServerRpcParams);
						FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1162019120u, val, (RpcDelivery)0);
						BytePacker.WriteValueBitPacked(val2, newClient);
						((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1162019120u, val, (RpcDelivery)0);
					}
					if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
					{
						UpdateClientListClientRpc(newClient);
					}
				}
			}

			[ClientRpc]
			public void UpdateClientListClientRpc(ulong newClient)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2868607049u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, newClient);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2868607049u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					if (!ConnectedClientIDs.Contains(newClient))
					{
						ConnectedClientIDs.Add(newClient);
					}
					WriteToConsole("New ClientID list is: [" + string.Join(",", ConnectedClientIDs.Select((ulong x) => x.ToString()).ToArray()) + "]");
				}
			}

			[ServerRpc(RequireOwnership = false)]
			public void BroadcastAllNewClipsServerRpc(ulong senderID)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0089: Unknown result type (might be due to invalid IL or missing references)
				//IL_018f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0199: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
				//IL_0109: Unknown result type (might be due to invalid IL or missing references)
				//IL_0120: Unknown result type (might be due to invalid IL or missing references)
				//IL_0121: Unknown result type (might be due to invalid IL or missing references)
				//IL_0126: Unknown result type (might be due to invalid IL or missing references)
				//IL_0127: Unknown result type (might be due to invalid IL or missing references)
				//IL_0129: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1706438528u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, senderID);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1706438528u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					if (!audioClips.Keys.Contains(senderID))
					{
						WriteToConsole("Client " + senderID + " has not synced yet. Requesting sync...");
						ClientRpcParams val3 = default(ClientRpcParams);
						val3.Send = new ClientRpcSendParams
						{
							TargetClientIds = new ulong[1] { senderID }
						};
						ClientRpcParams p = val3;
						SendServerMyClipsClientRpc(p);
					}
					else
					{
						WriteToConsole("Broadcasting " + senderID + "'s clips - " + audioClips[senderID].Count);
						List<AudioClip> clips = new List<AudioClip>(audioClips[senderID]);
						Task task = SendClipListAsync(clips, 0uL, specificClient: false, shouldSync: false, senderID);
						ClientRpcParams val3 = default(ClientRpcParams);
						val3.Send = new ClientRpcSendParams
						{
							TargetClientIds = new ulong[1] { senderID }
						};
						ClientRpcParams param = val3;
						ValidateClipsClientRpc(param);
					}
				}
			}

			[ClientRpc]
			public void SendServerMyClipsClientRpc(ClientRpcParams p = default(ClientRpcParams))
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0096: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
					{
						FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(3594351807u, p, (RpcDelivery)0);
						((NetworkBehaviour)this).__endSendClientRpc(ref val, 3594351807u, p, (RpcDelivery)0);
					}
					if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
					{
						Task task = SendClipListAsync(myClips, 0uL, specificClient: false, shouldSync: true, NetworkManager.Singleton.LocalClientId);
					}
				}
			}

			[ClientRpc]
			public void SetMaskedSuitClientRpc(string maskedId, int suitid)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e1: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00af: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4236159180u, val, (RpcDelivery)0);
					bool flag = maskedId != null;
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
					if (flag)
					{
						((FastBufferWriter)(ref val2)).WriteValueSafe(maskedId, false);
					}
					BytePacker.WriteValueBitPacked(val2, suitid);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4236159180u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
				{
					return;
				}
				try
				{
					maskedInstanceLookup[maskedId].SetSuit(suitid);
				}
				catch (Exception ex)
				{
					WriteToConsole(ex.Message);
				}
			}

			public async Task waitForMSeconds(int Mseconds)
			{
				await Task.Delay(Mseconds);
			}

			public async Task askServerResendList(List<(ulong COrID, FixedString128Bytes cname)> clipTuples)
			{
				foreach (var tup in clipTuples)
				{
					AskServerResendClipServerRpc(tup.COrID, tup.cname, NetworkManager.Singleton.LocalClientId);
					await Task.Delay(200);
				}
			}

			[ClientRpc]
			public void ValidateClipsClientRpc(ClientRpcParams param = default(ClientRpcParams))
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0096: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0120: Unknown result type (might be due to invalid IL or missing references)
				//IL_0144: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
				//IL_0286: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(3353027481u, param, (RpcDelivery)0);
					((NetworkBehaviour)this).__endSendClientRpc(ref val, 3353027481u, param, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
				{
					return;
				}
				try
				{
					List<FixedString128Bytes> list = new List<FixedString128Bytes>();
					List<AudioClip> list2 = new List<AudioClip>();
					foreach (ulong key in audioClips.Keys)
					{
						bool flag = false;
						foreach (AudioClip item in audioClips[key])
						{
							list.Add(FixedString128Bytes.op_Implicit(key + ((Object)item).name));
							if (!clipNamesArr.Contains(FixedString128Bytes.op_Implicit(key + ((Object)item).name)))
							{
								WriteToConsole("Client resending " + key + ((Object)item).name);
								list2.Add(item);
								flag = true;
							}
						}
						if (flag)
						{
							SendClipListAsync(list2, 0uL, specificClient: false, shouldSync: true, key);
						}
					}
					List<(ulong, FixedString128Bytes)> list3 = new List<(ulong, FixedString128Bytes)>();
					foreach (FixedString128Bytes item2 in clipNamesArr)
					{
						FixedString128Bytes current3 = item2;
						if (list.Contains(current3))
						{
							continue;
						}
						ulong num = 0uL;
						string text = ((object)(FixedString128Bytes)(ref current3)).ToString();
						foreach (char c in text)
						{
							if (c >= 'a' && c <= 'z')
							{
								break;
							}
							num *= 10;
							num += (ulong)(c - 48);
						}
						list3.Add((num, FixedString128Bytes.op_Implicit(((object)(FixedString128Bytes)(ref current3)).ToString().Substring(1))));
					}
					askServerResendList(list3);
				}
				catch
				{
					WriteToConsole("SYNC ERROR");
				}
			}

			[ServerRpc(RequireOwnership = false)]
			public void AskServerResendClipServerRpc(ulong originClipId, FixedString128Bytes name, ulong senderID)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cb: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_008a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0090: Unknown result type (might be due to invalid IL or missing references)
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
				//IL_0125: Unknown result type (might be due to invalid IL or missing references)
				//IL_012a: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2735770731u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, originClipId);
					((FastBufferWriter)(ref val2)).WriteValueSafe<FixedString128Bytes>(ref name, default(ForFixedStrings));
					BytePacker.WriteValueBitPacked(val2, senderID);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2735770731u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
				{
					return;
				}
				WriteToConsole("Resending...");
				List<AudioClip> list = new List<AudioClip>();
				foreach (AudioClip item in audioClips[originClipId])
				{
					FixedString128Bytes val3 = FixedString128Bytes.op_Implicit(((Object)item).name);
					if ((ref val3) == (ref name))
					{
						WriteToConsole("Server Resending " + originClipId + ((Object)item).name);
						list.Add(item);
					}
				}
				if (list.Count > 0)
				{
					SendClipListAsync(list, senderID, specificClient: false, shouldSync: false, originClipId);
				}
			}

			[ServerRpc(RequireOwnership = false)]
			public void TellServerReadyToSendServerRpc(string maskedID, bool ready, ServerRpcParams serverRpcParams = default(ServerRpcParams))
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ef: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0120: Unknown result type (might be due to invalid IL or missing references)
				//IL_0121: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(2447039368u, serverRpcParams, (RpcDelivery)0);
					bool flag = maskedID != null;
					((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
					if (flag)
					{
						((FastBufferWriter)(ref val)).WriteValueSafe(maskedID, false);
					}
					((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref ready, default(ForPrimitives));
					((NetworkBehaviour)this).__endSendServerRpc(ref val, 2447039368u, serverRpcParams, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
				{
					return;
				}
				WriteToConsole("Server got ready signal");
				ulong senderClientId = serverRpcParams.Receive.SenderClientId;
				WriteToConsole("Recieved " + ready + " from " + senderClientId);
				try
				{
					if (!serverReadyDict[maskedID].ContainsKey(senderClientId))
					{
						serverReadyDict[maskedID].Add(senderClientId, ready);
					}
					else
					{
						serverReadyDict[maskedID][senderClientId] = ready;
					}
				}
				catch (Exception ex)
				{
					WriteToConsole("ERROR HERE");
					WriteToConsole(ex.Message);
					foreach (string key in serverReadyDict.Keys)
					{
						WriteToConsole(key ?? "");
					}
				}
			}

			[ServerRpc(RequireOwnership = false)]
			public void AddToMaskedClientDictServerRpc(string maskedID, ulong clientID)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e1: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00af: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1290365431u, val, (RpcDelivery)0);
					bool flag = maskedID != null;
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
					if (flag)
					{
						((FastBufferWriter)(ref val2)).WriteValueSafe(maskedID, false);
					}
					BytePacker.WriteValueBitPacked(val2, clientID);
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1290365431u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost))
				{
					AddToMaskedClientDictClientRpc(maskedID, clientID);
				}
			}

			[ClientRpc]
			public void AddToMaskedClientDictClientRpc(string maskedID, ulong clientID)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e1: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_008e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00af: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3329064614u, val, (RpcDelivery)0);
					bool flag = maskedID != null;
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
					if (flag)
					{
						((FastBufferWriter)(ref val2)).WriteValueSafe(maskedID, false);
					}
					BytePacker.WriteValueBitPacked(val2, clientID);
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3329064614u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					sharedMaskedClientDict[maskedID] = clientID;
					WriteToConsole("added masked " + maskedID + " to masked_client_dict");
				}
			}

			[ClientRpc]
			public void SortAudioClipsClientRpc()
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0096: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
					{
						ClientRpcParams val = default(ClientRpcParams);
						FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(110445393u, val, (RpcDelivery)0);
						((NetworkBehaviour)this).__endSendClientRpc(ref val2, 110445393u, val, (RpcDelivery)0);
					}
					if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
					{
						sort_audioclips();
					}
				}
			}

			[ServerRpc(RequireOwnership = false)]
			public void TryPlayAudioServerRpc(ulong MimickingID, string maskedID)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e1: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0095: Unknown result type (might be due to invalid IL or missing references)
				//IL_009b: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost))
				{
					ServerRpcParams val = default(ServerRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(554559618u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, MimickingID);
					bool flag = maskedID != null;
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
					if (flag)
					{
						((FastBufferWriter)(ref val2)).WriteValueSafe(maskedID, false);
					}
					((NetworkBehaviour)this).__endSendServerRpc(ref val2, 554559618u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost))
				{
					return;
				}
				bool flag2 = true;
				foreach (bool value in serverReadyDict[maskedID].Values)
				{
					flag2 = value && flag2;
				}
				if (flag2 && serverRand.Next() % 10 == 0)
				{
					WriteToConsole("Trying to play audio");
					int indexToPlay = serverRand.Next() % audioClips[MimickingID].Count;
					PlayAudioClientRpc(MimickingID, indexToPlay, maskedID);
				}
			}

			[ClientRpc]
			public void PlayAudioClientRpc(ulong MimickingID, int indexToPlay, string maskedID)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Invalid comparison between Unknown and I4
				//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ee: Invalid comparison between Unknown and I4
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
				if (networkManager == null || !networkManager.IsListening)
				{
					return;
				}
				if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
				{
					ClientRpcParams val = default(ClientRpcParams);
					FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1350037529u, val, (RpcDelivery)0);
					BytePacker.WriteValueBitPacked(val2, MimickingID);
					BytePacker.WriteValueBitPacked(val2, indexToPlay);
					bool flag = maskedID != null;
					((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
					if (flag)
					{
						((FastBufferWriter)(ref val2)).WriteValueSafe(maskedID, false);
					}
					((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1350037529u, val, (RpcDelivery)0);
				}
				if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
				{
					WriteToConsole($"Masked {maskedID} playing {MimickingID}[{indexToPlay}] - {((Object)audioClips[MimickingID][indexToPlay]).name}");
					TryToPlayAudio(audioClips[MimickingID][indexToPlay], maskedID);
				}
			}

			protected override void __initializeVariables()
			{
				if (clipNamesArr == null)
				{
					throw new Exception("WendigosMessageHandler.clipNamesArr cannot be null. All NetworkVariableBase instances must be initialized.");
				}
				((NetworkVariableBase)clipNamesArr).Initialize((NetworkBehaviour)(object)this);
				((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)clipNamesArr, "clipNamesArr");
				base.NetworkVariableFields.Add((NetworkVariableBase)(object)clipNamesArr);
				((NetworkBehaviour)this).__initializeVariables();
			}

			[RuntimeInitializeOnLoadMethod]
			internal static void InitializeRPCS_WendigosMessageHandler()
			{
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Expected O, but got Unknown
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Expected O, but got Unknown
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_0051: Expected O, but got Unknown
				//IL_0062: Unknown result type (might be due to invalid IL or missing references)
				//IL_006c: Expected O, but got Unknown
				//IL_007d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0087: Expected O, but got Unknown
				//IL_0098: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a2: Expected O, but got Unknown
				//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: Expected O, but got Unknown
				//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d8: Expected O, but got Unknown
				//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f3: Expected O, but got Unknown
				//IL_0104: Unknown result type (might be due to invalid IL or missing references)
				//IL_010e: Expected O, but got Unknown
				//IL_011f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0129: Expected O, but got Unknown
				//IL_013a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0144: Expected O, but got Unknown
				//IL_0155: Unknown result type (might be due to invalid IL or missing references)
				//IL_015f: Expected O, but got Unknown
				NetworkManager.__rpc_func_table.Add(1162019120u, new RpcReceiveHandler(__rpc_handler_1162019120));
				NetworkManager.__rpc_func_table.Add(2868607049u, new RpcReceiveHandler(__rpc_handler_2868607049));
				NetworkManager.__rpc_func_table.Add(1706438528u, new RpcReceiveHandler(__rpc_handler_1706438528));
				NetworkManager.__rpc_func_table.Add(3594351807u, new RpcReceiveHandler(__rpc_handler_3594351807));
				NetworkManager.__rpc_func_table.Add(4236159180u, new RpcReceiveHandler(__rpc_handler_4236159180));
				NetworkManager.__rpc_func_table.Add(3353027481u, new RpcReceiveHandler(__rpc_handler_3353027481));
				NetworkManager.__rpc_func_table.Add(2735770731u, new RpcReceiveHandler(__rpc_handler_2735770731));
				NetworkManager.__rpc_func_table.Add(2447039368u, new RpcReceiveHandler(__rpc_handler_2447039368));
				NetworkManager.__rpc_func_table.Add(1290365431u, new RpcReceiveHandler(__rpc_handler_1290365431));
				NetworkManager.__rpc_func_table.Add(3329064614u, new RpcReceiveHandler(__rpc_handler_3329064614));
				NetworkManager.__rpc_func_table.Add(110445393u, new RpcReceiveHandler(__rpc_handler_110445393));
				NetworkManager.__rpc_func_table.Add(554559618u, new RpcReceiveHandler(__rpc_handler_554559618));
				NetworkManager.__rpc_func_table.Add(1350037529u, new RpcReceiveHandler(__rpc_handler_1350037529));
			}

			private static void __rpc_handler_1162019120(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					ulong newClient = default(ulong);
					ByteUnpacker.ReadValueBitPacked(reader, ref newClient);
					target.__rpc_exec_stage = (__RpcExecStage)1;
					((WendigosMessageHandler)(object)target).UpdateClientListServerRpc(newClient);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_2868607049(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					ulong newClient = default(ulong);
					ByteUnpacker.ReadValueBitPacked(reader, ref newClient);
					target.__rpc_exec_stage = (__RpcExecStage)2;
					((WendigosMessageHandler)(object)target).UpdateClientListClientRpc(newClient);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_1706438528(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_0050: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					ulong senderID = default(ulong);
					ByteUnpacker.ReadValueBitPacked(reader, ref senderID);
					target.__rpc_exec_stage = (__RpcExecStage)1;
					((WendigosMessageHandler)(object)target).BroadcastAllNewClipsServerRpc(senderID);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_3594351807(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: 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)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					ClientRpcParams client = rpcParams.Client;
					target.__rpc_exec_stage = (__RpcExecStage)2;
					((WendigosMessageHandler)(object)target).SendServerMyClipsClientRpc(client);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_4236159180(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_006e: Unknown result type (might be due to invalid IL or missing references)
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					bool flag = default(bool);
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
					string maskedId = null;
					if (flag)
					{
						((FastBufferReader)(ref reader)).ReadValueSafe(ref maskedId, false);
					}
					int suitid = default(int);
					ByteUnpacker.ReadValueBitPacked(reader, ref suitid);
					target.__rpc_exec_stage = (__RpcExecStage)2;
					((WendigosMessageHandler)(object)target).SetMaskedSuitClientRpc(maskedId, suitid);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_3353027481(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: 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)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					ClientRpcParams client = rpcParams.Client;
					target.__rpc_exec_stage = (__RpcExecStage)2;
					((WendigosMessageHandler)(object)target).ValidateClipsClientRpc(client);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_2735770731(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0042: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					ulong originClipId = default(ulong);
					ByteUnpacker.ReadValueBitPacked(reader, ref originClipId);
					FixedString128Bytes name = default(FixedString128Bytes);
					((FastBufferReader)(ref reader)).ReadValueSafe<FixedString128Bytes>(ref name, default(ForFixedStrings));
					ulong senderID = default(ulong);
					ByteUnpacker.ReadValueBitPacked(reader, ref senderID);
					target.__rpc_exec_stage = (__RpcExecStage)1;
					((WendigosMessageHandler)(object)target).AskServerResendClipServerRpc(originClipId, name, senderID);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_2447039368(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				//IL_006d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0076: Unknown result type (might be due to invalid IL or missing references)
				//IL_0077: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0086: Unknown result type (might be due to invalid IL or missing references)
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					bool flag = default(bool);
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
					string maskedID = null;
					if (flag)
					{
						((FastBufferReader)(ref reader)).ReadValueSafe(ref maskedID, false);
					}
					bool ready = default(bool);
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref ready, default(ForPrimitives));
					ServerRpcParams server = rpcParams.Server;
					target.__rpc_exec_stage = (__RpcExecStage)1;
					((WendigosMessageHandler)(object)target).TellServerReadyToSendServerRpc(maskedID, ready, server);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_1290365431(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_006e: Unknown result type (might be due to invalid IL or missing references)
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					bool flag = default(bool);
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
					string maskedID = null;
					if (flag)
					{
						((FastBufferReader)(ref reader)).ReadValueSafe(ref maskedID, false);
					}
					ulong clientID = default(ulong);
					ByteUnpacker.ReadValueBitPacked(reader, ref clientID);
					target.__rpc_exec_stage = (__RpcExecStage)1;
					((WendigosMessageHandler)(object)target).AddToMaskedClientDictServerRpc(maskedID, clientID);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_3329064614(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_006e: Unknown result type (might be due to invalid IL or missing references)
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					bool flag = default(bool);
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
					string maskedID = null;
					if (flag)
					{
						((FastBufferReader)(ref reader)).ReadValueSafe(ref maskedID, false);
					}
					ulong clientID = default(ulong);
					ByteUnpacker.ReadValueBitPacked(reader, ref clientID);
					target.__rpc_exec_stage = (__RpcExecStage)2;
					((WendigosMessageHandler)(object)target).AddToMaskedClientDictClientRpc(maskedID, clientID);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_110445393(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					target.__rpc_exec_stage = (__RpcExecStage)2;
					((WendigosMessageHandler)(object)target).SortAudioClipsClientRpc();
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_554559618(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0042: Unknown result type (might be due to invalid IL or missing references)
				//IL_006e: Unknown result type (might be due to invalid IL or missing references)
				//IL_008c: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					ulong mimickingID = default(ulong);
					ByteUnpacker.ReadValueBitPacked(reader, ref mimickingID);
					bool flag = default(bool);
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
					string maskedID = null;
					if (flag)
					{
						((FastBufferReader)(ref reader)).ReadValueSafe(ref maskedID, false);
					}
					target.__rpc_exec_stage = (__RpcExecStage)1;
					((WendigosMessageHandler)(object)target).TryPlayAudioServerRpc(mimickingID, maskedID);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			private static void __rpc_handler_1350037529(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				//IL_009d: Unknown result type (might be due to invalid IL or missing references)
				NetworkManager networkManager = target.NetworkManager;
				if (networkManager != null && networkManager.IsListening)
				{
					ulong mimickingID = default(ulong);
					ByteUnpacker.ReadValueBitPacked(reader, ref mimickingID);
					int indexToPlay = default(int);
					ByteUnpacker.ReadValueBitPacked(reader, ref indexToPlay);
					bool flag = default(bool);
					((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
					string maskedID = null;
					if (flag)
					{
						((FastBufferReader)(ref reader)).ReadValueSafe(ref maskedID, false);
					}
					target.__rpc_exec_stage = (__RpcExecStage)2;
					((WendigosMessageHandler)(object)target).PlayAudioClientRpc(mimickingID, indexToPlay, maskedID);
					target.__rpc_exec_stage = (__RpcExecStage)0;
				}
			}

			protected internal override string __getTypeName()
			{
				return "WendigosMessageHandler";
			}
		}

		public class WendigosLog
		{
			public bool generation_successful { get; set; }

			public DateTime last_successful_generation { get; set; }

			public string message { get; set; }

			public WendigosLog()
			{
				generation_successful = false;
				last_successful_generation = DateTime.MinValue;
				message = string.Empty;
			}

			public void Load()
			{
				if (File.Exists(assembly_path + "\\WendigosLog.json"))
				{
					WendigosLog wendigosLog = ReadFromJsonFile<WendigosLog>(assembly_path + "\\WendigosLog.json");
					generation_successful = wendigosLog.generation_successful;
					last_successful_generation = wendigosLog.last_successful_generation;
					message = wendigosLog.message;
				}
			}

			public void Save()
			{
				WriteToJsonFile(assembly_path + "\\WendigosLog.json", this);
			}
		}

		public enum Languages
		{
			English,
			Spanish,
			French,
			German,
			Italian,
			Portuguese,
			Polish,
			Turkish,
			Russian,
			Dutch,
			Czech,
			Arabic,
			Chinese,
			Japanese,
			Hungarian,
			Korean,
			Hindi
		}

		[HarmonyPatch(typeof(StartOfRound), "OnPlayerDC")]
		private class PlayerDCPatch
		{
			private static void Prefix(int playerObjectNumber, ulong clientId)
			{
				WriteToConsole($"Clearing {clientId}'s audio clips");
				WriteToConsole($"Removed {audioClips[clientId].Count} Clips");
				audioClips[clientId].Clear();
				WriteToConsole("AudioClip count is now " + get_clips_count());
				if (!((NetworkBehaviour)WendigosMessageHandler.Instance).IsServer)
				{
					return;
				}
				WendigosMessageHandler.ConnectedClientIDs.Remove(clientId);
				Dictionary<string, ulong> dictionary = new Dictionary<string, ulong>(sharedMaskedClientDict);
				foreach (string key in dictionary.Keys)
				{
					if (sharedMaskedClientDict[key] == clientId)
					{
						sharedMaskedClientDict.Remove(key);
					}
				}
				foreach (string key2 in serverReadyDict.Keys)
				{
					serverReadyDict[key2][clientId] = true;
				}
			}
		}

		[HarmonyPatch(typeof(MaskedPlayerEnemy), "Update")]
		private class MaskedPlayerEnemyUpdatePatch
		{
			private static void Prefix()
			{
				StartOfRound instance = StartOfRound.Instance;
				PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "OnLocalDisconnect")]
		private class DisconnectPatch
		{
			private static void Postfix()
			{
				foreach (List<AudioClip> value in audioClips.Values)
				{
					value.Clear();
				}
				sent_localID = false;
			}
		}

		[HarmonyPatch(typeof(MaskedPlayerEnemy), "DoAIInterval")]
		private class MaskedPlayerEnemyAIPatch
		{
			private static void Prefix(MaskedPlayerEnemy __instance)
			{
				if (((EnemyAI)__instance).isEnemyDead)
				{
					((EnemyAI)__instance).agent.speed = 0f;
					return;
				}
				string[] array = new string[3] { "idle", "nearby", "chasing" };
				string text = array[serverRand.Next(array.Length)];
				string id = ((Component)__instance).gameObject.GetComponent<MaskedEnemyIdentifier>().id;
				ulong num = 0uL;
				if (!sharedMaskedClientDict.Keys.Contains(id))
				{
					return;
				}
				num = sharedMaskedClientDict[id];
				switch (((EnemyAI)__instance).currentBehaviourStateIndex)
				{
				case 0:
					if ((Object)(object)((EnemyAI)__instance).CheckLineOfSightForClosestPlayer(45f, 60, -1, 0f) != (Object)null)
					{
						WendigosMessageHandler.Instance.TryPlayAudioServerRpc(num, id);
					}
					else
					{
						WendigosMessageHandler.Instance.TryPlayAudioServerRpc(num, id);
					}
					break;
				case 1:
					break;
				case 2:
					break;
				}
			}
		}

		[HarmonyPatch(typeof(MaskedPlayerEnemy), "SetVisibilityOfMaskedEnemy")]
		private class MaskedPlayerEnemyVisibilityPatch
		{
			private static void Postfix(MaskedPlayerEnemy __instance)
			{
				if ((bool)Traverse.Create((object)__instance).Field("enemyEnabled").GetValue())
				{
					((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskComedy")).gameObject.SetActive(false);
					((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskTragedy")).gameObject.SetActive(false);
				}
			}
		}

		[HarmonyPatch(typeof(MaskedPlayerEnemy), "SetHandsOutClientRpc")]
		private class MaskedPlayerEnemyRemoveHands
		{
			private static void Prefix(ref bool setOut, MaskedPlayerEnemy __instance)
			{
				setOut = false;
				string text = "chasing";
				string id = ((Component)__instance).gameObject.GetComponent<MaskedEnemyIdentifier>().id;
				if (sharedMaskedClientDict.Keys.Contains(id))
				{
					ulong mimickingID = sharedMaskedClientDict[id];
					WendigosMessageHandler.Instance.TryPlayAudioServerRpc(mimickingID, id);
				}
			}
		}

		public class MaskedEnemyIdentifier : MonoBehaviour
		{
			public string id;
		}

		[HarmonyPatch(typeof(MaskedPlayerEnemy), "Start")]
		private class MaskedStartPatch
		{
			private static void Postfix(MaskedPlayerEnemy __instance)
			{
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				((Component)__instance).gameObject.AddComponent<MaskedEnemyIdentifier>();
				MaskedEnemyIdentifier component = ((Component)__instance).gameObject.GetComponent<MaskedEnemyIdentifier>();
				Vector3 position = ((Component)__instance).transform.position;
				component.id = ((object)(Vector3)(ref position)).ToString();
				maskedInstanceLookup.TryAdd(((Component)__instance).gameObject.GetComponent<MaskedEnemyIdentifier>().id, __instance);
				WriteToConsole("Spawned Masked. ID: " + ((Component)__instance).gameObject.GetComponent<MaskedEnemyIdentifier>().id);
				if (((NetworkBehaviour)WendigosMessageHandler.Instance).IsServer)
				{
					List<ulong> list = new List<ulong>();
					WriteToConsole(WendigosMessageHandler.ConnectedClientIDs.ToString());
					foreach (ulong connectedClientID in WendigosMessageHandler.ConnectedClientIDs)
					{
						if (!sharedMaskedClientDict.Values.Contains(connectedClientID))
						{
							list.Add(connectedClientID);
						}
					}
					WriteToConsole("Created unasssigned list");
					if (list.Count == 0)
					{
						return;
					}
					ulong num = list[serverRand.Next() % list.Count];
					WendigosMessageHandler.Instance.AddToMaskedClientDictServerRpc(((Component)__instance).gameObject.GetComponent<MaskedEnemyIdentifier>().id, num);
					if (!serverReadyDict.TryAdd(((Component)__instance).gameObject.GetComponent<MaskedEnemyIdentifier>().id, new Dictionary<ulong, bool>()))
					{
						WriteToConsole("Failed to add masked");
					}
					WriteToConsole("added masked to per_masked_ready_dict");
					PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
					PlayerControllerB[] array = allPlayerScripts;
					foreach (PlayerControllerB val in array)
					{
						if (val.actualClientId == num)
						{
							WendigosMessageHandler.Instance.SetMaskedSuitClientRpc(((Component)__instance).gameObject.GetComponent<MaskedEnemyIdentifier>().id, val.currentSuitID);
							break;
						}
					}
				}
				WriteToConsole("Finished Spawning Masked");
			}
		}

		[HarmonyPatch(typeof(RoundManager), "LoadNewLevel")]
		private class RoundManagerSpawnPatch
		{
			private static void Prefix()
			{
				WriteToConsole("Clearing chared masked dict");
				serverReadyDict.Clear();
				sharedMaskedClientDict.Clear();
				WriteToConsole("Sorting Audioclips");
				sort_audioclips();
				if (NetworkManager.Singleton.IsServer)
				{
					WendigosMessageHandler.Instance.SortAudioClipsClientRpc();
				}
			}
		}

		[HarmonyPatch(typeof(IngamePlayerSettings), "LoadSettingsFromPrefs")]
		private class IngamePlayerSettingsLoadPatch
		{
			private static void Postfix(IngamePlayerSettings __instance)
			{
				mic_name = IngamePlayerSettings.Instance.settings.micDevice;
				WriteToConsole(mic_name);
			}
		}

		[HarmonyPatch(typeof(IngamePlayerSettings), "SaveChangedSettings")]
		private class IngamePlayerSettingsMicSavePatch
		{
			private static void Postfix(IngamePlayerSettings __instance)
			{
				mic_name = IngamePlayerSettings.Instance.settings.micDevice;
				WriteToConsole("Set to " + mic_name);
			}
		}

		[HarmonyPatch(typeof(MenuManager), "Start")]
		private class MenuManagerPatch
		{
			private static void Postfix(MenuManager __instance)
			{
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_0131: Unknown result type (might be due to invalid IL or missing references)
				//IL_0142: Unknown result type (might be due to invalid IL or missing references)
				//IL_0159: Unknown result type (might be due to invalid IL or missing references)
				//IL_0163: Unknown result type (might be due to invalid IL or missing references)
				if (__instance.isInitScene)
				{
					Task.Factory.StartNew(GeneratePlayerAudioClips);
					if (!elevenlabs_enabled.Value)
					{
						Task.Factory.StartNew((Func<Task>)download_main_exe);
					}
					return;
				}
				try
				{
					steamID = SteamClient.SteamId.Value;
				}
				catch
				{
					steamID = 1uL;
				}
				__instance.NewsPanel.SetActive(false);
				if (!File.Exists(assembly_path + "\\sample_player_audio\\sample_player0_audio.wav") || need_new_player_audio.Value)
				{
					if (!elevenlabs_enabled.Value)
					{
						need_new_player_audio.Value = true;
						__instance.DisplayMenuNotification("Press R to record some voice lines.\nSelected Mic is " + mic_name, "[ Close ]");
						Transform val = __instance.menuNotification.transform.Find("Panel").Find("ResponseButton");
						((Component)val).transform.position = new Vector3(((Component)val).transform.position.x, ((Component)val).transform.position.y - 10f, ((Component)val).transform.position.z);
					}
				}
				else if (!doneGenerating)
				{
					__instance.DisplayMenuNotification("Please wait for audio clips to finish generating", "[ close ]");
					GeneratingAnimation(__instance);
				}
			}
		}

		[HarmonyPatch(typeof(MenuManager), "Update")]
		private class MenuManagerUpdatePatch
		{
			private static int index;

			private static bool recorded;

			private static Task task1;

			private static void Postfix(MenuManager __instance)
			{
				if (__instance.isInitScene || !__instance.menuNotification.activeInHierarchy || elevenlabs_enabled.Value)
				{
					return;
				}
				if (!Microphone.IsRecording(mic_name) && !recorded)
				{
					if (UnityInput.Current.GetKeyUp("R"))
					{
						recorded = true;
						int num = default(int);
						int num2 = default(int);
						Microphone.GetDeviceCaps(mic_name, ref num, ref num2);
						mic_audio_clip = Microphone.Start(mic_name, false, 600, num2);
						((TMP_Text)__instance.menuNotificationButtonText).text = "Recording...";
						((TMP_Text)__instance.menuNotificationText).text = "Press Q to quit recording\nPress N for next line\n- - " + (index + 1) + "/" + lines_to_read.Length + " - -\n" + lines_to_read[index];
					}
				}
				else if (UnityInput.Current.GetKeyUp("Q") && need_new_player_audio.Value)
				{
					Microphone.End(mic_name);
					((TMP_Text)__instance.menuNotificationButtonText).text = "[ don't close ]";
					((TMP_Text)__instance.menuNotificationText).text = "Recording stopped.\nPlease wait for audio clips to finish generating ";
					SavWav.Save(assembly_path + "\\sample_player_audio\\sample_player0_audio.wav", mic_audio_clip, trim: true);
					doneGenerating = false;
					if (task1 == null)
					{
						task1 = Task.Factory.StartNew(delegate
						{
							GenerateAllPlayerSentences(new_player_audio: true);
						});
					}
					need_new_player_audio.Value = false;
					GeneratingAnimation(__instance);
				}
				else if (UnityInput.Current.GetKeyUp("N") && need_new_player_audio.Value)
				{
					if (index + 1 < lines_to_read.Length)
					{
						index++;
						((TMP_Text)__instance.menuNotificationText).text = "Press Q to quit recording\nPress N for next line\n- - " + (index + 1) + "/" + lines_to_read.Length + " - -\n" + lines_to_read[index];
					}
					else
					{
						Microphone.End(mic_name);
						((TMP_Text)__instance.menuNotificationButtonText).text = "[ don't close ]";
						((TMP_Text)__instance.menuNotificationText).text = "Recording stopped.\nPlease wait for audio clips to finish generating ";
						SavWav.Save(assembly_path + "\\sample_player_audio\\sample_player0_audio.wav", mic_audio_clip, trim: true);
						doneGenerating = false;
						if (task1 == null)
						{
							task1 = Task.Factory.StartNew(delegate
							{
								GenerateAllPlayerSentences(new_player_audio: true);
							});
						}
						need_new_player_audio.Value = false;
						GeneratingAnimation(__instance);
					}
				}
				if (doneGenerating && !need_new_player_audio.Value)
				{
					((TMP_Text)__instance.menuNotificationButtonText).text = "[ close ]";
					((TMP_Text)__instance.menuNotificationText).text = "Voice lines finished generating!";
				}
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ShowNameBillboard")]
		private class HidePlayerNamePatch
		{
			private static void Postfix(PlayerControllerB __instance)
			{
				__instance.usernameAlpha.alpha = 0f;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		private class PlayerConnectPatch
		{
			private static void Postfix()
			{
				if (!sent_localID)
				{
					WendigosMessageHandler.Instance.UpdateClientListServerRpc(NetworkManager.Singleton.LocalClientId);
					if (!audioClips.Keys.Contains(NetworkManager.Singleton.LocalClientId))
					{
						audioClips.Add(NetworkManager.Singleton.LocalClientId, new List<AudioClip>());
					}
					sent_localID = true;
				}
			}
		}

		public static string[] LanguagesList = new string[17]
		{
			"en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl",
			"cs", "ar", "zh-cn", "ja", "hu", "ko", "hi"
		};

		private static string MAIN_HASH_VALUE = "20ca39002a389704d5499df0f522848ec21fe724f8d13de830d596f28df69a7ae860aa4bb58e0b7ddbefcdf3e96b902fc2f98fca37777a4bf08de15af231f36e";

		private static bool main_downloaded = false;

		private static bool doneGenerating = false;

		private static int sentenceTypesCompleted = 0;

		private static ConfigEntry<bool> mod_enabled;

		private static ConfigEntry<bool> need_new_player_audio;

		private static ConfigEntry<Languages> voice_language;

		private static ConfigEntry<bool> elevenlabs_enabled;

		private static ConfigEntry<string> elevenlabs_api_key;

		private static ConfigEntry<string> elevenlabs_voice_id;

		private static Random serverRand = new Random();

		private static Dictionary<string, Dictionary<ulong, bool>> serverReadyDict = new Dictionary<string, Dictionary<ulong, bool>>();

		private static Dictionary<string, ulong> sharedMaskedClientDict = new Dictionary<string, ulong>();

		private Harmony harmonyInstance = new Harmony("my-instance");

		private static string config_path;

		private static string assembly_path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

		private static DateTime last_successful_generation;

		private static WendigosLog log = new WendigosLog();

		internal static string mic_name;

		internal static ulong steamID;

		private static AudioClip mic_audio_clip;

		private static List<AudioClip> myClips = new List<AudioClip>();

		public static Dictionary<ulong, List<AudioClip>> audioClips = new Dictionary<ulong, List<AudioClip>> { 
		{
			0uL,
			new List<AudioClip>()
		} };

		private static Dictionary<string, MaskedPlayerEnemy> maskedInstanceLookup = new Dictionary<string, MaskedPlayerEnemy>();

		private static string[] lines_to_read = (from a in "Prosecutors have opened a massive investigation into allegations of fixing games and illegal betting.\r\nDifferent telescope designs perform differently and have different strengths and weaknesses.\r\nWe can continue to strengthen the education of good lawyers.\r\nFeedback must be timely and accurate throughout the project.\r\nHumans also judge distance by using the relative sizes of objects.\r\nChurches should not encourage it or make it look harmless.\r\nLearn about setting up wireless network configuration.\r\nYou can eat them fresh, cooked or fermented.\r\nIf this is true then those who tend to think creatively really are somehow different.\r\nShe will likely jump for joy and want to skip straight to the honeymoon.\r\nThe sugar syrup should create very fine strands of sugar that drape over the handles.\r\nBut really in the grand scheme of things, this information is insignificant.\r\nI let the positive overrule the negative.\r\nHe wiped his brow with his forearm.\r\nInstead of fixing it, they give it a nickname.\r\nAbout half the people who are infected also lose weight.\r\nThe second half of the book focuses on argument and essay writing.\r\nWe have the means to help ourselves.\r\nThe large items are put into containers for disposal.\r\nHe loves to watch me drink this stuff.\r\nStill, it is an odd fashion choice.\r\nFunding is always an issue after the fact.\r\nLet us encourage each other.\r\nSubscribe to @Tim-Shaw on YouTube".Split('\n')
			orderby serverRand.Next()
			select a).ToArray();

		private static bool sent_localID = false;

		private static void sort_audioclips()
		{
			foreach (List<AudioClip> value in audioClips.Values)
			{
				value.Sort((AudioClip c1, AudioClip c2) => ((Object)c1).name.CompareTo(((Object)c2).name));
			}
			WriteToConsole("sorted");
		}

		private static void WriteToConsole(string output)
		{
			Console.WriteLine("Wendigos: " + output);
		}

		private static void Open_YT_URL()
		{
			Application.OpenURL("https://www.youtube.com/@Tim-Shaw");
		}

		private static string CalculateMainHash(string filename)
		{
			WriteToConsole("Calculating hash...");
			using SHA512 sHA = SHA512.Create();
			using FileStream inputStream = File.OpenRead(filename);
			byte[] array = sHA.ComputeHash(inputStream);
			return BitConverter.ToString(array).Replace("-", "").ToLowerInvariant();
		}

		private static async Task download_main_exe()
		{
			if (File.Exists(assembly_path + "\\main.exe"))
			{
				WriteToConsole(CalculateMainHash(assembly_path + "\\main.exe"));
				if (CalculateMainHash(assembly_path + "\\main.exe").Equals(MAIN_HASH_VALUE))
				{
					WriteToConsole("Valid main.exe");
					main_downloaded = true;
					sentenceTypesCompleted++;
				}
				else
				{
					WriteToConsole("INVALID main.exe already downloaded. Redownloading...");
					File.Delete(assembly_path + "\\main.exe");
					await download_main_exe();
				}
				return;
			}
			WriteToConsole("Downloading main.exe for voice generation");
			using (WebClient wc = new WebClient())
			{
				try
				{
					wc.DownloadFile("https://github.com/TimShaw1/Wendigos-Mod/releases/download/v0.1.0/main.exe", assembly_path + "\\main.exe");
				}
				catch (Exception ex2)
				{
					Exception ex = ex2;
					WriteToConsole(ex.Message);
				}
			}
			if (File.Exists(assembly_path + "\\main.exe"))
			{
				main_downloaded = true;
				sentenceTypesCompleted++;
				WriteToConsole("main.exe finished downloading");
				if (CalculateMainHash(assembly_path + "\\main.exe").Equals(MAIN_HASH_VALUE))
				{
					WriteToConsole("Valid main.exe");
					return;
				}
				WriteToConsole("INVALID main.exe");
				File.Delete(assembly_path + "\\main.exe");
			}
			else
			{
				WriteToConsole("main.exe failed to download");
			}
		}

		private static void GeneratePlayerSentences(string file_name, string sentences_file_path)
		{
			File.WriteAllText(assembly_path + "\\player_sentences\\player0_sentences.txt", File.ReadAllText(sentences_file_path));
			WriteToConsole("wrote to sentences text file");
			if (Directory.Exists(assembly_path + "\\audio_output\\player0\\" + file_name))
			{
				Directory.Delete(assembly_path + "\\audio_output\\player0\\" + file_name, recursive: true);
				WriteToConsole("deleted old wav files for " + file_name);
			}
			Directory.CreateDirectory(assembly_path + "\\audio_output\\player0\\" + file_name);
			WriteToConsole("created directory \\audio_output\\player0\\" + file_name);
			while (!main_downloaded)
			{
			}
			ProcessStartInfo processStartInfo = new ProcessStartInfo();
			processStartInfo.CreateNoWindow = false;
			processStartInfo.UseShellExecute = false;
			processStartInfo.FileName = "cmd.exe";
			processStartInfo.WorkingDirectory = assembly_path;
			processStartInfo.Arguments = "/C (set PYTORCH_JIT=0)&(main.exe " + file_name + " " + LanguagesList[(int)voice_language.Value] + ")";
			processStartInfo.RedirectStandardOutput = true;
			processStartInfo.RedirectStandardError = true;
			processStartInfo.RedirectStandardInput = true;
			processStartInfo.StandardOutputEncoding = Encoding.UTF8;
			try
			{
				Process exeProcess = Process.Start(processStartInfo);
				try
				{
					WriteToConsole("started process");
					exeProcess.OutputDataReceived += delegate(object sender, DataReceivedEventArgs args)
					{
						WriteToConsole("received output: " + args.Data);
						if (args.Data.Contains("[y/n]"))
						{
							WriteToConsole("WAITING FOR MODEL DOWNLOAD ... (1.75gb)");
							exeProcess.StandardInput.WriteLine("y");
						}
					};
					exeProcess.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs args)
					{
						WriteToConsole(args.Data);
					};
					exeProcess.BeginOutputReadLine();
					exeProcess.BeginErrorReadLine();
					WriteToConsole("LOADING MODEL " + LanguagesList[(int)voice_language.Value] + "...");
					exeProcess.WaitForExit();
				}
				finally
				{
					if (exeProcess != null)
					{
						((IDisposable)exeProcess).Dispose();
					}
				}
			}
			catch
			{
			}
			File.Delete(assembly_path + "\\player_sentences\\player0_sentences.txt");
			WriteToConsole("deleted temporary sentences text file");
		}

		private static async void GeneratePlayerSentencesElevenlabs(string file_name, string sentences_file_path)
		{
			WriteToConsole("IN ELEVENLABS GEN");
			if (Directory.Exists(assembly_path + "\\audio_output\\player0\\" + file_name))
			{
				Directory.Delete(assembly_path + "\\audio_output\\player0\\" + file_name, recursive: true);
				WriteToConsole("deleted old wav files for " + file_name);
			}
			Directory.CreateDirectory(assembly_path + "\\audio_output\\player0\\" + file_name);
			WriteToConsole("created directory \\audio_output\\player0\\" + file_name);
			ElevenLabs elevenlabs_client = new ElevenLabs(elevenlabs_api_key.Value);
			string[] readText = File.ReadAllLines(sentences_file_path);
			int i = 0;
			string[] array = readText;
			foreach (string s in array)
			{
				await elevenlabs_client.RequestAudio(s, elevenlabs_voice_id.Value, file_name + "0_line", assembly_path + "\\audio_output\\player0\\" + file_name + "\\", i);
				i++;
			}
		}

		private static void GenerateAllPlayerSentences(bool new_player_audio = false)
		{
			if (doneGenerating)
			{
				WriteToConsole("Already Generated");
				return;
			}
			string message = log.message;
			log.generation_successful = false;
			log.message = "Not finished generating player sentences";
			log.Save();
			bool flag = File.Exists(assembly_path + "\\sample_player_audio\\sample_player0_audio.wav");
			bool flag3;
			bool flag2;
			bool flag4 = (flag3 = (flag2 = new_player_audio));
			if (elevenlabs_enabled.Value)
			{
				flag = true;
				WriteToConsole("ELEVENLABS ENABLED");
				if (message != "Elevenlabs")
				{
					flag4 = (flag3 = (flag2 = true));
				}
			}
			if (!File.Exists(config_path + "Wendigos\\player_sentences\\player0_idle_sentences.txt"))
			{
				File.WriteAllText(config_path + "Wendigos\\player_sentences\\player0_idle_sentences.txt", "Help me\nStop Sign Over Here\nWhere is everyone?");
			}
			if (flag && isFileChanged(config_path + "Wendigos\\player_sentences\\player0_idle_sentences.txt"))
			{
				flag4 = true;
			}
			if (flag4)
			{
				WriteToConsole("generating idle sentences");
				if (!elevenlabs_enabled.Value)
				{
					GeneratePlayerSentences("idle", config_path + "Wendigos\\player_sentences\\player0_idle_sentences.txt");
				}
				else
				{
					GeneratePlayerSentencesElevenlabs("idle", config_path + "Wendigos\\player_sentences\\player0_idle_sentences.txt");
				}
				sentenceTypesCompleted++;
				log.last_successful_generation = DateTime.Now;
			}
			if (!File.Exists(config_path + "Wendigos\\player_sentences\\player0_nearby_sentences.txt"))
			{
				File.WriteAllText(config_path + "Wendigos\\player_sentences\\player0_nearby_sentences.txt", "What's up?\nFind anything?\nhaha yeah");
			}
			if (flag && isFileChanged(config_path + "Wendigos\\player_sentences\\player0_nearby_sentences.txt"))
			{
				flag3 = true;
			}
			if (flag3)
			{
				WriteToConsole("generating nearby sentences");
				if (!elevenlabs_enabled.Value)
				{
					GeneratePlayerSentences("nearby", config_path + "Wendigos\\player_sentences\\player0_nearby_sentences.txt");
				}
				else
				{
					GeneratePlayerSentencesElevenlabs("nearby", config_path + "Wendigos\\player_sentences\\player0_nearby_sentences.txt");
				}
				sentenceTypesCompleted++;
				log.last_successful_generation = DateTime.Now;
			}
			if (!File.Exists(config_path + "Wendigos\\player_sentences\\player0_chasing_sentences.txt"))
			{
				File.WriteAllText(config_path + "Wendigos\\player_sentences\\player0_chasing_sentences.txt", "wait come back\nwhere are you going?\nbye");
			}
			if (flag && isFileChanged(config_path + "Wendigos\\player_sentences\\player0_chasing_sentences.txt"))
			{
				flag2 = true;
			}
			if (flag2)
			{
				WriteToConsole("generating chasing sentences");
				if (!elevenlabs_enabled.Value)
				{
					GeneratePlayerSentences("chasing", config_path + "Wendigos\\player_sentences\\player0_chasing_sentences.txt");
				}
				else
				{
					GeneratePlayerSentencesElevenlabs("chasing", config_path + "Wendigos\\player_sentences\\player0_chasing_sentences.txt");
				}
				sentenceTypesCompleted++;
				log.last_successful_generation = DateTime.Now;
			}
			log.generation_successful = true;
			if (elevenlabs_enabled.Value)
			{
				log.message = "Elevenlabs";
			}
			else
			{
				log.message = "";
			}
			log.Save();
			doneGenerating = true;
			GeneratePlayerAudioClips();
			sentenceTypesCompleted++;
			WriteToConsole("Finished generating voice lines.");
		}

		private static bool isFileChanged(string path)
		{
			DateTime lastWriteTime = File.GetLastWriteTime(path);
			return lastWriteTime > last_successful_generation;
		}

		public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
		{
			TextWriter textWriter = null;
			try
			{
				string value = JsonConvert.SerializeObject((object)objectToWrite);
				textWriter = new StreamWriter(filePath, append);
				textWriter.Write(value);
			}
			finally
			{
				textWriter?.Close();
			}
		}

		public static T ReadFromJsonFile<T>(string filePath) where T : new()
		{
			TextReader textReader = null;
			try
			{
				textReader = new StreamReader(filePath);
				string text = textReader.ReadToEnd();
				return JsonConvert.DeserializeObject<T>(text);
			}
			finally
			{
				textReader?.Close();
			}
		}

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Wendigos is loaded!");
			mod_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enable mod?", false, "Enables the mod");
			need_new_player_audio = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Record new player sample audio?", true, "Whether the record audio prompt should show up");
			voice_language = ((BaseUnityPlugin)this).Config.Bind<Languages>("General", "Language", Languages.English, "What language the voice generator should use");
			elevenlabs_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Elevenlabs", "Enabled", false, "Whether to use elevenlabs for ai voice generation");
			if (elevenlabs_enabled.Value)
			{
				need_new_player_audio.Value = false;
			}
			elevenlabs_api_key = ((BaseUnityPlugin)this).Config.Bind<string>("Elevenlabs", "API key", "", "Your elevenlabs API key");
			elevenlabs_voice_id = ((BaseUnityPlugin)this).Config.Bind<string>("Elevenlabs", "Voice id", "", "Your elevenlabs voice id");
			if (!mod_enabled.Value)
			{
				return;
			}
			log.Load();
			log.Save();
			if (log.generation_successful)
			{
				last_successful_generation = log.last_successful_generation;
			}
			else
			{
				last_successful_generation = DateTime.MinValue;
			}
			harmonyInstance.PatchAll();
			SceneManager.sceneLoaded += WendigosMessageHandler.ClientConnectInitializer;
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			config_path = ((BaseUnityPlugin)this).Config.ConfigFilePath.Replace("Wendigos.cfg", "");
			Directory.CreateDirectory(config_path + "Wendigos\\player_sentences");
			Directory.CreateDirectory(assembly_path + "\\player_sentences");
			Directory.CreateDirectory(assembly_path + "\\sample_player_audio");
			Directory.CreateDirectory(assembly_path + "\\audio_output");
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Wendigos: Created/found config directories");
			bool flag = File.Exists(assembly_path + "\\sample_player_audio\\sample_player0_audio.wav");
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Wendigos: " + (flag ? "found" : "didn't find") + " player sample audio"));
			doneGenerating = false;
			Task.Factory.StartNew(delegate
			{
				GenerateAllPlayerSentences();
			});
		}

		public static string GetHashSHA1(byte[] data)
		{
			using SHA1CryptoServiceProvider sHA1CryptoServiceProvider = new SHA1CryptoServiceProvider();
			return string.Concat(from x in sHA1CryptoServiceProvider.ComputeHash(data)
				select x.ToString("X2"));
		}

		private static AudioClip LoadAudioFile(string audioFilePath)
		{
			if (elevenlabs_enabled.Value)
			{
				return LoadMP3File(audioFilePath);
			}
			return LoadWavFile(audioFilePath);
		}

		private static AudioClip LoadWavFile(string audioFilePath)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			if (File.Exists(audioFilePath))
			{
				UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(audioFilePath, (AudioType)20);
				try
				{
					audioClip.SendWebRequest();
					while ((int)audioClip.result == 0)
					{
					}
					if ((int)audioClip.result != 1)
					{
						WriteToConsole("www.error " + audioClip.error);
						WriteToConsole(" www.uri " + audioClip.uri);
						WriteToConsole(" www.url " + audioClip.url);
						Result result = audioClip.result;
						WriteToConsole(" www.result " + ((object)(Result)(ref result)).ToString());
						return null;
					}
					return DownloadHandlerAudioClip.GetContent(audioClip);
				}
				finally
				{
					((IDisposable)audioClip)?.Dispose();
				}
			}
			WriteToConsole("AUDIO FILE NOT FOUND");
			return null;
		}

		private static AudioClip LoadMP3File(string audioFilePath)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			if (File.Exists(audioFilePath))
			{
				UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(audioFilePath, (AudioType)13);
				try
				{
					audioClip.SendWebRequest();
					while ((int)audioClip.result == 0)
					{
					}
					if ((int)audioClip.result != 1)
					{
						WriteToConsole("www.error " + audioClip.error);
						WriteToConsole(" www.uri " + audioClip.uri);
						WriteToConsole(" www.url " + audioClip.url);
						Result result = audioClip.result;
						WriteToConsole(" www.result " + ((object)(Result)(ref result)).ToString());
						return null;
					}
					return DownloadHandlerAudioClip.GetContent(audioClip);
				}
				finally
				{
					((IDisposable)audioClip)?.Dispose();
				}
			}
			WriteToConsole("AUDIO FILE NOT FOUND");
			return null;
		}

		private static void TryToPlayAudio(AudioClip clip, string maskedID)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				WendigosMessageHandler.Instance.TellServerReadyToSendServerRpc(maskedID, ready: false);
				MaskedPlayerEnemy val = maskedInstanceLookup[maskedID];
				if (Object.op_Implicit((Object)(object)clip) && !((EnemyAI)val).creatureVoice.isPlaying)
				{
					((EnemyAI)val).creatureVoice.PlayOneShot(clip);
					waitThenSayReady(val, maskedID);
				}
			}
			catch (Exception ex)
			{
				WriteToConsole("Playing audio failed: " + ex.Message + ": " + ex.Source);
			}
		}

		private static async void waitThenSayReady(MaskedPlayerEnemy __instance, string maskedID)
		{
			WriteToConsole("WAITING");
			while (((EnemyAI)__instance).creatureVoice.isPlaying)
			{
				await Task.Delay(10);
			}
			WriteToConsole("SAYING READY");
			WendigosMessageHandler.Instance.TellServerReadyToSendServerRpc(maskedID, ready: true);
		}

		private static string GetPathOfWav(string type, int lineNum = -1)
		{
			if (lineNum < 0)
			{
				Random random = new Random();
				lineNum = random.Next(CountFilesInDir(GetPathOfType(type)));
			}
			return assembly_path + "\\audio_output\\player0\\" + type + "\\" + type + "0_line" + lineNum + ".wav";
		}

		private static string GetPathOfType(string type)
		{
			return assembly_path + "\\audio_output\\player