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'); var output = ""; foreach (var path in paths) { output += CreateBibTeX(path); } return output; } /// /// Create a BibTeX string from an input file path /// /// /// public string CreateBibTeX(string path) { var reader = File.OpenText(path); byte[] contentBytes = File.ReadAllBytes(path); var content = Encoding.Latin1.GetString(contentBytes); IEnumerable entries = new List(); try { entries = content.Split('%').ToList().Select(entry => Process(entry)); } catch (Exception) { throw; } var bibtex = ""; foreach (var entry in entries) { bibtex += entry; } return bibtex; } /// /// 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; try { citation = type switch { "J" => (new ArticleBib()).Convert(lines), "B" => new BookBib().Convert(lines), //"C" => new ChapterBib(), //"P" => new ConferenceBib(), _ => "" }; } catch (Exception) { throw new Exception("Faulty string in " + entryFromTxt); } 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); } } }