using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml.Serialization; using SabreTools.Core; using SabreTools.FileTypes; using SabreTools.Filtering; using SabreTools.IO; using SabreTools.Logging; using SabreTools.Library.DatItems; using SabreTools.Library.Reports; using SabreTools.Skippers; using NaturalSort; using Newtonsoft.Json; namespace SabreTools.Library.DatFiles { /// /// Represents a format-agnostic DAT /// [JsonObject("datfile"), XmlRoot("datfile")] public abstract class DatFile { #region Fields /// /// Header values /// [JsonProperty("header"), XmlElement("header")] public DatHeader Header { get; set; } = new DatHeader(); /// /// DatItems and related statistics /// [JsonProperty("items"), XmlElement("items")] public ItemDictionary Items { get; set; } = new ItemDictionary(); #endregion #region Logging /// /// Logging object /// [JsonIgnore, XmlIgnore] protected Logger logger; #endregion #region Constructors /// /// Create a new DatFile from an existing one /// /// DatFile to get the values from public DatFile(DatFile datFile) { logger = new Logger(this); if (datFile != null) { Header = datFile.Header; Items = datFile.Items; } } /// /// Create a specific type of DatFile to be used based on a format and a base DAT /// /// Format of the DAT to be created /// DatFile containing the information to use in specific operations /// For relevant types, assume the usage of quotes /// DatFile of the specific internal type that corresponds to the inputs public static DatFile Create(DatFormat? datFormat = null, DatFile baseDat = null, bool quotes = true) { switch (datFormat) { case DatFormat.AttractMode: return new AttractMode(baseDat); case DatFormat.ClrMamePro: return new ClrMamePro(baseDat, quotes); case DatFormat.CSV: return new SeparatedValue(baseDat, ','); case DatFormat.DOSCenter: return new DosCenter(baseDat); case DatFormat.EverdriveSMDB: return new EverdriveSMDB(baseDat); case DatFormat.Listrom: return new Listrom(baseDat); case DatFormat.Listxml: return new Listxml(baseDat); case DatFormat.Logiqx: return new Logiqx(baseDat, false); case DatFormat.LogiqxDeprecated: return new Logiqx(baseDat, true); case DatFormat.MissFile: return new Missfile(baseDat); case DatFormat.OfflineList: return new OfflineList(baseDat); case DatFormat.OpenMSX: return new OpenMSX(baseDat); case DatFormat.RedumpMD5: return new Hashfile(baseDat, Hash.MD5); #if NET_FRAMEWORK case DatFormat.RedumpRIPEMD160: return new Hashfile(baseDat, Hash.RIPEMD160); #endif case DatFormat.RedumpSFV: return new Hashfile(baseDat, Hash.CRC); case DatFormat.RedumpSHA1: return new Hashfile(baseDat, Hash.SHA1); case DatFormat.RedumpSHA256: return new Hashfile(baseDat, Hash.SHA256); case DatFormat.RedumpSHA384: return new Hashfile(baseDat, Hash.SHA384); case DatFormat.RedumpSHA512: return new Hashfile(baseDat, Hash.SHA512); case DatFormat.RedumpSpamSum: return new Hashfile(baseDat, Hash.SpamSum); case DatFormat.RomCenter: return new RomCenter(baseDat); case DatFormat.SabreJSON: return new SabreJSON(baseDat); case DatFormat.SabreXML: return new SabreXML(baseDat); case DatFormat.SoftwareList: return new SoftwareList(baseDat); case DatFormat.SSV: return new SeparatedValue(baseDat, ';'); case DatFormat.TSV: return new SeparatedValue(baseDat, '\t'); // We use new-style Logiqx as a backup for generic DatFile case null: default: return new Logiqx(baseDat, false); } } /// /// Create a new DatFile from an existing DatHeader /// /// DatHeader to get the values from public static DatFile Create(DatHeader datHeader) { DatFile datFile = Create(datHeader.DatFormat); datFile.Header = (DatHeader)datHeader.Clone(); return datFile; } /// /// Add items from another DatFile to the existing DatFile /// /// DatFile to add from /// If items should be deleted from the source DatFile public void AddFromExisting(DatFile datFile, bool delete = false) { // Get the list of keys from the DAT var keys = datFile.Items.Keys.ToList(); foreach (string key in keys) { // Add everything from the key to the internal DAT Items.AddRange(key, datFile.Items[key]); // Now remove the key from the source DAT if (delete) datFile.Items.Remove(key); } // Now remove the file dictionary from the source DAT if (delete) datFile.Items = null; } /// /// Apply a DatHeader to an existing DatFile /// /// DatHeader to get the values from public void ApplyDatHeader(DatHeader datHeader) { Header.ConditionalCopy(datHeader); } /// /// Fill the header values based on existing Header and path /// /// Path used for creating a name, if necessary /// True if the date should be omitted from name and description, false otherwise public void FillHeaderFromPath(string path, bool bare) { // If the description is defined but not the name, set the name from the description if (string.IsNullOrWhiteSpace(Header.Name) && !string.IsNullOrWhiteSpace(Header.Description)) { Header.Name = Header.Description; } // If the name is defined but not the description, set the description from the name else if (!string.IsNullOrWhiteSpace(Header.Name) && string.IsNullOrWhiteSpace(Header.Description)) { Header.Description = Header.Name + (bare ? string.Empty : $" ({Header.Date})"); } // If neither the name or description are defined, set them from the automatic values else if (string.IsNullOrWhiteSpace(Header.Name) && string.IsNullOrWhiteSpace(Header.Description)) { string[] splitpath = path.TrimEnd(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar); Header.Name = splitpath.Last(); Header.Description = Header.Name + (bare ? string.Empty : $" ({Header.Date})"); } } #endregion #region Converting and Updating /// /// Replace item values from the base set represented by the current DAT /// /// DatFile to replace the values in /// List of Fields representing what should be updated /// True if descriptions should only be replaced if the game name is the same, false otherwise public void BaseReplace(DatFile intDat, List updateFields, bool onlySame) { logger.User($"Replacing items in '{intDat.Header.FileName}' from the base DAT"); // If we are matching based on DatItem fields of any sort if (updateFields.Intersect(DatItem.DatItemFields).Any()) { // For comparison's sake, we want to use CRC as the base bucketing Items.BucketBy(Field.DatItem_CRC, DedupeType.Full); intDat.Items.BucketBy(Field.DatItem_CRC, DedupeType.None); // Then we do a hashwise comparison against the base DAT Parallel.ForEach(intDat.Items.Keys, Globals.ParallelOptions, key => { List datItems = intDat.Items[key]; List newDatItems = new List(); foreach (DatItem datItem in datItems) { List dupes = Items.GetDuplicates(datItem, sorted: true); DatItem newDatItem = datItem.Clone() as DatItem; // Replace fields from the first duplicate, if we have one if (dupes.Count > 0) newDatItem.ReplaceFields(dupes.First(), updateFields); newDatItems.Add(newDatItem); } // Now add the new list to the key intDat.Items.Remove(key); intDat.Items.AddRange(key, newDatItems); }); } // If we are matching based on Machine fields of any sort if (updateFields.Intersect(DatItem.MachineFields).Any()) { // For comparison's sake, we want to use Machine Name as the base bucketing Items.BucketBy(Field.Machine_Name, DedupeType.Full); intDat.Items.BucketBy(Field.Machine_Name, DedupeType.None); // Then we do a namewise comparison against the base DAT Parallel.ForEach(intDat.Items.Keys, Globals.ParallelOptions, key => { List datItems = intDat.Items[key]; List newDatItems = new List(); foreach (DatItem datItem in datItems) { DatItem newDatItem = datItem.Clone() as DatItem; if (Items.ContainsKey(key) && Items[key].Count() > 0) newDatItem.Machine.ReplaceFields(Items[key][0].Machine, updateFields, onlySame); newDatItems.Add(newDatItem); } // Now add the new list to the key intDat.Items.Remove(key); intDat.Items.AddRange(key, newDatItems); }); } } /// /// Output diffs against a base set represented by the current DAT /// /// DatFile to replace the values in /// True to diff using games, false to use hashes public void DiffAgainst(DatFile intDat, bool useGames) { // For comparison's sake, we want to use a base ordering if (useGames) Items.BucketBy(Field.Machine_Name, DedupeType.None); else Items.BucketBy(Field.DatItem_CRC, DedupeType.None); logger.User($"Comparing '{intDat.Header.FileName}' to base DAT"); // For comparison's sake, we want to a the base bucketing if (useGames) intDat.Items.BucketBy(Field.Machine_Name, DedupeType.None); else intDat.Items.BucketBy(Field.DatItem_CRC, DedupeType.Full); // Then we compare against the base DAT List keys = intDat.Items.Keys.ToList(); Parallel.ForEach(keys, Globals.ParallelOptions, key => { // Game Against uses game names if (useGames) { // If the base DAT doesn't contain the key, keep it if (!Items.ContainsKey(key)) return; // If the number of items is different, then keep it if (Items[key].Count != intDat.Items[key].Count) return; // Otherwise, compare by name and hash the remaining files bool exactMatch = true; foreach (DatItem item in intDat.Items[key]) { // TODO: Make this granular to name as well if (!Items[key].Contains(item)) { exactMatch = false; break; } } // If we have an exact match, remove the game if (exactMatch) intDat.Items.Remove(key); } // Standard Against uses hashes else { List datItems = intDat.Items[key]; List keepDatItems = new List(); foreach (DatItem datItem in datItems) { if (!Items.HasDuplicates(datItem, true)) keepDatItems.Add(datItem); } // Now add the new list to the key intDat.Items.Remove(key); intDat.Items.AddRange(key, keepDatItems); } }); } /// /// Output cascading diffs /// /// Dat headers used optionally /// List of DatFiles representing the individually indexed items public List DiffCascade(List datHeaders) { // Create a list of DatData objects representing output files List outDats = new List(); // Ensure the current DatFile is sorted optimally Items.BucketBy(Field.DatItem_CRC, DedupeType.None); // Loop through each of the inputs and get or create a new DatData object InternalStopwatch watch = new InternalStopwatch("Initializing and filling all output DATs"); // Create the DatFiles from the set of headers DatFile[] outDatsArray = new DatFile[datHeaders.Count]; Parallel.For(0, datHeaders.Count, Globals.ParallelOptions, j => { DatFile diffData = Create(datHeaders[j]); diffData.Items = new ItemDictionary(); FillWithSourceIndex(diffData, j); outDatsArray[j] = diffData; }); outDats = outDatsArray.ToList(); watch.Stop(); return outDats; } /// /// Output duplicate item diff /// /// List of inputs to write out from public DatFile DiffDuplicates(List inputs) { List paths = inputs.Select(i => new ParentablePath(i)).ToList(); return DiffDuplicates(paths); } /// /// Output duplicate item diff /// /// List of inputs to write out from public DatFile DiffDuplicates(List inputs) { InternalStopwatch watch = new InternalStopwatch("Initializing duplicate DAT"); // Fill in any information not in the base DAT if (string.IsNullOrWhiteSpace(Header.FileName)) Header.FileName = "All DATs"; if (string.IsNullOrWhiteSpace(Header.Name)) Header.Name = "All DATs"; if (string.IsNullOrWhiteSpace(Header.Description)) Header.Description = "All DATs"; string post = " (Duplicates)"; DatFile dupeData = Create(Header); dupeData.Header.FileName += post; dupeData.Header.Name += post; dupeData.Header.Description += post; dupeData.Items = new ItemDictionary(); watch.Stop(); // Now, loop through the dictionary and populate the correct DATs watch.Start("Populating duplicate DAT"); Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => { List items = DatItem.Merge(Items[key]); // If the rom list is empty or null, just skip it if (items == null || items.Count == 0) return; // Loop through and add the items correctly foreach (DatItem item in items) { if (item.DupeType.HasFlag(DupeType.External)) { DatItem newrom = item.Clone() as DatItem; newrom.Machine.Name += $" ({Path.GetFileNameWithoutExtension(inputs[item.Source.Index].CurrentPath)})"; dupeData.Items.Add(key, newrom); } } }); watch.Stop(); return dupeData; } /// /// Output non-cascading diffs /// /// List of inputs to write out from public List DiffIndividuals(List inputs) { List paths = inputs.Select(i => new ParentablePath(i)).ToList(); return DiffIndividuals(paths); } /// /// Output non-cascading diffs /// /// List of inputs to write out from public List DiffIndividuals(List inputs) { InternalStopwatch watch = new InternalStopwatch("Initializing all individual DATs"); // Fill in any information not in the base DAT if (string.IsNullOrWhiteSpace(Header.FileName)) Header.FileName = "All DATs"; if (string.IsNullOrWhiteSpace(Header.Name)) Header.Name = "All DATs"; if (string.IsNullOrWhiteSpace(Header.Description)) Header.Description = "All DATs"; // Loop through each of the inputs and get or create a new DatData object DatFile[] outDatsArray = new DatFile[inputs.Count]; Parallel.For(0, inputs.Count, Globals.ParallelOptions, j => { string innerpost = $" ({j} - {inputs[j].GetNormalizedFileName(true)} Only)"; DatFile diffData = Create(Header); diffData.Header.FileName += innerpost; diffData.Header.Name += innerpost; diffData.Header.Description += innerpost; diffData.Items = new ItemDictionary(); outDatsArray[j] = diffData; }); // Create a list of DatData objects representing individual output files List outDats = outDatsArray.ToList(); watch.Stop(); // Now, loop through the dictionary and populate the correct DATs watch.Start("Populating all individual DATs"); Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => { List items = DatItem.Merge(Items[key]); // If the rom list is empty or null, just skip it if (items == null || items.Count == 0) return; // Loop through and add the items correctly foreach (DatItem item in items) { if (item.DupeType.HasFlag(DupeType.Internal) || item.DupeType == 0x00) outDats[item.Source.Index].Items.Add(key, item); } }); watch.Stop(); return outDats.ToList(); } /// /// Output non-duplicate item diff /// /// List of inputs to write out from public DatFile DiffNoDuplicates(List inputs) { List paths = inputs.Select(i => new ParentablePath(i)).ToList(); return DiffNoDuplicates(paths); } /// /// Output non-duplicate item diff /// /// List of inputs to write out from public DatFile DiffNoDuplicates(List inputs) { InternalStopwatch watch = new InternalStopwatch("Initializing no duplicate DAT"); // Fill in any information not in the base DAT if (string.IsNullOrWhiteSpace(Header.FileName)) Header.FileName = "All DATs"; if (string.IsNullOrWhiteSpace(Header.Name)) Header.Name = "All DATs"; if (string.IsNullOrWhiteSpace(Header.Description)) Header.Description = "All DATs"; string post = " (No Duplicates)"; DatFile outerDiffData = Create(Header); outerDiffData.Header.FileName += post; outerDiffData.Header.Name += post; outerDiffData.Header.Description += post; outerDiffData.Items = new ItemDictionary(); watch.Stop(); // Now, loop through the dictionary and populate the correct DATs watch.Start("Populating no duplicate DAT"); Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => { List items = DatItem.Merge(Items[key]); // If the rom list is empty or null, just skip it if (items == null || items.Count == 0) return; // Loop through and add the items correctly foreach (DatItem item in items) { if (item.DupeType.HasFlag(DupeType.Internal) || item.DupeType == 0x00) { DatItem newrom = item.Clone() as DatItem; newrom.Machine.Name += $" ({Path.GetFileNameWithoutExtension(inputs[item.Source.Index].CurrentPath)})"; outerDiffData.Items.Add(key, newrom); } } }); watch.Stop(); return outerDiffData; } /// /// Fill a DatFile with all items with a particular ItemType /// /// DatFile to add found items to /// ItemType to retrieve items for /// DatFile containing all items with the ItemType/returns> public void FillWithItemType(DatFile indexDat, ItemType itemType) { // Loop through and add the items for this index to the output Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => { List items = DatItem.Merge(Items[key]); // If the rom list is empty or null, just skip it if (items == null || items.Count == 0) return; foreach (DatItem item in items) { if (item.ItemType == itemType) indexDat.Items.Add(key, item); } }); } /// /// Fill a DatFile with all items with a particular source index ID /// /// DatFile to add found items to /// Source index ID to retrieve items for /// DatFile containing all items with the source index ID/returns> public void FillWithSourceIndex(DatFile indexDat, int index) { // Loop through and add the items for this index to the output Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => { List items = DatItem.Merge(Items[key]); // If the rom list is empty or null, just skip it if (items == null || items.Count == 0) return; foreach (DatItem item in items) { if (item.Source.Index == index) indexDat.Items.Add(key, item); } }); } /// /// Populate from multiple paths while returning the invividual headers /// /// Paths to DATs to parse /// List of DatHeader objects representing headers public List PopulateUserData(List inputs) { List paths = inputs.Select(i => new ParentablePath(i)).ToList(); return PopulateUserData(paths); } /// /// Populate from multiple paths while returning the invividual headers /// /// Paths to DATs to parse /// List of DatHeader objects representing headers public List PopulateUserData(List inputs) { DatFile[] datFiles = new DatFile[inputs.Count]; InternalStopwatch watch = new InternalStopwatch("Processing individual DATs"); // Parse all of the DATs into their own DatFiles in the array Parallel.For(0, inputs.Count, Globals.ParallelOptions, i => { var input = inputs[i]; logger.User($"Adding DAT: {input.CurrentPath}"); datFiles[i] = Create(Header.CloneFiltering()); datFiles[i].Parse(input, i, keep: true); }); watch.Stop(); watch.Start("Populating internal DAT"); for (int i = 0; i < inputs.Count; i++) { AddFromExisting(datFiles[i], true); } watch.Stop(); return datFiles.Select(d => d.Header).ToList(); } #endregion #region Filtering /// /// Apply cleaning methods to the DatFile /// /// Cleaner to use /// True if the error that is thrown should be thrown back to the caller, false otherwise /// True if cleaning was successful, false on error public bool ApplyCleaning(Cleaner cleaner, bool throwOnError = false) { try { // Perform item-level cleaning CleanDatItems(cleaner); // Bucket and dedupe according to the flag if (cleaner?.DedupeRoms == DedupeType.Full) Items.BucketBy(Field.DatItem_CRC, cleaner.DedupeRoms); else if (cleaner?.DedupeRoms == DedupeType.Game) Items.BucketBy(Field.Machine_Name, cleaner.DedupeRoms); // Process description to machine name if (cleaner?.DescriptionAsName == true) MachineDescriptionToName(); // If we are removing scene dates, do that now if (cleaner?.SceneDateStrip == true) StripSceneDatesFromItems(); // Run the one rom per game logic, if required if (cleaner?.OneGamePerRegion == true) OneGamePerRegion(cleaner.RegionList); // Run the one rom per game logic, if required if (cleaner?.OneRomPerGame == true) OneRomPerGame(); // If we are removing fields, do that now if (cleaner.ExcludeFields != null && cleaner.ExcludeFields.Any()) RemoveFieldsFromItems(cleaner.ExcludeFields); // Remove all marked items Items.ClearMarked(); // We remove any blanks, if we aren't supposed to have any if (cleaner?.KeepEmptyGames == false) Items.ClearEmpty(); } catch (Exception ex) { logger.Error(ex); if (throwOnError) throw ex; return false; } return true; } /// /// Apply a set of Extra INIs on the DatFile /// /// ExtrasIni to use /// True if the error that is thrown should be thrown back to the caller, false otherwise /// True if the extras were applied, false on error public bool ApplyExtras(ExtraIni extras, bool throwOnError = false) { try { // Bucket by game first Items.BucketBy(Field.Machine_Name, DedupeType.None); // Create a new set of mappings based on the items var map = new Dictionary>(); // Loop through each of the extras foreach (ExtraIniItem item in extras.Items) { foreach (var mapping in item.Mappings) { string key = mapping.Key; List machineNames = mapping.Value; // Loop through the machines and add the new mappings foreach (string machine in machineNames) { if (!map.ContainsKey(machine)) map[machine] = new Dictionary(); map[machine][item.Field] = key; } } } // Now apply the new set of mappings foreach (string key in map.Keys) { // If the key doesn't exist, continue if (!Items.ContainsKey(key)) continue; List datItems = Items[key]; var mappings = map[key]; foreach (var datItem in datItems) { datItem.SetFields(mappings); } } } catch (Exception ex) { logger.Error(ex); if (throwOnError) throw ex; return false; } return true; } /// /// Apply a Filter on the DatFile /// /// Filter to use /// True if entire machines are considered, false otherwise (default) /// True if the error that is thrown should be thrown back to the caller, false otherwise /// True if the DatFile was filtered, false on error public bool ApplyFilter(Filter filter, bool perMachine = false, bool throwOnError = false) { // If we have a null filter, return false if (filter == null) return false; // If we're filtering per machine, bucket by machine first if (perMachine) Items.BucketBy(Field.Machine_Name, DedupeType.None); try { // Loop over every key in the dictionary List keys = Items.Keys.ToList(); foreach (string key in keys) { // For every item in the current key bool machinePass = true; List items = Items[key]; foreach (DatItem item in items) { // If we have a null item, we can't pass it if (item == null) continue; // If the item is already filtered out, we skip if (item.Remove) continue; // If the rom doesn't pass the filter, mark for removal if (!item.PassesFilter(filter)) { item.Remove = true; // If we're in machine mode, set and break if (perMachine) { machinePass = false; break; } } } // If we didn't pass and we're in machine mode, set all items as remove if (perMachine && !machinePass) { foreach (DatItem item in items) { item.Remove = true; } } // Assign back for caution Items[key] = items; } } catch (Exception ex) { logger.Error(ex); if (throwOnError) throw ex; return false; } return true; } /// /// Apply splitting on the DatFile /// /// Split type to try /// True if DatFile tags override splitting, false otherwise /// True if the error that is thrown should be thrown back to the caller, false otherwise /// True if the DatFile was split, false on error public bool ApplySplitting(MergingFlag splitType, bool useTags, bool throwOnError = false) { try { // If we are using tags from the DAT, set the proper input for split type unless overridden if (useTags && splitType == MergingFlag.None) splitType = Header.ForceMerging; // Run internal splitting switch (splitType) { case MergingFlag.None: // No-op break; case MergingFlag.Device: CreateDeviceNonMergedSets(DedupeType.None); break; case MergingFlag.Full: CreateFullyNonMergedSets(DedupeType.None); break; case MergingFlag.NonMerged: CreateNonMergedSets(DedupeType.None); break; case MergingFlag.Merged: CreateMergedSets(DedupeType.None); break; case MergingFlag.Split: CreateSplitSets(DedupeType.None); break; } } catch (Exception ex) { logger.Error(ex); if (throwOnError) throw ex; return false; } return true; } /// /// Apply SuperDAT naming logic to a merged DatFile /// /// List of inputs to use for renaming public void ApplySuperDAT(List inputs) { List keys = Items.Keys.ToList(); Parallel.ForEach(keys, Globals.ParallelOptions, key => { List items = Items[key].ToList(); List newItems = new List(); foreach (DatItem item in items) { DatItem newItem = item; string filename = inputs[newItem.Source.Index].CurrentPath; string rootpath = inputs[newItem.Source.Index].ParentPath; if (!string.IsNullOrWhiteSpace(rootpath)) rootpath += Path.DirectorySeparatorChar.ToString(); filename = filename.Remove(0, rootpath.Length); newItem.Machine.Name = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + Path.DirectorySeparatorChar + newItem.Machine.Name; newItems.Add(newItem); } Items.Remove(key); Items.AddRange(key, newItems); }); } /// /// Clean individual items based on the current filter /// /// Cleaner to use public void CleanDatItems(Cleaner cleaner) { List keys = Items.Keys.ToList(); foreach (string key in keys) { // For every item in the current key List items = Items[key]; foreach (DatItem item in items) { // If we have a null item, we can't clean it it if (item == null) continue; // Run cleaning per item item.Clean(cleaner); } // Assign back for caution Items[key] = items; } } /// /// Use game descriptions as names in the DAT, updating cloneof/romof/sampleof /// /// True if the error that is thrown should be thrown back to the caller, false otherwise public void MachineDescriptionToName(bool throwOnError = false) { try { // First we want to get a mapping for all games to description ConcurrentDictionary mapping = new ConcurrentDictionary(); Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => { List items = Items[key]; foreach (DatItem item in items) { // If the key mapping doesn't exist, add it mapping.TryAdd(item.Machine.Name, item.Machine.Description.Replace('/', '_').Replace("\"", "''").Replace(":", " -")); } }); // Now we loop through every item and update accordingly Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => { List items = Items[key]; List newItems = new List(); foreach (DatItem item in items) { // Update machine name if (!string.IsNullOrWhiteSpace(item.Machine.Name) && mapping.ContainsKey(item.Machine.Name)) item.Machine.Name = mapping[item.Machine.Name]; // Update cloneof if (!string.IsNullOrWhiteSpace(item.Machine.CloneOf) && mapping.ContainsKey(item.Machine.CloneOf)) item.Machine.CloneOf = mapping[item.Machine.CloneOf]; // Update romof if (!string.IsNullOrWhiteSpace(item.Machine.RomOf) && mapping.ContainsKey(item.Machine.RomOf)) item.Machine.RomOf = mapping[item.Machine.RomOf]; // Update sampleof if (!string.IsNullOrWhiteSpace(item.Machine.SampleOf) && mapping.ContainsKey(item.Machine.SampleOf)) item.Machine.SampleOf = mapping[item.Machine.SampleOf]; // Add the new item to the output list newItems.Add(item); } // Replace the old list of roms with the new one Items.Remove(key); Items.AddRange(key, newItems); }); } catch (Exception ex) { logger.Warning(ex.ToString()); if (throwOnError) throw ex; } } /// /// Filter a DAT using 1G1R logic given an ordered set of regions /// /// Ordered list of regions to use /// /// In the most technical sense, the way that the region list is being used does not /// confine its values to be just regions. Since it's essentially acting like a /// specialized version of the machine name filter, anything that is usually encapsulated /// in parenthesis would be matched on, including disc numbers, languages, editions, /// and anything else commonly used. Please note that, unlike other existing 1G1R /// solutions, this does not have the ability to contain custom mappings of parent /// to clone sets based on name, nor does it have the ability to match on the /// Release DatItem type. /// public void OneGamePerRegion(List regions) { // If we have null region list, make it empty if (regions == null) regions = new List(); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, DedupeType.None, norename: true); // Then we want to get a mapping of all machines to parents Dictionary> parents = new Dictionary>(); foreach (string key in Items.Keys) { DatItem item = Items[key][0]; // Match on CloneOf first if (!string.IsNullOrEmpty(item.Machine.CloneOf)) { if (!parents.ContainsKey(item.Machine.CloneOf.ToLowerInvariant())) parents.Add(item.Machine.CloneOf.ToLowerInvariant(), new List()); parents[item.Machine.CloneOf.ToLowerInvariant()].Add(item.Machine.Name.ToLowerInvariant()); } // Then by RomOf else if (!string.IsNullOrEmpty(item.Machine.RomOf)) { if (!parents.ContainsKey(item.Machine.RomOf.ToLowerInvariant())) parents.Add(item.Machine.RomOf.ToLowerInvariant(), new List()); parents[item.Machine.RomOf.ToLowerInvariant()].Add(item.Machine.Name.ToLowerInvariant()); } // Otherwise, treat it as a parent else { if (!parents.ContainsKey(item.Machine.Name.ToLowerInvariant())) parents.Add(item.Machine.Name.ToLowerInvariant(), new List()); parents[item.Machine.Name.ToLowerInvariant()].Add(item.Machine.Name.ToLowerInvariant()); } } // Once we have the full list of mappings, filter out games to keep foreach (string key in parents.Keys) { // Find the first machine that matches the regions in order, if possible string machine = default; foreach (string region in regions) { machine = parents[key].FirstOrDefault(m => Regex.IsMatch(m, @"\(.*" + region + @".*\)", RegexOptions.IgnoreCase)); if (machine != default) break; } // If we didn't get a match, use the parent if (machine == default) machine = key; // Remove the key from the list parents[key].Remove(machine); // Remove the rest of the items from this key parents[key].ForEach(k => Items.Remove(k)); } // Finally, strip out the parent tags RemoveTagsFromChild(); } /// /// Ensure that all roms are in their own game (or at least try to ensure) /// public void OneRomPerGame() { // Because this introduces subfolders, we need to set the SuperDAT type Header.Type = "SuperDAT"; // For each rom, we want to update the game to be "/" Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => { List items = Items[key]; for (int i = 0; i < items.Count; i++) { items[i].SetOneRomPerGame(); } }); } /// /// Remove fields as per the header /// /// List of fields to use public void RemoveFieldsFromItems(List fields) { // If we have null field list, make it empty if (fields == null) fields = new List(); // Output the logging statement logger.User("Removing filtered fields"); // Now process all of the roms Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => { List items = Items[key]; for (int j = 0; j < items.Count; j++) { items[j].RemoveFields(fields); } Items.Remove(key); Items.AddRange(key, items); }); } /// /// Strip the dates from the beginning of scene-style set names /// public void StripSceneDatesFromItems() { // Output the logging statement logger.User("Stripping scene-style dates"); // Set the regex pattern to use string pattern = @"([0-9]{2}\.[0-9]{2}\.[0-9]{2}-)(.*?-.*?)"; // Now process all of the roms Parallel.ForEach(Items.Keys, Globals.ParallelOptions, key => { List items = Items[key]; for (int j = 0; j < items.Count; j++) { DatItem item = items[j]; if (Regex.IsMatch(item.Machine.Name, pattern)) item.Machine.Name = Regex.Replace(item.Machine.Name, pattern, "$2"); if (Regex.IsMatch(item.Machine.Description, pattern)) item.Machine.Description = Regex.Replace(item.Machine.Description, pattern, "$2"); items[j] = item; } Items.Remove(key); Items.AddRange(key, items); }); } #endregion // TODO: Should any of these create a new DatFile in the process? // The reason this comes up is that doing any of the splits or merges // is an inherently destructive process. Making it output a new DatFile // might make it easier to deal with multiple internal steps. On the other // hand, this will increase memory usage significantly and would force the // existing paths to behave entirely differently #region Internal Splitting/Merging /// /// Use cdevice_ref tags to get full non-merged sets and remove parenting tags /// /// Dedupe type to be used private void CreateDeviceNonMergedSets(DedupeType mergeroms) { logger.User("Creating device non-merged sets from the DAT"); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, mergeroms, norename: true); // Now we want to loop through all of the games and set the correct information while (AddRomsFromDevices(false, false)) ; while (AddRomsFromDevices(true, false)) ; // Then, remove the romof and cloneof tags so it's not picked up by the manager RemoveTagsFromChild(); } /// /// Use cloneof tags to create non-merged sets and remove the tags plus using the device_ref tags to get full sets /// /// Dedupe type to be used private void CreateFullyNonMergedSets(DedupeType mergeroms) { logger.User("Creating fully non-merged sets from the DAT"); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, mergeroms, norename: true); // Now we want to loop through all of the games and set the correct information while (AddRomsFromDevices(true, true)) ; AddRomsFromDevices(false, true); AddRomsFromParent(); // Now that we have looped through the cloneof tags, we loop through the romof tags AddRomsFromBios(); // Then, remove the romof and cloneof tags so it's not picked up by the manager RemoveTagsFromChild(); } /// /// Use cloneof tags to create merged sets and remove the tags /// /// Dedupe type to be used private void CreateMergedSets(DedupeType mergeroms) { logger.User("Creating merged sets from the DAT"); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, mergeroms, norename: true); // Now we want to loop through all of the games and set the correct information AddRomsFromChildren(); // Now that we have looped through the cloneof tags, we loop through the romof tags RemoveBiosRomsFromChild(false); RemoveBiosRomsFromChild(true); // Finally, remove the romof and cloneof tags so it's not picked up by the manager RemoveTagsFromChild(); } /// /// Use cloneof tags to create non-merged sets and remove the tags /// /// Dedupe type to be used private void CreateNonMergedSets(DedupeType mergeroms) { logger.User("Creating non-merged sets from the DAT"); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, mergeroms, norename: true); // Now we want to loop through all of the games and set the correct information AddRomsFromParent(); // Now that we have looped through the cloneof tags, we loop through the romof tags RemoveBiosRomsFromChild(false); RemoveBiosRomsFromChild(true); // Finally, remove the romof and cloneof tags so it's not picked up by the manager RemoveTagsFromChild(); } /// /// Use cloneof and romof tags to create split sets and remove the tags /// /// Dedupe type to be used private void CreateSplitSets(DedupeType mergeroms) { logger.User("Creating split sets from the DAT"); // For sake of ease, the first thing we want to do is bucket by game Items.BucketBy(Field.Machine_Name, mergeroms, norename: true); // Now we want to loop through all of the games and set the correct information RemoveRomsFromChild(); // Now that we have looped through the cloneof tags, we loop through the romof tags RemoveBiosRomsFromChild(false); RemoveBiosRomsFromChild(true); // Finally, remove the romof and cloneof tags so it's not picked up by the manager RemoveTagsFromChild(); } /// /// Use romof tags to add roms to the children /// private void AddRomsFromBios() { List games = Items.Keys.OrderBy(g => g).ToList(); foreach (string game in games) { // If the game has no items in it, we want to continue if (Items[game].Count == 0) continue; // Determine if the game has a parent or not string parent = null; if (!string.IsNullOrWhiteSpace(Items[game][0].Machine.RomOf)) parent = Items[game][0].Machine.RomOf; // If the parent doesnt exist, we want to continue if (string.IsNullOrWhiteSpace(parent)) continue; // If the parent doesn't have any items, we want to continue if (Items[parent].Count == 0) continue; // If the parent exists and has items, we copy the items from the parent to the current game DatItem copyFrom = Items[game][0]; List parentItems = Items[parent]; foreach (DatItem item in parentItems) { DatItem datItem = (DatItem)item.Clone(); datItem.CopyMachineInformation(copyFrom); if (Items[game].Where(i => i.GetName() == datItem.GetName()).Count() == 0 && !Items[game].Contains(datItem)) Items.Add(game, datItem); } } } /// /// Use device_ref and optionally slotoption tags to add roms to the children /// /// True if only child device sets are touched, false for non-device sets (default) /// True if slotoptions tags are used as well, false otherwise private bool AddRomsFromDevices(bool dev = false, bool useSlotOptions = false) { bool foundnew = false; List machines = Items.Keys.OrderBy(g => g).ToList(); foreach (string machine in machines) { // If the machine doesn't have items, we continue if (Items[machine] == null || Items[machine].Count == 0) continue; // If the machine (is/is not) a device, we want to continue if (dev ^ (Items[machine][0].Machine.MachineType.HasFlag(MachineType.Device))) continue; // Get all device reference names from the current machine List deviceReferences = Items[machine] .Where(i => i.ItemType == ItemType.DeviceReference) .Select(i => i as DeviceReference) .Select(dr => dr.Name) .Distinct() .ToList(); // Get all slot option names from the current machine List slotOptions = Items[machine] .Where(i => i.ItemType == ItemType.Slot) .Select(i => i as Slot) .Where(s => s.SlotOptionsSpecified) .SelectMany(s => s.SlotOptions) .Select(so => so.DeviceName) .Distinct() .ToList(); // If we're checking device references if (deviceReferences.Any()) { // Loop through all names and check the corresponding machines List newDeviceReferences = new List(); foreach (string deviceReference in deviceReferences) { // If the machine doesn't exist then we continue if (Items[deviceReference] == null || Items[deviceReference].Count == 0) continue; // Add to the list of new device reference names List devItems = Items[deviceReference]; newDeviceReferences.AddRange(devItems .Where(i => i.ItemType == ItemType.DeviceReference) .Select(i => (i as DeviceReference).Name)); // Set new machine information and add to the current machine DatItem copyFrom = Items[machine][0]; foreach (DatItem item in devItems) { // If the parent machine doesn't already contain this item, add it if (!Items[machine].Any(i => i.ItemType == item.ItemType && i.GetName() == item.GetName())) { // Set that we found new items foundnew = true; // Clone the item and then add it DatItem datItem = (DatItem)item.Clone(); datItem.CopyMachineInformation(copyFrom); Items.Add(machine, datItem); } } } // Now that every device reference is accounted for, add the new list of device references, if they don't already exist foreach (string deviceReference in newDeviceReferences.Distinct()) { if (!deviceReferences.Contains(deviceReference)) Items[machine].Add(new DeviceReference() { Name = deviceReference }); } } // If we're checking slotoptions if (useSlotOptions && slotOptions.Any()) { // Loop through all names and check the corresponding machines List newSlotOptions = new List(); foreach (string slotOption in slotOptions) { // If the machine doesn't exist then we continue if (Items[slotOption] == null || Items[slotOption].Count == 0) continue; // Add to the list of new slot option names List slotItems = Items[slotOption]; newSlotOptions.AddRange(slotItems .Where(i => i.ItemType == ItemType.Slot) .Where(s => (s as Slot).SlotOptionsSpecified) .SelectMany(s => (s as Slot).SlotOptions) .Select(o => o.DeviceName)); // Set new machine information and add to the current machine DatItem copyFrom = Items[machine][0]; foreach (DatItem item in slotItems) { // If the parent machine doesn't already contain this item, add it if (!Items[machine].Any(i => i.ItemType == item.ItemType && i.GetName() == item.GetName())) { // Set that we found new items foundnew = true; // Clone the item and then add it DatItem datItem = (DatItem)item.Clone(); datItem.CopyMachineInformation(copyFrom); Items.Add(machine, datItem); } } } // Now that every device is accounted for, add the new list of slot options, if they don't already exist foreach (string slotOption in newSlotOptions.Distinct()) { if (!slotOptions.Contains(slotOption)) Items[machine].Add(new Slot() { SlotOptions = new List { new SlotOption { DeviceName = slotOption } } }); } } } return foundnew; } /// /// Use cloneof tags to add roms to the children, setting the new romof tag in the process /// private void AddRomsFromParent() { List games = Items.Keys.OrderBy(g => g).ToList(); foreach (string game in games) { // If the game has no items in it, we want to continue if (Items[game].Count == 0) continue; // Determine if the game has a parent or not string parent = null; if (!string.IsNullOrWhiteSpace(Items[game][0].Machine.CloneOf)) parent = Items[game][0].Machine.CloneOf; // If the parent doesnt exist, we want to continue if (string.IsNullOrWhiteSpace(parent)) continue; // If the parent doesn't have any items, we want to continue if (Items[parent].Count == 0) continue; // If the parent exists and has items, we copy the items from the parent to the current game DatItem copyFrom = Items[game][0]; List parentItems = Items[parent]; foreach (DatItem item in parentItems) { DatItem datItem = (DatItem)item.Clone(); datItem.CopyMachineInformation(copyFrom); if (Items[game].Where(i => i.GetName()?.ToLowerInvariant() == datItem.GetName()?.ToLowerInvariant()).Count() == 0 && !Items[game].Contains(datItem)) { Items.Add(game, datItem); } } // Now we want to get the parent romof tag and put it in each of the items List items = Items[game]; string romof = Items[parent][0].Machine.RomOf; foreach (DatItem item in items) { item.Machine.RomOf = romof; } } } /// /// Use cloneof tags to add roms to the parents, removing the child sets in the process /// /// True to add DatItems to subfolder of parent (not including Disk), false otherwise private void AddRomsFromChildren(bool subfolder = true) { List games = Items.Keys.OrderBy(g => g).ToList(); foreach (string game in games) { // If the game has no items in it, we want to continue if (Items[game].Count == 0) continue; // Determine if the game has a parent or not string parent = null; if (!string.IsNullOrWhiteSpace(Items[game][0].Machine.CloneOf)) parent = Items[game][0].Machine.CloneOf; // If there is no parent, then we continue if (string.IsNullOrWhiteSpace(parent)) continue; // Otherwise, move the items from the current game to a subfolder of the parent game DatItem copyFrom; if (Items[parent].Count == 0) { copyFrom = new Rom(); copyFrom.Machine.Name = parent; copyFrom.Machine.Description = parent; } else { copyFrom = Items[parent][0]; } List items = Items[game]; foreach (DatItem item in items) { // Special disk handling if (item.ItemType == ItemType.Disk) { Disk disk = item as Disk; // If the merge tag exists and the parent already contains it, skip if (disk.MergeTag != null && Items[parent].Where(i => i.ItemType == ItemType.Disk).Select(i => (i as Disk).Name).Contains(disk.MergeTag)) { continue; } // If the merge tag exists but the parent doesn't contain it, add to parent else if (disk.MergeTag != null && !Items[parent].Where(i => i.ItemType == ItemType.Disk).Select(i => (i as Disk).Name).Contains(disk.MergeTag)) { disk.CopyMachineInformation(copyFrom); Items.Add(parent, disk); } // If there is no merge tag, add to parent else if (disk.MergeTag == null) { disk.CopyMachineInformation(copyFrom); Items.Add(parent, disk); } } // Special rom handling else if (item.ItemType == ItemType.Rom) { Rom rom = item as Rom; // If the merge tag exists and the parent already contains it, skip if (rom.MergeTag != null && Items[parent].Where(i => i.ItemType == ItemType.Rom).Select(i => (i as Rom).Name).Contains(rom.MergeTag)) { continue; } // If the merge tag exists but the parent doesn't contain it, add to subfolder of parent else if (rom.MergeTag != null && !Items[parent].Where(i => i.ItemType == ItemType.Rom).Select(i => (i as Rom).Name).Contains(rom.MergeTag)) { if (subfolder) rom.Name = $"{rom.Machine.Name}\\{rom.Name}"; rom.CopyMachineInformation(copyFrom); Items.Add(parent, rom); } // If the parent doesn't already contain this item, add to subfolder of parent else if (!Items[parent].Contains(item)) { if (subfolder) rom.Name = $"{item.Machine.Name}\\{rom.Name}"; rom.CopyMachineInformation(copyFrom); Items.Add(parent, rom); } } // All other that would be missing to subfolder of parent else if (!Items[parent].Contains(item)) { if (subfolder) item.SetFields(new Dictionary { [Field.DatItem_Name] = $"{item.Machine.Name}\\{item.GetName()}" }); item.CopyMachineInformation(copyFrom); Items.Add(parent, item); } } // Then, remove the old game so it's not picked up by the writer Items.Remove(game); } } /// /// Remove all BIOS and device sets /// private void RemoveBiosAndDeviceSets() { List games = Items.Keys.OrderBy(g => g).ToList(); foreach (string game in games) { if (Items[game].Count > 0 && (Items[game][0].Machine.MachineType.HasFlag(MachineType.Bios) || Items[game][0].Machine.MachineType.HasFlag(MachineType.Device))) { Items.Remove(game); } } } /// /// Use romof tags to remove bios roms from children /// /// True if only child Bios sets are touched, false for non-bios sets (default) private void RemoveBiosRomsFromChild(bool bios = false) { // Loop through the romof tags List games = Items.Keys.OrderBy(g => g).ToList(); foreach (string game in games) { // If the game has no items in it, we want to continue if (Items[game].Count == 0) continue; // If the game (is/is not) a bios, we want to continue if (bios ^ Items[game][0].Machine.MachineType.HasFlag(MachineType.Bios)) continue; // Determine if the game has a parent or not string parent = null; if (!string.IsNullOrWhiteSpace(Items[game][0].Machine.RomOf)) parent = Items[game][0].Machine.RomOf; // If the parent doesnt exist, we want to continue if (string.IsNullOrWhiteSpace(parent)) continue; // If the parent doesn't have any items, we want to continue if (Items[parent].Count == 0) continue; // If the parent exists and has items, we remove the items that are in the parent from the current game List parentItems = Items[parent]; foreach (DatItem item in parentItems) { DatItem datItem = (DatItem)item.Clone(); while (Items[game].Contains(datItem)) { Items.Remove(game, datItem); } } } } /// /// Use cloneof tags to remove roms from the children /// private void RemoveRomsFromChild() { List games = Items.Keys.OrderBy(g => g).ToList(); foreach (string game in games) { // If the game has no items in it, we want to continue if (Items[game].Count == 0) continue; // Determine if the game has a parent or not string parent = null; if (!string.IsNullOrWhiteSpace(Items[game][0].Machine.CloneOf)) parent = Items[game][0].Machine.CloneOf; // If the parent doesnt exist, we want to continue if (string.IsNullOrWhiteSpace(parent)) continue; // If the parent doesn't have any items, we want to continue if (Items[parent].Count == 0) continue; // If the parent exists and has items, we remove the parent items from the current game List parentItems = Items[parent]; foreach (DatItem item in parentItems) { DatItem datItem = (DatItem)item.Clone(); while (Items[game].Contains(datItem)) { Items.Remove(game, datItem); } } // Now we want to get the parent romof tag and put it in each of the remaining items List items = Items[game]; string romof = Items[parent][0].Machine.RomOf; foreach (DatItem item in items) { item.Machine.RomOf = romof; } } } /// /// Remove all romof and cloneof tags from all games /// private void RemoveTagsFromChild() { List games = Items.Keys.OrderBy(g => g).ToList(); foreach (string game in games) { List items = Items[game]; foreach (DatItem item in items) { item.Machine.CloneOf = null; item.Machine.RomOf = null; item.Machine.SampleOf = null; } } } #endregion #region Parsing /// /// Create a DatFile and parse a file into it /// /// Name of the file to be parsed /// True if the error that is thrown should be thrown back to the caller, false otherwise public static DatFile CreateAndParse(string filename, bool throwOnError = false) { DatFile datFile = Create(); datFile.Parse(new ParentablePath(filename), throwOnError: throwOnError); return datFile; } /// /// Parse a DAT and return all found games and roms within /// /// Name of the file to be parsed /// Index ID for the DAT /// True if full pathnames are to be kept, false otherwise (default) /// True if original extension should be kept, false otherwise (default) /// True if quotes are assumed in supported types (default), false otherwise /// True if the error that is thrown should be thrown back to the caller, false otherwise public void Parse( string filename, int indexId = 0, bool keep = false, bool keepext = false, bool quotes = true, bool throwOnError = false) { ParentablePath path = new ParentablePath(filename.Trim('"')); Parse(path, indexId, keep, keepext, quotes, throwOnError); } /// /// Parse a DAT and return all found games and roms within /// /// Name of the file to be parsed /// Index ID for the DAT /// True if full pathnames are to be kept, false otherwise (default) /// True if original extension should be kept, false otherwise (default) /// True if quotes are assumed in supported types (default), false otherwise /// True if the error that is thrown should be thrown back to the caller, false otherwise public void Parse( ParentablePath input, int indexId = 0, bool keep = false, bool keepext = false, bool quotes = true, bool throwOnError = true) { // Get the current path from the filename string currentPath = input.CurrentPath; // Check the file extension first as a safeguard if (!PathExtensions.HasValidDatExtension(currentPath)) return; // If the output filename isn't set already, get the internal filename Header.FileName = (string.IsNullOrWhiteSpace(Header.FileName) ? (keepext ? Path.GetFileName(currentPath) : Path.GetFileNameWithoutExtension(currentPath)) : Header.FileName); // If the output type isn't set already, get the internal output type DatFormat currentPathFormat = GetDatFormat(currentPath); Header.DatFormat = (Header.DatFormat == 0 ? currentPathFormat : Header.DatFormat); Items.SetBucketedBy(Field.DatItem_CRC); // Setting this because it can reduce issues later // Now parse the correct type of DAT try { Create(currentPathFormat, this, quotes)?.ParseFile(currentPath, indexId, keep, throwOnError); } catch (Exception ex) { logger.Error(ex, $"Error with file '{currentPath}'"); if (throwOnError) throw ex; } } /// /// Get what type of DAT the input file is /// /// Name of the file to be parsed /// The DatFormat corresponding to the DAT protected DatFormat GetDatFormat(string filename) { // Limit the output formats based on extension if (!PathExtensions.HasValidDatExtension(filename)) return 0; // Get the extension from the filename string ext = PathExtensions.GetNormalizedExtension(filename); // Check if file exists if (!File.Exists(filename)) return 0; // Some formats should only require the extension to know switch (ext) { case "csv": return DatFormat.CSV; case "json": return DatFormat.SabreJSON; case "md5": return DatFormat.RedumpMD5; #if NET_FRAMEWORK case "ripemd160": return DatFormat.RedumpRIPEMD160; #endif case "sfv": return DatFormat.RedumpSFV; case "sha1": return DatFormat.RedumpSHA1; case "sha256": return DatFormat.RedumpSHA256; case "sha384": return DatFormat.RedumpSHA384; case "sha512": return DatFormat.RedumpSHA512; case "spamsum": return DatFormat.RedumpSpamSum; case "ssv": return DatFormat.SSV; case "tsv": return DatFormat.TSV; } // For everything else, we need to read it // Get the first two non-whitespace, non-comment lines to check, if possible string first = string.Empty, second = string.Empty; try { using (StreamReader sr = File.OpenText(filename)) { first = sr.ReadLine().ToLowerInvariant(); while ((string.IsNullOrWhiteSpace(first) || first.StartsWith("