using System;
using System.Collections;
using System.IO;

namespace MathSpeakWrite
{
	/// <summary>
	/// SymbolData is a class designed read in the contents of a symbol description file and 
	/// store them in ArrayList which can be queried for symbols, names or the symbols for name
	/// and names for symbols.
	/// </summary>
	public class SymbolData
	{
		public ArrayList names, codes;
		public string lastfn;

		public SymbolData()
		{
			names = new ArrayList();
			codes = new ArrayList();
		}
			
		/// <summary>
		/// Using the already provided filename for the SymbolData file, reloads it's contents.
		/// </summary>
		public void ReadData()
		{
			ReadData(lastfn);
		}
		
		/// <summary>
		/// Loads the contents of the SymbolData file with the filename. 
		/// </summary>
		/// <param name="fn"></param>
		public void ReadData(string fn)
		{
			StreamReader aSR = new StreamReader(fn);
			char [] seperators = {'\t'};
			string presStr, presName, presHex;
			
			this.names = new ArrayList();
			this.codes = new ArrayList();

			lastfn = fn;

			while(true)
			{
				try
				{
					presStr = aSR.ReadLine();
					
					if(presStr == null)
						break;

					string [] arr = presStr.Split(seperators, 2);
					presName = arr[0];
					presHex = arr[1];
					this.names.Add(presName);
					this.codes.Add(presHex);
				}
				catch (IOException)
				{
					break;
				}
			}
		}
		
		/// <summary>
		/// Asks for the name of the nth symbol
		/// </summary>
		/// <param name="n"></param>
		/// <returns></returns>
		public string NameN(int n)
		{
			return (string) names[n];
		}
		
		/// <summary>
		/// Asks for the code of the nth symbol
		/// </summary>
		/// <param name="n"></param>
		/// <returns></returns>
		public string CodeN(int n)
		{
			return (string) codes[n];
		}
		
		/// <summary>
		/// Given the code for a symbol, find it's name. Returns null if no such symbol in 
		/// this SymbolData.
		/// </summary>
		/// <param name="code"></param>
		/// <returns></returns>
		public string NameCorrespondingToCode(string code)
		{
			int i;
			for(i=0; i < codes.Count; i++)
				if((string) codes[i] == code)
					return (string) names[i];
			return null;
		}
		
		/// <summary>
		/// Given the name for a symbol, return it's code. Returns null if no such symbol in 
		/// this SymbolData.
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public string CodeCorrespondingToName(string name)
		{
			int i;
			for(i=0; i < names.Count; i++)
				if((string) names[i] == name)
					return (string) codes[i];
			return null;
		}
		
		/// <summary>
		/// Returns the number of symbols in this SymbolData.
		/// </summary>
		/// <param name="n"></param>
		/// <returns></returns>
		public int NumSyms(int n)
		{
			return codes.Count;
		}
	}
}
