lnicola
6/24/2014 - 3:09 PM

TeXify.cs

using System.IO;
using System.Text;

namespace TeXify
{
	class Program
	{
		static bool inQuotes = false;

		static string FixLine(string line)
		{
			string result = "";

			for (int i = 0; i < line.Length; i++)
				if (line[i] == '"')
				{
					if (inQuotes)
						result += "''";
					else
						result += "``";

					inQuotes = !inQuotes;
				}
				else
					result += line[i];
			return result.Replace("...", "\\ldots "); //.Replace('ş', 'ș').Replace('ţ', 'ț').Replace('Ş', 'Ș').Replace('Ţ', 'Ț');
		}

		static string ProcessFile(string fileName, StreamWriter fStreamWriter)
		{
			int start = fileName.LastIndexOf('\\') + 1, stop = fileName.LastIndexOf('.');
			string title = fileName.Substring(start, stop - start);
			StreamReader streamReader = new StreamReader(File.OpenRead(fileName), Encoding.UTF8);
			string ptitle = streamReader.ReadLine().Replace("...", "\\ldots ");
			fStreamWriter.WriteLine("\\poemtitle{" + ptitle + "}");
			fStreamWriter.WriteLine("\\begin{poem}");

			string line, nextLine = streamReader.ReadLine();
			while ((line = nextLine) != null)
			{
				nextLine = streamReader.ReadLine();
				if (line != "")
				{
					line = FixLine(line);

					if (nextLine == "" || nextLine == null)
						line += "\n\\end{stanza}";
					else
						if (!line.EndsWith("\\brokenline"))
							line += "\\verseline";
				}
				else
					if (nextLine == "")
						line = "\\bigskip";
					else
						line = "\\begin{stanza}";

				fStreamWriter.WriteLine(line);
			}

			streamReader.Close();
			fStreamWriter.WriteLine("\\end{poem}\n\\newpage");

			return title;
		}

		static void Main(string[] args)
		{
			if (args.Length != 1)
				return;

			StreamWriter fstreamWriter = new StreamWriter(File.Create("poems.inc"), Encoding.UTF8);
			string path = args[0].Substring(0, args[0].LastIndexOf('\\') + 1);

			foreach (string fileName in File.ReadAllLines(args[0]))
				ProcessFile(path + fileName + ".txt", fstreamWriter);

			fstreamWriter.Close();
		}
	}
}