private List<byte> ParseLine(string line)
{
List<byte> data = new List<byte>();
if (!line.Contains('"') && line.Contains(','))
{
// there are no double-quotes on the line, simply split by ","
foreach (string elem in line.Split(','))
data.Add(byte.Parse(elem));
}
else if (line.Contains('"'))
{
if (line.Contains(','))
{
string[] elements = line.Split(',');
bool isStartOfString = true;
for (int i = 0; i < elements.Length; i++)
{
string elem = elements[i];
if (isStartOfString && elem.StartsWith("\""))
{
// this is a string, not a number
if (elem.EndsWith("\"") && elem.Length > 1)
{
// this is not a multipart string
data.AddRange(Encoding.UTF8.GetBytes(elem.Substring(1, elem.Length - 2)));
}
else
{
if (elem.Length > 1)
data.AddRange(Encoding.UTF8.GetBytes(elem.Substring(1)));
data.AddRange(Encoding.UTF8.GetBytes(","));
// this string is spread across multiple strings
isStartOfString = false;
}
}
else
{
if (!isStartOfString)
{
// we are currently parsing a string.
if (elem.EndsWith("\""))
{
data.AddRange(Encoding.UTF8.GetBytes(elem.Substring(0, elem.Length - 1)));
isStartOfString = true; // done finding the end of the string
}
else
{
data.AddRange(Encoding.UTF8.GetBytes(elem));
data.AddRange(Encoding.UTF8.GetBytes(","));
}
}
else
{
data.Add(byte.Parse(elem));
}
}
}
}
else
{
// no commas, so should be one string surrounded by double-quote marks
line = line.Replace("\\0", "\0"); // ltxt has "escaped" nulls.
if (line.StartsWith("\"") && line.EndsWith("\""))
{
data.AddRange(Encoding.UTF8.GetBytes(line.Substring(1, line.Length - 2)));
}
else
{
throw new Exception("String values should start and end with double-quote marks.");
}
}
}
else
{
// line should contain a single number (0-255) with no quotes or commas.
data.Add(byte.Parse(line));
}
return data;
}