Decompiled source of ReppoModHU v1.0.0

plugins/ReppoModHU.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ReppoModHU;

[BepInPlugin("local.reppo.modhu", "ReppoModHU", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Plugin : BaseUnityPlugin
{
	private class Rule
	{
		public string Assembly;

		public Regex Methods;

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

		public readonly List<string> NamePostfixes = new List<string>();

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

		public readonly Dictionary<string, int[]> ArgPatches = new Dictionary<string, int[]>();

		public readonly List<string> Statics = new List<string>();
	}

	internal static ManualLogSource Log;

	private static readonly Dictionary<string, Rule> rules = new Dictionary<string, Rule>();

	private static readonly Dictionary<string, Rule> byAssembly = new Dictionary<string, Rule>();

	private static readonly Dictionary<string, string> names = new Dictionary<string, string>();

	private static readonly Dictionary<string, string> tailSep = new Dictionary<string, string>();

	private static readonly Dictionary<MethodBase, string> tailByMethod = new Dictionary<MethodBase, string>();

	private static readonly List<KeyValuePair<Assembly, Rule>> withStatics = new List<KeyValuePair<Assembly, Rule>>();

	private static bool started;

	private static int replaced;

	private static Harmony harmony;

	private static readonly char[] CR = new char[1] { '\r' };

	private static readonly char[] Comma = new char[1] { ',' };

	private static Rule FindRule(string asmName)
	{
		if (rules.TryGetValue(asmName, out var value))
		{
			return value;
		}
		foreach (KeyValuePair<string, Rule> rule in rules)
		{
			if (rule.Key.EndsWith("*") && asmName.StartsWith(rule.Key.Substring(0, rule.Key.Length - 1)))
			{
				return rule.Value;
			}
		}
		return null;
	}

	private void Awake()
	{
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
		string text = Path.Combine(directoryName, "ReppoModHU.txt");
		if (!File.Exists(text))
		{
			Log.LogWarning((object)("Rules file not found: " + text));
			return;
		}
		LoadRules(text);
		LoadNames(Path.Combine(Paths.ConfigPath, Path.Combine("Translation", Path.Combine("hu", "Text"))));
		harmony = new Harmony("local.reppo.modhu");
		AppDomain.CurrentDomain.AssemblyLoad += delegate(object sender, AssemblyLoadEventArgs args)
		{
			TryPatch(args.LoadedAssembly);
		};
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly asm in assemblies)
		{
			TryPatch(asm);
		}
		Log.LogInfo((object)("Hungarian texts patched into mods: " + replaced + " string(s), " + names.Count + " names loaded."));
	}

	private void Start()
	{
		started = true;
		foreach (KeyValuePair<Assembly, Rule> withStatic in withStatics)
		{
			ApplyStatics(withStatic.Key, withStatic.Value);
		}
	}

	private static void TryPatch(Assembly asm)
	{
		string name;
		try
		{
			name = asm.GetName().Name;
		}
		catch (Exception)
		{
			return;
		}
		Rule rule = FindRule(name);
		if (rule == null || byAssembly.ContainsKey(name))
		{
			return;
		}
		byAssembly[name] = rule;
		try
		{
			PatchAssembly(harmony, asm, rule);
		}
		catch (Exception ex2)
		{
			Log.LogWarning((object)(rule.Assembly + ": " + ex2.Message));
		}
		if (rule.Statics.Count > 0)
		{
			withStatics.Add(new KeyValuePair<Assembly, Rule>(asm, rule));
			if (started)
			{
				ApplyStatics(asm, rule);
			}
		}
	}

	private static string Unescape(string s)
	{
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < s.Length; i++)
		{
			char c = s[i];
			if (c == '\\' && i + 1 < s.Length)
			{
				char c2 = s[++i];
				switch (c2)
				{
				case 'n':
					stringBuilder.Append('\n');
					break;
				case 't':
					stringBuilder.Append('\t');
					break;
				default:
					stringBuilder.Append(c2);
					break;
				}
			}
			else
			{
				stringBuilder.Append(c);
			}
		}
		return stringBuilder.ToString();
	}

	private static int SplitIndex(string line)
	{
		for (int i = 0; i < line.Length; i++)
		{
			if (line[i] == '\\')
			{
				i++;
			}
			else if (line[i] == '=')
			{
				return i;
			}
		}
		return -1;
	}

	private static void LoadRules(string path)
	{
		Rule rule = null;
		string[] array = File.ReadAllLines(path, Encoding.UTF8);
		foreach (string text in array)
		{
			string text2 = text.TrimEnd(CR);
			if (text2.Length == 0 || text2.StartsWith("#"))
			{
				continue;
			}
			if (text2.StartsWith("[") && text2.EndsWith("]"))
			{
				rule = new Rule();
				rule.Assembly = text2.Substring(1, text2.Length - 2).Trim();
				rules[rule.Assembly] = rule;
			}
			else
			{
				if (rule == null)
				{
					continue;
				}
				if (text2.StartsWith("@methods "))
				{
					rule.Methods = new Regex(text2.Substring(9).Trim());
				}
				else if (text2.StartsWith("@names "))
				{
					rule.NamePostfixes.Add(text2.Substring(7).Trim());
				}
				else if (text2.StartsWith("@tailnames "))
				{
					string text3 = text2.Substring(11);
					int num = text3.IndexOf('"');
					int num2 = text3.LastIndexOf('"');
					if (num > 0 && num2 > num)
					{
						rule.TailNames[text3.Substring(0, num).Trim()] = Unescape(text3.Substring(num + 1, num2 - num - 1));
					}
					else
					{
						Log.LogWarning((object)("Bad @tailnames line: " + text2));
					}
				}
				else if (text2.StartsWith("@args "))
				{
					string text4 = text2.Substring(6).Trim();
					int num3 = text4.LastIndexOf(' ');
					try
					{
						string[] array2 = text4.Substring(num3 + 1).Split(Comma);
						int[] array3 = new int[array2.Length];
						for (int j = 0; j < array2.Length; j++)
						{
							array3[j] = int.Parse(array2[j].Trim());
						}
						rule.ArgPatches[text4.Substring(0, num3).Trim()] = array3;
					}
					catch (Exception)
					{
						Log.LogWarning((object)("Bad @args line: " + text2));
					}
				}
				else if (text2.StartsWith("@statics "))
				{
					rule.Statics.Add(text2.Substring(9).Trim());
				}
				else
				{
					int num4 = SplitIndex(text2);
					if (num4 > 0)
					{
						rule.Literals[Unescape(text2.Substring(0, num4))] = Unescape(text2.Substring(num4 + 1));
					}
				}
			}
		}
	}

	private static void LoadNames(string dir)
	{
		if (!Directory.Exists(dir))
		{
			return;
		}
		string[] files = Directory.GetFiles(dir, "*.txt");
		foreach (string path in files)
		{
			string fileName = Path.GetFileName(path);
			if (fileName.StartsWith("_"))
			{
				continue;
			}
			string[] array = File.ReadAllLines(path, Encoding.UTF8);
			foreach (string text in array)
			{
				string text2 = text.TrimEnd(CR);
				if (text2.Length == 0 || text2.StartsWith("//") || text2.StartsWith("r:") || text2.StartsWith("sr:"))
				{
					continue;
				}
				int num = SplitIndex(text2);
				if (num > 0)
				{
					string key = Unescape(text2.Substring(0, num));
					if (!names.ContainsKey(key))
					{
						names[key] = Unescape(text2.Substring(num + 1));
					}
				}
			}
		}
	}

	internal static string TranslateName(string s)
	{
		if (string.IsNullOrEmpty(s))
		{
			return s;
		}
		if (names.TryGetValue(s, out var value))
		{
			return value;
		}
		string text = s.Trim();
		if (text != s && names.TryGetValue(text, out value))
		{
			return s.Replace(text, value);
		}
		return s;
	}

	private static IEnumerable<Type> SafeTypes(Assembly asm)
	{
		try
		{
			return asm.GetTypes();
		}
		catch (ReflectionTypeLoadException ex)
		{
			List<Type> list = new List<Type>();
			Type[] types = ex.Types;
			foreach (Type type in types)
			{
				if (type != null)
				{
					list.Add(type);
				}
			}
			return list;
		}
	}

	private static void PatchAssembly(Harmony harmony, Assembly asm, Rule rule)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Expected O, but got Unknown
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Expected O, but got Unknown
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Expected O, but got Unknown
		//IL_0208: Unknown result type (might be due to invalid IL or missing references)
		//IL_0212: Expected O, but got Unknown
		HarmonyMethod val = new HarmonyMethod(typeof(Plugin).GetMethod("Transpiler", BindingFlags.Static | BindingFlags.Public));
		HarmonyMethod val2 = new HarmonyMethod(typeof(Plugin).GetMethod("NamePostfix", BindingFlags.Static | BindingFlags.Public));
		HarmonyMethod val3 = new HarmonyMethod(typeof(Plugin).GetMethod("TailPostfix", BindingFlags.Static | BindingFlags.Public));
		int num = 0;
		foreach (Type item in SafeTypes(asm))
		{
			string text = (item.FullName ?? item.Name).Replace('+', '/');
			MethodInfo[] methods;
			try
			{
				methods = item.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			}
			catch (Exception)
			{
				continue;
			}
			MethodInfo[] array = methods;
			foreach (MethodInfo methodInfo in array)
			{
				if (methodInfo.IsAbstract || methodInfo.ContainsGenericParameters)
				{
					continue;
				}
				string text2 = text + "::" + methodInfo.Name;
				HarmonyMethod val4 = null;
				HarmonyMethod val5 = null;
				List<HarmonyMethod> list = new List<HarmonyMethod>();
				if (methodInfo.ReturnType == typeof(string))
				{
					string value;
					if (rule.NamePostfixes.Contains(text2))
					{
						val4 = val2;
					}
					else if (rule.TailNames.TryGetValue(text2, out value))
					{
						tailSep[text2] = value;
						val4 = val3;
					}
				}
				if (rule.ArgPatches.TryGetValue(text2, out var value2))
				{
					ParameterInfo[] parameters = methodInfo.GetParameters();
					int[] array2 = value2;
					foreach (int num2 in array2)
					{
						MethodInfo method = typeof(Plugin).GetMethod("ArgPrefix" + num2, BindingFlags.Static | BindingFlags.Public);
						if (method == null || num2 >= parameters.Length || parameters[num2].ParameterType != typeof(string))
						{
							Log.LogWarning((object)("@args: parameter " + num2 + " of " + text2 + " is not a text parameter."));
						}
						else
						{
							list.Add(new HarmonyMethod(method));
						}
					}
				}
				if (rule.Methods != null && rule.Methods.IsMatch(text2) && UsesKnownLiteral(methodInfo, rule))
				{
					val5 = val;
				}
				if (list.Count == 0 && val4 == null && val5 == null)
				{
					continue;
				}
				try
				{
					harmony.Patch((MethodBase)methodInfo, (list.Count > 0) ? list[0] : null, val4, val5, (HarmonyMethod)null, (HarmonyMethod)null);
					for (int k = 1; k < list.Count; k++)
					{
						harmony.Patch((MethodBase)methodInfo, list[k], (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
					num++;
				}
				catch (Exception ex2)
				{
					Log.LogWarning((object)("Text patch failed " + text2 + ": " + ex2.Message));
				}
			}
		}
		Log.LogInfo((object)(rule.Assembly + " (" + asm.GetName().Name + "): patched " + num + " method(s)."));
	}

	private static string KeyOf(MethodBase m)
	{
		Type declaringType = m.DeclaringType;
		return ((declaringType == null) ? "" : (declaringType.FullName ?? declaringType.Name).Replace('+', '/')) + "::" + m.Name;
	}

	private static void ApplyStatics(Assembly asm, Rule rule)
	{
		int num = 0;
		foreach (string @static in rule.Statics)
		{
			try
			{
				int num2 = @static.LastIndexOf("::", StringComparison.Ordinal);
				Type type = ((num2 > 0) ? asm.GetType(@static.Substring(0, num2).Replace('/', '+'), throwOnError: false) : null);
				FieldInfo fieldInfo = ((type == null) ? null : type.GetField(@static.Substring(num2 + 2), BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
				if (fieldInfo == null)
				{
					Log.LogWarning((object)("Static field not found: " + @static));
					continue;
				}
				object value = fieldInfo.GetValue(null);
				if (value is string s)
				{
					fieldInfo.SetValue(null, TranslateName(s));
					num++;
					continue;
				}
				if (!(value is IList<string> list) || (list.IsReadOnly && !(value is string[])))
				{
					Log.LogWarning((object)("Static field is not text: " + @static));
					continue;
				}
				for (int i = 0; i < list.Count; i++)
				{
					list[i] = TranslateName(list[i]);
				}
				num++;
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Static " + @static + ": " + ex.Message));
			}
		}
		Log.LogInfo((object)(rule.Assembly + ": translated " + num + " static text field(s)."));
	}

	private static bool UsesKnownLiteral(MethodBase m, Rule rule)
	{
		MethodBody methodBody;
		try
		{
			methodBody = m.GetMethodBody();
		}
		catch (Exception)
		{
			return false;
		}
		if (methodBody == null)
		{
			return false;
		}
		byte[] iLAsByteArray = methodBody.GetILAsByteArray();
		if (iLAsByteArray == null)
		{
			return false;
		}
		for (int i = 0; i + 4 < iLAsByteArray.Length; i++)
		{
			if (iLAsByteArray[i] != 114)
			{
				continue;
			}
			int num = BitConverter.ToInt32(iLAsByteArray, i + 1);
			if (num >> 24 != 112)
			{
				continue;
			}
			try
			{
				string key = m.Module.ResolveString(num);
				if (rule.Literals.ContainsKey(key))
				{
					return true;
				}
			}
			catch (Exception)
			{
			}
		}
		return false;
	}

	private static bool FeedsConfig(List<CodeInstruction> list, int index)
	{
		for (int i = index + 1; i < list.Count && i <= index + 14; i++)
		{
			MethodBase methodBase = list[i].operand as MethodBase;
			if (methodBase == null || methodBase.DeclaringType == null)
			{
				continue;
			}
			string name = methodBase.DeclaringType.Name;
			if (methodBase.Name == "Bind" && name == "ConfigFile")
			{
				return true;
			}
			if (methodBase.Name == ".ctor")
			{
				switch (name)
				{
				case "ConfigDefinition":
				case "ConfigDescription":
				case "Row":
					return true;
				}
			}
			if (methodBase.Name == "NewI18N")
			{
				return true;
			}
		}
		return false;
	}

	public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase original)
	{
		List<CodeInstruction> list = new List<CodeInstruction>(instructions);
		if (original == null || !byAssembly.TryGetValue(original.DeclaringType.Assembly.GetName().Name, out var value))
		{
			return list;
		}
		for (int i = 0; i < list.Count; i++)
		{
			if (!(list[i].opcode != OpCodes.Ldstr) && list[i].operand is string key && value.Literals.TryGetValue(key, out var value2) && !FeedsConfig(list, i))
			{
				list[i].operand = value2;
				replaced++;
			}
		}
		return list;
	}

	public static void NamePostfix(ref string __result)
	{
		__result = TranslateName(__result);
	}

	public static void TailPostfix(MethodBase __originalMethod, ref string __result)
	{
		if (__result == null || __originalMethod == null)
		{
			return;
		}
		if (!tailByMethod.TryGetValue(__originalMethod, out var value))
		{
			tailSep.TryGetValue(KeyOf(__originalMethod), out value);
			tailByMethod[__originalMethod] = value;
		}
		if (string.IsNullOrEmpty(value))
		{
			return;
		}
		int num = __result.LastIndexOf(value, StringComparison.Ordinal);
		if (num >= 0)
		{
			string text = __result.Substring(num + value.Length);
			string text2 = TranslateName(text);
			if (text2 != text)
			{
				__result = __result.Substring(0, num + value.Length) + text2;
			}
		}
	}

	public static void ArgPrefix0(ref string __0)
	{
		__0 = TranslateName(__0);
	}

	public static void ArgPrefix1(ref string __1)
	{
		__1 = TranslateName(__1);
	}

	public static void ArgPrefix2(ref string __2)
	{
		__2 = TranslateName(__2);
	}

	public static void ArgPrefix3(ref string __3)
	{
		__3 = TranslateName(__3);
	}

	public static void ArgPrefix4(ref string __4)
	{
		__4 = TranslateName(__4);
	}

	public static void ArgPrefix5(ref string __5)
	{
		__5 = TranslateName(__5);
	}
}

plugins/ReppoTTSHU.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ReppoTTSHU;

[BepInPlugin("ggeery.reppottshu", "ReppoTTSHU", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	public const string GUID = "ggeery.reppottshu";

	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> HungarianChat;

	internal static ConfigEntry<bool> HungarianModSpeech;

	private void Awake()
	{
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		HungarianChat = ((BaseUnityPlugin)this).Config.Bind<bool>("Voice", "HungarianChat", true, "Your chat messages are spoken with Hungarian pronunciation for everyone who has this mod. Start a message with [en] to have it read in English.");
		HungarianModSpeech = ((BaseUnityPlugin)this).Config.Bind<bool>("Voice", "HungarianModSpeech", true, "Speech from mods that do not give a language (for example EnemyTTS monster lines) uses Hungarian pronunciation.");
		try
		{
			Installer.Apply(new Harmony("ggeery.reppottshu"));
			Log.LogInfo((object)"Hungarian TTS pronunciation ready.");
		}
		catch (Exception ex)
		{
			Log.LogError((object)("ReppoTTSHU could not start: " + ex));
		}
	}
}
public static class Installer
{
	public static void Apply(Harmony h)
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Expected O, but got Unknown
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Expected O, but got Unknown
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Expected O, but got Unknown
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Expected O, but got Unknown
		//IL_011a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Expected O, but got Unknown
		Type typeFromHandle = typeof(TTSPronunciation);
		Type typeFromHandle2 = typeof(TTSFormatting);
		h.Patch((MethodBase)Need(typeFromHandle, "SupportedLocaleCodeGet", null), (HarmonyMethod)null, new HarmonyMethod(typeof(Patches), "SupportedPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)Need(typeFromHandle, "BuildLanguages", null), (HarmonyMethod)null, new HarmonyMethod(typeof(Patches), "PronunciationBuilt", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)Need(typeFromHandle2, "BuildLanguages", null), (HarmonyMethod)null, new HarmonyMethod(typeof(Patches), "FormattingBuilt", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)Need(typeFromHandle, "ResolveLocale", null), new HarmonyMethod(typeof(Patches), "ResolvePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		h.Patch((MethodBase)Need(typeof(TTSVoice), "StartSpeakingWithHighlight", new Type[3]
		{
			typeof(string),
			typeof(bool),
			typeof(string)
		}), new HarmonyMethod(typeof(Patches), "SpeakPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		HuLanguage.InjectPronunciation();
		HuLanguage.InjectFormatting(HuLanguage.StaticField(typeFromHandle2).GetValue(null) as IDictionary);
	}

	private static MethodInfo Need(Type t, string name, Type[] args)
	{
		MethodInfo methodInfo = ((args == null) ? AccessTools.Method(t, name, (Type[])null, (Type[])null) : AccessTools.Method(t, name, args, (Type[])null));
		if (methodInfo == null)
		{
			throw new MissingMethodException(t.Name, name);
		}
		return methodInfo;
	}
}
public static class Patches
{
	public static void SupportedPostfix(string localeCode, ref string __result)
	{
		if (__result == null && !string.IsNullOrEmpty(localeCode))
		{
			string text = localeCode.Trim().Replace('_', '-').ToLowerInvariant();
			if (text == "hu" || text.StartsWith("hu-"))
			{
				__result = "hu-HU";
			}
		}
	}

	public static void PronunciationBuilt()
	{
		HuLanguage.InjectPronunciation();
	}

	public static void FormattingBuilt(object __result)
	{
		HuLanguage.InjectFormatting(__result as IDictionary);
	}

	public static void ResolvePrefix(ref string _localeCode)
	{
		if (Plugin.HungarianChat == null || Plugin.HungarianChat.Value)
		{
			_localeCode = "hu-HU";
		}
	}

	public static void SpeakPrefix(ref string text, ref string localeCode)
	{
		if (string.IsNullOrEmpty(localeCode) && (Plugin.HungarianModSpeech == null || Plugin.HungarianModSpeech.Value))
		{
			localeCode = "hu-HU";
		}
		if (HuLanguage.IsHungarian(localeCode))
		{
			text = HuLanguage.PrepareText(text);
		}
	}
}
public static class HuLanguage
{
	public const string Code = "hu";

	public const string Locale = "hu-HU";

	private const BindingFlags Any = BindingFlags.Public | BindingFlags.NonPublic;

	private const string Vowels = "aáeéiíoóöőuúüűyõôûũäàâèêëìîïòøùÿå";

	private const string FrontVowels = "eéiíöőüűõûũäèêëìîïøÿ";

	private static readonly string[][] Rules = new string[83][]
	{
		R("ddzs", "d,dZ"),
		R("dzs", "dZ"),
		R("ccs", "t,tS"),
		R("ssz", "s,s"),
		R("zzs", "Z,Z"),
		R("ggy", "d,d,j"),
		R("nny", "n,n,j"),
		R("tty", "t,t,j"),
		R("lly", "j,j"),
		R("ngy", "n,d,j"),
		R("dz", "d,z"),
		R("cs", "tS"),
		R("sz", "s"),
		R("zs", "Z"),
		R("gy", "d,j"),
		R("ny", "n,j"),
		R("ty", "t,j"),
		R("ly", "j"),
		R("ch", "tS"),
		R("cz", "t,s"),
		R("th", "t"),
		R("ph", "f"),
		R("qu", "k,v"),
		R("nk", "N,k"),
		R("ng", "N,g"),
		R("rr", "r"),
		R("a", "0"),
		R("á", "AA"),
		R("b", "b"),
		R("c", "t,s"),
		R("d", "d"),
		R("e", "e"),
		R("é", "ee"),
		R("f", "f"),
		R("g", "g"),
		R("h", "", 'V', '#'),
		R("h", "h"),
		R("i", "i"),
		R("í", "ii"),
		R("j", "j"),
		R("k", "k"),
		R("l", "l"),
		R("m", "m"),
		R("n", "n"),
		R("o", "o"),
		R("ó", "oo"),
		R("ö", "3"),
		R("ő", "33"),
		R("p", "p"),
		R("q", "k"),
		R("r", "r"),
		R("s", "S"),
		R("t", "t"),
		R("u", "u"),
		R("ú", "uu"),
		R("ü", "I"),
		R("ű", "II"),
		R("v", "v"),
		R("w", "v"),
		R("x", "k,s"),
		R("y", "i"),
		R("z", "z"),
		R("õ", "33"),
		R("ô", "33"),
		R("û", "II"),
		R("ũ", "II"),
		R("ä", "e"),
		R("à", "0"),
		R("â", "0"),
		R("è", "e"),
		R("ê", "e"),
		R("ë", "e"),
		R("ì", "i"),
		R("î", "i"),
		R("ï", "i"),
		R("ò", "o"),
		R("ø", "3"),
		R("ù", "u"),
		R("ÿ", "i"),
		R("ç", "s"),
		R("ñ", "n,j"),
		R("ß", "s"),
		R("å", "o")
	};

	private static readonly string[][] Abbreviations = new string[25][]
	{
		new string[2] { "pl", "például" },
		new string[2] { "stb", "satöbbi" },
		new string[2] { "kb", "körülbelül" },
		new string[2] { "ill", "illetve" },
		new string[2] { "xd", "iksz dé" },
		new string[2] { "ok", "oké" },
		new string[2] { "oks", "oksz" },
		new string[2] { "gg", "gé gé" },
		new string[2] { "thx", "tenksz" },
		new string[2] { "pls", "plíz" },
		new string[2] { "plz", "plíz" },
		new string[2] { "h", "hogy" },
		new string[2] { "v", "vagy" },
		new string[2] { "vmi", "valami" },
		new string[2] { "vki", "valaki" },
		new string[2] { "vhol", "valahol" },
		new string[2] { "sztem", "szerintem" },
		new string[2] { "mrt", "miért" },
		new string[2] { "nm", "nem" },
		new string[2] { "omg", "ó em gé" },
		new string[2] { "brb", "bé er bé" },
		new string[2] { "afk", "á ef ká" },
		new string[2] { "wtf", "vé té ef" },
		new string[2] { "np", "nem probléma" },
		new string[2] { "asap", "ászap" }
	};

	private static readonly Regex SuffixHyphen = new Regex("([\\d%])-(\\p{L})");

	private static readonly string[] Ones = new string[10] { "", "egy", "kettő", "három", "négy", "öt", "hat", "hét", "nyolc", "kilenc" };

	private static readonly string[] OnesJoined = new string[10] { "", "egy", "két", "három", "négy", "öt", "hat", "hét", "nyolc", "kilenc" };

	private static readonly string[] TensAlone = new string[10] { "", "tíz", "húsz", "harminc", "negyven", "ötven", "hatvan", "hetven", "nyolcvan", "kilencven" };

	private static readonly string[] TensJoined = new string[10] { "", "tizen", "huszon", "harminc", "negyven", "ötven", "hatvan", "hetven", "nyolcvan", "kilencven" };

	private static readonly string[] Letters = new string[26]
	{
		"á", "bé", "cé", "dé", "e", "ef", "gé", "há", "i", "jé",
		"ká", "el", "em", "en", "ó", "pé", "kú", "er", "es", "té",
		"ú", "vé", "duplavé", "iksz", "ipszilon", "zé"
	};

	private static readonly string[] Months = new string[12]
	{
		"január", "február", "március", "április", "május", "június", "július", "augusztus", "szeptember", "október",
		"november", "december"
	};

	private static readonly string[] Days = new string[31]
	{
		"elseje", "másodika", "harmadika", "negyedike", "ötödike", "hatodika", "hetedike", "nyolcadika", "kilencedike", "tizedike",
		"tizenegyedike", "tizenkettedike", "tizenharmadika", "tizennegyedike", "tizenötödike", "tizenhatodika", "tizenhetedike", "tizennyolcadika", "tizenkilencedike", "huszadika",
		"huszonegyedike", "huszonkettedike", "huszonharmadika", "huszonnegyedike", "huszonötödike", "huszonhatodika", "huszonhetedike", "huszonnyolcadika", "huszonkilencedike", "harmincadika",
		"harmincegyedike"
	};

	private static readonly string[][] Terms = new string[21][]
	{
		new string[2] { "minus", "mínusz" },
		new string[2] { "plus", "plusz" },
		new string[2] { "decimal", "egész" },
		new string[2] { "percent", "százalék" },
		new string[2] { "to", "" },
		new string[2] { "over", "per" },
		new string[2] { "slash", "per" },
		new string[2] { "colon", "kettőspont" },
		new string[2] { "dot", "pont" },
		new string[2] { "at", "kukac" },
		new string[2] { "equals", "egyenlő" },
		new string[2] { "and", "és" },
		new string[2] { "times", "szorozva" },
		new string[2] { "divided", "osztva" },
		new string[2] { "less", "kisebb mint" },
		new string[2] { "greater", "nagyobb mint" },
		new string[2] { "number", "szám" },
		new string[2] { "link", "link" },
		new string[2] { "email", "ímél" },
		new string[2] { "degree", "fok" },
		new string[2] { "underscore", "alulvonás" }
	};

	private static readonly string[][] Measures = new string[35][]
	{
		new string[2] { "kg", "kilogramm" },
		new string[2] { "g", "gramm" },
		new string[2] { "km", "kilométer" },
		new string[2] { "m", "méter" },
		new string[2] { "cm", "centiméter" },
		new string[2] { "mm", "milliméter" },
		new string[2] { "L", "liter" },
		new string[2] { "ml", "milliliter" },
		new string[2] { "°C", "celziuszfok" },
		new string[2] { "°F", "fárenhájtfok" },
		new string[2] { "h", "óra" },
		new string[2] { "min", "perc" },
		new string[2] { "s", "másodperc" },
		new string[2] { "day", "nap" },
		new string[2] { "month", "hónap" },
		new string[2] { "year", "év" },
		new string[2] { "%", "százalék" },
		new string[2] { "‰", "ezrelék" },
		new string[2] { "°", "fok" },
		new string[2] { "ms", "ezredmásodperc" },
		new string[2] { "USD", "amerikai dollár" },
		new string[2] { "EUR", "euró" },
		new string[2] { "GBP", "angol font" },
		new string[2] { "JPY", "japán jen" },
		new string[2] { "CNY", "kínai jüan" },
		new string[2] { "SEK", "svéd korona" },
		new string[2] { "DKK", "dán korona" },
		new string[2] { "NOK", "norvég korona" },
		new string[2] { "PLN", "lengyel zloti" },
		new string[2] { "RUB", "orosz rubel" },
		new string[2] { "UAH", "ukrán hrivnya" },
		new string[2] { "TRY", "török líra" },
		new string[2] { "KRW", "dél-koreai von" },
		new string[2] { "THB", "thai bát" },
		new string[2] { "BRL", "brazil reál" }
	};

	private static readonly string[][] AbbreviationsDotted = new string[8][]
	{
		new string[2] { "Dr.", "doktor" },
		new string[2] { "pl.", "például" },
		new string[2] { "stb.", "satöbbi" },
		new string[2] { "kb.", "körülbelül" },
		new string[2] { "ill.", "illetve" },
		new string[2] { "ún.", "úgynevezett" },
		new string[2] { "db.", "darab" },
		new string[2] { "u.", "utca" }
	};

	private static string[] R(string letters, string phonemes)
	{
		return new string[4] { letters, phonemes, " ", " " };
	}

	private static string[] R(string letters, string phonemes, char before, char after)
	{
		return new string[4]
		{
			letters,
			phonemes,
			before.ToString(),
			after.ToString()
		};
	}

	public static FieldInfo StaticField(Type t)
	{
		return t.GetField("languages", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
	}

	public static bool IsHungarian(string locale)
	{
		if (locale != null && locale.Length >= 2 && string.Compare(locale, 0, "hu", 0, 2, StringComparison.OrdinalIgnoreCase) == 0)
		{
			if (locale.Length != 2 && locale[2] != '-')
			{
				return locale[2] == '_';
			}
			return true;
		}
		return false;
	}

	public static string PrepareText(string text)
	{
		if (string.IsNullOrEmpty(text) || text.IndexOf('-') < 0)
		{
			return text;
		}
		return SuffixHyphen.Replace(text, "$1 $2");
	}

	public static void InjectPronunciation()
	{
		if (StaticField(typeof(TTSPronunciation)).GetValue(null) is IDictionary dictionary && !dictionary.Contains("hu"))
		{
			object set = (dictionary["hu"] = BuildRuleSet());
			FillAbbreviations(set);
		}
	}

	private static object BuildRuleSet()
	{
		Type typeFromHandle = typeof(TTSPronunciation);
		Type nestedType = typeFromHandle.GetNestedType("LanguageRuleSet", BindingFlags.Public | BindingFlags.NonPublic);
		Type nestedType2 = typeFromHandle.GetNestedType("PhonemeRule", BindingFlags.Public | BindingFlags.NonPublic);
		Type nestedType3 = typeFromHandle.GetNestedType("StressRule", BindingFlags.Public | BindingFlags.NonPublic);
		object obj = Activator.CreateInstance(nestedType);
		Array array = Array.CreateInstance(nestedType2, Rules.Length);
		for (int i = 0; i < Rules.Length; i++)
		{
			string[] array2 = Rules[i];
			array.SetValue(Activator.CreateInstance(nestedType2, array2[0], array2[1], array2[2][0], array2[3][0]), i);
		}
		nestedType.GetField("rules").SetValue(obj, array);
		nestedType.GetField("vowels").SetValue(obj, "aáeéiíoóöőuúüűyõôûũäàâèêëìîïòøùÿå");
		nestedType.GetField("frontVowels").SetValue(obj, "eéiíöőüűõûũäèêëìîïøÿ");
		nestedType.GetField("wordExceptions").SetValue(obj, new Dictionary<string, string>());
		nestedType.GetField("numberWords").SetValue(obj, new Func<int, List<string>>(NumberWords));
		nestedType.GetField("stress").SetValue(obj, Enum.ToObject(nestedType3, 1));
		nestedType.GetField("reduceUnstressedO").SetValue(obj, false);
		return obj;
	}

	private static void FillAbbreviations(object set)
	{
		try
		{
			MethodInfo method = typeof(TTSPronunciation).GetMethod("WordPhonemes", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			Dictionary<string, string> dictionary = (Dictionary<string, string>)set.GetType().GetField("wordExceptions").GetValue(set);
			Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
			string[][] abbreviations = Abbreviations;
			foreach (string[] array in abbreviations)
			{
				StringBuilder stringBuilder = new StringBuilder();
				string[] array2 = array[1].Split(' ');
				foreach (string text in array2)
				{
					string value = (string)method.Invoke(null, new object[2] { text, set });
					if (string.IsNullOrEmpty(value))
					{
						stringBuilder.Length = 0;
						break;
					}
					if (stringBuilder.Length > 0)
					{
						stringBuilder.Append(' ');
					}
					stringBuilder.Append(value);
				}
				if (stringBuilder.Length > 0)
				{
					dictionary2[array[0]] = stringBuilder.ToString();
				}
			}
			foreach (KeyValuePair<string, string> item in dictionary2)
			{
				dictionary[item.Key] = item.Value;
			}
		}
		catch (Exception ex)
		{
			if (Plugin.Log != null)
			{
				Plugin.Log.LogWarning((object)("Abbreviation readings skipped: " + ex.Message));
			}
		}
	}

	private static string Below1000(int n, bool joined)
	{
		StringBuilder stringBuilder = new StringBuilder();
		int num = n / 100;
		int num2 = n % 100 / 10;
		int num3 = n % 10;
		if (num > 0)
		{
			if (num > 1)
			{
				stringBuilder.Append(OnesJoined[num]);
			}
			stringBuilder.Append("száz");
		}
		if (num2 > 0)
		{
			stringBuilder.Append((num3 == 0) ? TensAlone[num2] : TensJoined[num2]);
		}
		if (num3 > 0)
		{
			stringBuilder.Append(joined ? OnesJoined[num3] : Ones[num3]);
		}
		return stringBuilder.ToString();
	}

	public static List<string> NumberWords(int value)
	{
		List<string> list = new List<string>();
		long num = value;
		if (num < 0)
		{
			list.Add("mínusz");
			num = -num;
		}
		if (num == 0)
		{
			list.Add("nulla");
			return list;
		}
		long[] array = new long[3] { 1000000000L, 1000000L, 1000L };
		string[] array2 = new string[3] { "milliárd", "millió", "ezer" };
		for (int i = 0; i < array.Length; i++)
		{
			int num2 = (int)(num / array[i]);
			num %= array[i];
			if (num2 != 0)
			{
				list.Add(((num2 == 1 && i == 2) ? "" : Below1000(num2, joined: true)) + array2[i]);
			}
		}
		if (num > 0)
		{
			list.Add(Below1000((int)num, joined: false));
		}
		return list;
	}

	public static void InjectFormatting(IDictionary dict)
	{
		if (dict == null || dict.Contains("hu") || !dict.Contains("en"))
		{
			return;
		}
		object obj = dict["en"];
		Type type = obj.GetType();
		object obj2 = Activator.CreateInstance(type);
		type.GetField("code").SetValue(obj2, "hu");
		type.GetField("decimalMark").SetValue(obj2, ',');
		type.GetField("groupMark").SetValue(obj2, ' ');
		type.GetField("letters").SetValue(obj2, Letters.Clone());
		type.GetField("datePattern").SetValue(obj2, "y. MMMM d.");
		type.GetField("months").SetValue(obj2, Months.Clone());
		type.GetField("days").SetValue(obj2, Days.Clone());
		Dictionary<string, string> dictionary = new Dictionary<string, string>((Dictionary<string, string>)type.GetField("terms").GetValue(obj));
		string[][] terms = Terms;
		foreach (string[] array in terms)
		{
			dictionary[array[0]] = array[1];
		}
		type.GetField("terms").SetValue(obj2, dictionary);
		type.GetField("readings").SetValue(obj2, new Dictionary<string, string>());
		Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
		string[][] abbreviationsDotted = AbbreviationsDotted;
		foreach (string[] array2 in abbreviationsDotted)
		{
			dictionary2[array2[0]] = array2[1];
		}
		type.GetField("abbreviations").SetValue(obj2, dictionary2);
		Dictionary<string, Dictionary<string, string>> dictionary3 = (Dictionary<string, Dictionary<string, string>>)type.GetField("measures").GetValue(obj);
		Dictionary<string, Dictionary<string, string>> dictionary4 = new Dictionary<string, Dictionary<string, string>>();
		foreach (KeyValuePair<string, Dictionary<string, string>> item in dictionary3)
		{
			dictionary4[item.Key] = new Dictionary<string, string>(item.Value);
		}
		string[][] measures = Measures;
		foreach (string[] array3 in measures)
		{
			if (!dictionary4.TryGetValue(array3[0], out var value))
			{
				value = new Dictionary<string, string>();
				dictionary4[array3[0]] = value;
			}
			value["one"] = "{0} " + array3[1];
			value["other"] = "{0} " + array3[1];
		}
		type.GetField("measures").SetValue(obj2, dictionary4);
		dict["hu"] = obj2;
	}
}