/// <summary>
        ///   Terminates the program gracefully
        /// </summary>
        /// <param name="exitCode">Optional exit code</param>
        /// <param name="exit">Whether to actually exit or just perform cleanup tasks</param>
        internal static void Exit(int exitCode = 0, bool exit = true)
        {
            try {
                Log.WriteLine(LogLevel.Warning, $"exiting with code 0x{exitCode:x8}");

                DesktopKeyboardHook?.Dispose();
                DesktopMouseHook?.Dispose();
                TrayIcon?.Hide();
                Options?.Save();
                HudManager?.Dispose();
                UpdateManager?.Dispose();

#if DEBUG
                Log.WriteLine(LogLevel.Warning, ObjectTracker.ReportActiveObjects());
#endif

                loggerStream.Dispose();
                Log.Streams.Clear();

                GC.WaitForPendingFinalizers();
            } catch (Exception exception) {
                // try to log exceptions
                if (Log.Streams?.Count > 0 && Log.Streams.All(s => s.CanWrite))
                {
                    Log.WriteLine(LogLevel.Error, $"exception caught: {exception}");
                }
            } finally {
                if (exit)
                {
                    Environment.ExitCode = exitCode;
                    System.Windows.Forms.Application.Exit();
                }
            }
        }