/// <summary>
        ///  Loads and decrypts the KIFINT archive entries using the V_CODE2.<para/>
        ///  Using this will initialize with the specified KIFINT archive type.
        /// </summary>
        /// <param name="kifintPath">The path to the KIFINT archive to decrypt.</param>
        /// <param name="type">The type of archive to create.</param>
        /// <param name="vcode2">The V_CODE2 key obtained from the exe, used to decrypt the file names.</param>
        /// <param name="callback">The optional callback for progress made during loading.</param>
        /// <returns>The <see cref="KifintArchive"/> with all of the loaded entries.</returns>
        ///
        /// <exception cref="ArgumentNullException">
        ///  <paramref name="kifintPath"/> or <paramref name="vcode2"/> is null.
        /// </exception>
        public static KifintArchive LoadArchive(string kifintPath, KifintType type, string vcode2,
                                                KifintProgressCallback callback = null)
        {
            if (kifintPath == null)
            {
                throw new ArgumentNullException(nameof(kifintPath));
            }
            if (vcode2 == null)
            {
                throw new ArgumentNullException(nameof(vcode2));
            }
            KifintArchive      archive;
            KifintProgressArgs progress = new KifintProgressArgs {
                ArchiveType  = type,
                ArchiveIndex = 0,
                ArchiveCount = 1,
            };

            progress.ArchiveName = Path.GetFileName(kifintPath);
            using (Stream stream = File.OpenRead(kifintPath))
                archive = LoadLookup(type, stream, kifintPath, vcode2, progress, callback);
            progress.ArchiveIndex++;

            progress.EntryName  = null;
            progress.EntryIndex = 0;
            progress.EntryCount = 0;
            callback?.Invoke(progress);
            return(archive);
        }
        /*public static KifintLookupCollection DecryptLookups(KifintType type, string installDir, string vcode2,
         *      KifintProgressCallback callback = null)
         * {
         *
         * }*/

        #endregion

        #region DecryptArchive

        public static void DecryptArchives(string wildcard, string installDir, string vcode2,
                                           KifintProgressCallback callback = null)
        {
            if (vcode2 == null)
            {
                throw new ArgumentNullException(nameof(vcode2));
            }
            KifintType type = KifintType.Unknown;

            string[]           files    = Directory.GetFiles(installDir, wildcard);
            KifintProgressArgs progress = new KifintProgressArgs {
                ArchiveType  = type,
                ArchiveIndex = 0,
                ArchiveCount = files.Length,
            };

            foreach (string kifintPath in files)
            {
                progress.ArchiveName = Path.GetFileName(kifintPath);
                string kifintBackup = Path.Combine(Path.GetDirectoryName(installDir) + "intbackups");
                using (Stream stream = File.OpenRead(kifintPath))
                    DecryptArchive(stream, kifintPath, kifintBackup, vcode2, false, progress, callback);
                progress.ArchiveIndex++;
            }
            progress.EntryName  = null;
            progress.EntryIndex = 0;
            progress.EntryCount = 0;
            callback?.Invoke(progress);
        }
        /// <summary>
        ///  Decrypts the KIFINT archives using the wildcard search, install directory, and name of executable with the
        ///  V_CODE2 used to decrypt.<para/>
        ///  Using this will initialize with <see cref="KifintType.Unknown"/>.
        /// </summary>
        /// <param name="wildcard">The wildcard name of the files to look for and merge.</param>
        /// <param name="installDir">The installation directory for both the archives and executable.</param>
        /// <param name="vcode2">The V_CODE2 key obtained from the exe, used to decrypt the file names.</param>
        /// <param name="callback">The optional callback for progress made during decryption.</param>
        /// <returns>The <see cref="KifintLookup"/> merged with all loaded archives.</returns>
        ///
        /// <exception cref="ArgumentNullException">
        ///  <paramref name="wildcard"/>, <paramref name="installDir"/>, or <paramref name="vcode2"/> is null.
        /// </exception>
        public static KifintLookup LoadLookup(string wildcard, string installDir, string vcode2,
                                              KifintProgressCallback callback = null)
        {
            if (vcode2 == null)
            {
                throw new ArgumentNullException(nameof(vcode2));
            }
            KifintType   type   = KifintType.Unknown;
            KifintLookup lookup = new KifintLookup(type);

            string[]           files    = Directory.GetFiles(installDir, wildcard);
            KifintProgressArgs progress = new KifintProgressArgs {
                ArchiveType  = type,
                ArchiveIndex = 0,
                ArchiveCount = files.Length,
            };

            foreach (string kifintPath in files)
            {
                progress.ArchiveName = Path.GetFileName(kifintPath);
                using (Stream stream = File.OpenRead(kifintPath))
                    lookup.Merge(LoadLookup(type, stream, kifintPath, vcode2, progress, callback));
                progress.ArchiveIndex++;
            }
            progress.EntryName  = null;
            progress.EntryIndex = 0;
            progress.EntryCount = 0;
            callback?.Invoke(progress);
            return(lookup);
        }
        /// <summary>
        ///  Decrypts the KIFINT archives using the known archive type, install directory, and name of executable with
        ///  the V_CODE2 used to decrypt.
        /// </summary>
        /// <param name="type">The type of archive to look for and decrypt.</param>
        /// <param name="installDir">The installation directory for both the archives and executable.</param>
        /// <param name="vcode2">The V_CODE2 key obtained from the exe, used to decrypt the file names.</param>
        /// <param name="callback">The optional callback for progress made during decryption.</param>
        /// <returns>The <see cref="KifintLookup"/> merged with all loaded archives.</returns>
        ///
        /// <exception cref="ArgumentNullException">
        ///  <paramref name="installDir"/> or <paramref name="vcode2"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///  <paramref name="type"/> is <see cref="KifintType.Unknown"/>.
        /// </exception>
        public static KifintLookup LoadLookup(KifintType type, string installDir, string vcode2,
                                              KifintProgressCallback callback = null)
        {
            if (vcode2 == null)
            {
                throw new ArgumentNullException(nameof(vcode2));
            }
            if (type == KifintType.Unknown)
            {
                throw new ArgumentException($"{nameof(type)} cannot be {nameof(KifintType.Unknown)}!", nameof(type));
            }
            KifintLookup lookup       = new KifintLookup(type);
            var          files        = Enumerable.Empty <string>();
            var          wildcardAttr = EnumInfo.GetAttribute <KifintType, KifintWildcardAttribute>(type);

            foreach (string wildcard in wildcardAttr.Wildcards)
            {
                files = files.Concat(Directory.GetFiles(installDir, wildcard));
            }
            //string wildcard = EnumInfo.GetAttribute<KifintType, KifintWildcardAttribute>(type).Wildcard;
            //string[] files = Directory.GetFiles(installDir, wildcard);
            KifintProgressArgs progress = new KifintProgressArgs {
                ArchiveType  = type,
                ArchiveIndex = 0,
                ArchiveCount = files.Count(),
            };

            foreach (string kifintPath in files)
            {
                progress.ArchiveName = Path.GetFileName(kifintPath);
                using (Stream stream = File.OpenRead(kifintPath))
                    lookup.Merge(LoadLookup(type, stream, kifintPath, vcode2, progress, callback));
                progress.ArchiveIndex++;
            }
            progress.EntryName  = null;
            progress.EntryIndex = 0;
            progress.EntryCount = 0;
            callback?.Invoke(progress);
            return(lookup);
        }
        /// <summary>
        ///  Decrypts the KIFINT archives using the known archive type, install directory, and name of executable with
        ///  the V_CODE2 used to decrypt.
        /// </summary>
        /// <param name="type">The type of archive to look for and decrypt.</param>
        /// <param name="stream">The stream to the open KIFINT archive.</param>
        /// <param name="installDir">The installation directory for both the archives and executable.</param>
        /// <param name="exePath">The path to the executable to extract the V_CODE2 key from.</param>
        /// <returns>The <see cref="KifintLookup"/> merged with all loaded archives.</returns>
        ///
        /// <exception cref="ArgumentNullException">
        ///  <paramref name="stream"/>, <paramref name="kifintPath"/>, or <paramref name="exePath"/> is null.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        ///  The <paramref name="stream"/> is closed.
        /// </exception>
        private static KifintArchive LoadLookup(KifintType type, Stream stream, string kifintPath, string vcode2,
                                                KifintProgressArgs progress, KifintProgressCallback callback)
        {
            if (kifintPath == null)
            {
                throw new ArgumentNullException(nameof(kifintPath));
            }
            if (vcode2 == null)
            {
                throw new ArgumentNullException(nameof(vcode2));
            }

            BinaryReader reader = new BinaryReader(stream);
            KIFHDR       hdr    = reader.ReadUnmanaged <KIFHDR>();

            UnexpectedFileTypeException.ThrowIfInvalid(hdr.Signature, KIFHDR.ExpectedSignature);

            KIFENTRY[] entries = reader.ReadUnmanagedArray <KIFENTRY>(hdr.EntryCount);

            progress.EntryName  = null;
            progress.EntryIndex = 0;
            progress.EntryCount = entries.Length;

            // Table of contents seed
            uint     tocSeed      = GenerateTocSeed(vcode2);
            uint     fileKey      = 0;
            int      fileKeyIndex = -1;
            Blowfish blowfish     = null;

            // Obtain the decryption file key if one exists
            for (int i = 0; i < hdr.EntryCount; i++)
            {
                if (entries[i].FileName == KeyFileName)
                {
                    fileKey      = MersenneTwister.GenRand(entries[i].Length);
                    blowfish     = CatDebug.NewBlowfish(fileKey);
                    fileKeyIndex = i;
                    break;
                }
            }

            const int ProgressThreshold = 500;

            // Decrypt the KIFINT entries using the file key
            if (fileKeyIndex != -1)
            {
                for (uint i = 0; i < hdr.EntryCount; i++, progress.EntryIndex++)
                {
                    if (unchecked ((int)i) == fileKeyIndex)
                    {
                        continue;
                    }

                    // Give the entry the correct name
                    UnobfuscateFileName(entries[i].FileNameRaw, unchecked (tocSeed + i));
                    // Apply the extra offset before decryption
                    entries[i].Offset += i;
                    // Decrypt the entry's offset and length
                    blowfish.Decrypt(ref entries[i].Info);

                    progress.EntryName = entries[i].FileName;
                    if (i % ProgressThreshold == 0 || i + 1 == hdr.EntryCount)
                    {
                        callback?.Invoke(progress);
                    }
                }
            }

            return(new KifintArchive(kifintPath, entries, fileKeyIndex != -1, fileKey, type, blowfish));
        }
        private static void DecryptArchiveSave(KIFHDR hdr, List <KIFENTRY> entries, uint tocSeed, uint fileKey,
                                               Blowfish blowfish, int keyIndex, Stream inStream, Stream outStream, KifintProgressArgs progress,
                                               KifintProgressCallback callback)
        {
            BinaryReader reader = new BinaryReader(inStream);
            BinaryWriter writer = new BinaryWriter(outStream);

            const int ProgressThreshold = 1;

            progress.EntryName  = null;
            progress.EntryIndex = 0;
            progress.EntryCount = entries.Count;

            // Decrypt the KIFINT entries using the file key
            for (uint i = 0; i < hdr.EntryCount; i++, progress.EntryIndex++)
            {
                if (unchecked ((int)i) == keyIndex)
                {
                    continue;
                }

                KIFENTRY entry = entries[unchecked ((int)i)];

                // Give the entry the correct name
                UnobfuscateFileName(entry.FileNameRaw, unchecked (tocSeed + i));
                // Apply the extra offset to be decrypted
                entry.Offset += i;
                // Decrypt the entry's length and offset
                blowfish.Decrypt(ref entry.Info);

                progress.EntryName = entry.FileName;
                if (i % ProgressThreshold == 0 || i + 1 == hdr.EntryCount)
                {
                    callback?.Invoke(progress);
                }

                // Goto the entry's decrypted offset, read the buffer, then decrypt it
                inStream.Position = entry.Offset;
                byte[] buffer = reader.ReadBytes(entry.Length);
                blowfish.Decrypt(buffer, entry.Length & ~7);

                // Move to the entry's offset in the output stream and write the buffer
                outStream.Position = entry.Offset;
                writer.Write(buffer);

                // Make sure to reassign the entry to the list, because
                // it's not an array and does not return struct references.
                entries[unchecked ((int)i)] = entry;
            }

            entries.RemoveAt(keyIndex);
            hdr.EntryCount--;

            outStream.Position = 0;
            writer.WriteUnmanaged(hdr);
            writer.WriteUnmanagedArray(entries);
        }
        private static bool DecryptArchive(Stream inStream, string kifintPath, string kifintBackup, string vcode2, bool isBackup,
                                           KifintProgressArgs progress, KifintProgressCallback callback)
        {
            if (kifintPath == null)
            {
                throw new ArgumentNullException(nameof(kifintPath));
            }
            if (vcode2 == null)
            {
                throw new ArgumentNullException(nameof(vcode2));
            }

            /*const string BackupName = "intbackup";
             * string dir = Path.GetDirectoryName(kifintPath);
             * string name = Path.GetFileName(kifintPath);
             * string kifintBackup = Path.Combine(dir, BackupName, name);
             * bool isBackup = Path.GetFileName(dir).ToLower() == BackupName;
             * if (isBackup) {
             *      dir = Path.GetDirectoryName(dir);
             *      kifintPath = Path.Combine(dir, name);
             * }
             * else {
             *
             * }*/
            Directory.CreateDirectory(Path.GetDirectoryName(kifintBackup));

            BinaryReader reader = new BinaryReader(inStream);
            KIFHDR       hdr    = reader.ReadUnmanaged <KIFHDR>();

            try {
                UnexpectedFileTypeException.ThrowIfInvalid(hdr.Signature, KIFHDR.ExpectedSignature);
            } catch (UnexpectedFileTypeException) {
                if (!isBackup && File.Exists(kifintBackup))
                {
                    inStream.Close();
                    // We must have stopped while decrypting an archive. Let's restart from the already-made backup
                    using (inStream = File.OpenRead(kifintBackup))
                        DecryptArchive(inStream, kifintPath, kifintBackup, vcode2, true, progress, callback);
                    return(true);
                }
                throw;
            }

            List <KIFENTRY> entries = new List <KIFENTRY>(hdr.EntryCount);

            entries.AddRange(reader.ReadUnmanagedArray <KIFENTRY>(hdr.EntryCount));

            // Table of contents seed
            uint     tocSeed  = GenerateTocSeed(vcode2);
            uint     fileKey  = 0;
            bool     decrypt  = false;
            Blowfish blowfish = null;
            int      keyIndex = -1;

            // Obtain the decryption file key if one exists
            for (int i = 0; i < hdr.EntryCount; i++)
            {
                if (entries[i].FileName == KeyFileName)
                {
                    fileKey  = MersenneTwister.GenRand(entries[i].Length);
                    decrypt  = true;
                    blowfish = CatDebug.NewBlowfish(fileKey);
                    keyIndex = i;
                    break;
                }
            }

            // This archive is already decrypted, return and let the calling method know
            if (!decrypt)
            {
                return(false);
            }

            if (isBackup)
            {
                using (Stream outStream = File.Create(kifintPath))
                    DecryptArchiveSave(hdr, entries, tocSeed, fileKey, blowfish, keyIndex, inStream, outStream,
                                       progress, callback);
            }
            else
            {
                if (File.Exists(kifintBackup))
                {
                    File.Delete(kifintBackup);
                }
                inStream.Close();
                File.Move(kifintPath, kifintBackup);
                using (inStream = File.OpenRead(kifintBackup))
                    using (Stream outStream = File.Create(kifintPath))
                        DecryptArchiveSave(hdr, entries, tocSeed, fileKey, blowfish, keyIndex, inStream, outStream,
                                           progress, callback);
            }

            return(true);
        }