using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using Txt2Bib.Records; using System.Windows; using System.Runtime.CompilerServices; using System.CodeDom; namespace Txt2Bib { /// /// Converting entries from text file to BibTeX format /// public class Text2Bib { private string[] _citTypes = { "J", "B", "C", "P", "?" }; /// /// Generate single .bib file from input text files /// /// /// public string Generate(string filenames) { var paths = filenames.Trim().Split('\n'); string result = ""; string output = ""; foreach (var path in paths) { var reader = File.OpenText(path); byte[] contentBytes = File.ReadAllBytes(path); result += Encoding.Latin1.GetString(contentBytes); } IEnumerable entries = new List(); try { entries = result.Split('%').ToList().Select(entry => Process(entry)); } catch (Exception) { throw; } foreach (var entry in entries) { output += entry; } return output; } /// /// Creates a bib entry from source text /// /// Handle exception /// /// /// Invalid citation type for this entry public string Process(string entryFromTxt) { var lines = entryFromTxt.Trim().Replace("\r", string.Empty).Split("\n"); var type = lines.First().Trim(); if (!IsValidEntry(type)) throw new Exception($"Invalid entry type '{type}'"); string citation = type switch { "J" => (new ArticleBib()).Convert(lines), //"B" => new BookBib(), //"C" => new ChapterBib(), //"P" => new ConferenceBib(), _ => (new ArticleBib()).Convert(lines) }; return citation; } /// /// Validate txt entry based /// on citation types /// /// protected bool IsValidEntry(string entryType) { return _citTypes.Contains(entryType); } /// /// TODO: How to determine correct encoding of text file?? /// /// The stream reader for the file /// private Encoding GuessEncoding(StreamReader reader) { var cp = "UTF-8"; return Encoding.GetEncoding(cp); } } }