using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TableApi;

public class xyTable
{
	public class ButtonConfig
	{
		public string Type { get; set; }

		public string Name { get; set; }

		public string GridX { get; set; }

		public string GridY { get; set; }

		public string OffsetX { get; set; }

		public string OffsetY { get; set; }

		public string Zmax { get; set; }
	}

	private class ConfigItems
	{
		public string xCoord;

		public string yCoord;

		public ConfigItems(string x, string y)
		{
			xCoord = x;
			yCoord = y;
		}
	}

	protected class SerialIO
	{
		private static SerialPort _serialPort = new SerialPort();

		private string message;

		private long xyPromptTimeout;

		private Stopwatch timer = new Stopwatch();

		public SerialIO(long promptTimeout)
		{
			xyPromptTimeout = promptTimeout;
		}

		public void GetPortNames(ref string[] portnames)
		{
			portnames = SerialPort.GetPortNames();
		}

		public bool Open(string portname, int baudrate)
		{
			_serialPort = new SerialPort();
			_serialPort.PortName = portname;
			_serialPort.BaudRate = baudrate;
			try
			{
				if (_serialPort.IsOpen)
				{
					_serialPort.Close();
				}
				_serialPort.Open();
			}
			catch (Exception ex)
			{
				message = ex.Message;
				return false;
			}
			return true;
		}

		public string GetResponse()
		{
			string text = "";
			bool flag = false;
			timer.Reset();
			try
			{
				if (_serialPort.IsOpen)
				{
					text = ReadBuffer();
					timer.Start();
					while (!flag && timer.Elapsed.TotalSeconds < (double)xyPromptTimeout)
					{
						if (text.Length >= "CMD >> ".Length && text.EndsWith("CMD >> "))
						{
							flag = true;
							timer.Stop();
							break;
						}
						text = ReadBuffer();
					}
					if ((double)xyPromptTimeout <= timer.Elapsed.TotalSeconds)
					{
						timer.Reset();
						message = "ERROR: Timeout occured. Response prompt not received from contrller board via serial port.";
					}
					timer.Reset();
					_serialPort.DiscardInBuffer();
					_serialPort.DiscardOutBuffer();
					return text;
				}
			}
			catch (Exception ex)
			{
				message = ex.Message;
			}
			return message;
		}

		public string ReadBuffer()
		{
			string text = "";
			bool flag = false;
			if (_serialPort.BytesToRead > 0)
			{
				flag = true;
				while (flag)
				{
					text += _serialPort.ReadExisting();
					if (_serialPort.BytesToRead == 0)
					{
						flag = false;
					}
				}
				flag = false;
			}
			return text;
		}

		public bool CheckControllerCOMport()
		{
			string text = "";
			bool flag = false;
			long num = 5L;
			Stopwatch stopwatch = new Stopwatch();
			stopwatch.Reset();
			if (!Send("\r\n"))
			{
				return false;
			}
			try
			{
				if (_serialPort.IsOpen)
				{
					text = ReadBuffer();
					stopwatch.Start();
					while (!flag && stopwatch.Elapsed.Seconds <= num)
					{
						if (text.Length >= "CMD >> ".Length && text.EndsWith("CMD >> "))
						{
							flag = true;
							stopwatch.Stop();
							break;
						}
						text = ReadBuffer();
					}
					if (num <= stopwatch.Elapsed.Seconds)
					{
						stopwatch.Reset();
						message = "ERROR: Timeout occured. Response prompt not received from contrller board via serial port.";
						return false;
					}
					stopwatch.Reset();
					_serialPort.DiscardInBuffer();
					_serialPort.DiscardOutBuffer();
					return true;
				}
			}
			catch (Exception ex)
			{
				message = ex.Message;
			}
			return true;
		}

		public bool Send(string strCmd)
		{
			bool result = true;
			try
			{
				if (_serialPort.IsOpen)
				{
					_serialPort.Write(strCmd);
				}
			}
			catch
			{
				result = false;
			}
			return result;
		}

		public bool IsOpen()
		{
			try
			{
				if (_serialPort.IsOpen)
				{
					return true;
				}
				return false;
			}
			catch (Exception)
			{
				return false;
			}
		}

		public void Close()
		{
			try
			{
				if (_serialPort.IsOpen)
				{
					_serialPort.Close();
				}
			}
			catch (Exception)
			{
			}
		}
	}

	private const string QPREFIX = "qti_";

	private const string XyPrompt = "CMD >> ";

	private string xyTableCfgPath = "mmi_xyTable.cfg ";

	public bool phoneIsReleased;

	private int iDUTZone_x;

	private int iDUTZone_y;

	private int iDUTZone_safe_z1;

	private int iDUTZone_safe_z2;

	private int iDUTZone_all_z1;

	private int iDUTZone_all_z2;

	private StreamReader reader;

	public static List<ButtonConfig> buttons = new List<ButtonConfig>();

	public Dictionary<string, string> setupItems = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
	{
		{ "[SETUP]", "Setup Config Section" },
		{ "ID", "" },
		{ "NAME", "" },
		{ "PRTNUM", "" },
		{ "DIMTYPE", "" },
		{ "TXYORIGIN", "" },
		{ "PXYORIGIN", "" },
		{ "PXOFFSET", "" },
		{ "PYOFFSET", "" },
		{ "PXDIM", "" },
		{ "PYDIM", "" },
		{ "SXDIM", "" },
		{ "SYDIM", "" },
		{ "OYDIM", "" },
		{ "OXDIM", "" },
		{ "ZMAX", "" },
		{ "ZPHONE", "" },
		{ "GRIDSIZE", "" },
		{ "COMPORTNAME", "" },
		{ "COMPORTBAUD", "" },
		{ "Q1KEEPOUTX1", "" },
		{ "Q1KEEPOUTX2", "" },
		{ "Q1KEEPOUTY1", "" },
		{ "Q1KEEPOUTY2", "" },
		{ "Z2_XOffset", "" },
		{ "Z2_YOffset", "" },
		{ "XrefOffset", "" },
		{ "YrefOffset", "" },
		{ "Z1GlobalOffset", "" },
		{ "Z2GlobalOffset", "" },
		{ "DUTZone_Max_X", "" },
		{ "DUTZone_Max_Y", "" },
		{ "DUTZone_safe_z1", "" },
		{ "DUTZone_safe_z2", "" },
		{ "AllZone_safe_z1", "" },
		{ "AllZone_safe_z2", "" },
		{ "AllZone_safe_z1=0", "" },
		{ "AllZone_safe_z2=400 ", "" }
	};

	private IOSTAT ioStat;

	private IOSTAT tmpIoStat;

	private bool waitForSerialCmd = true;

	private static long promptTimeoutValueSec = 10L;

	private bool z1Down;

	private bool z2Down;

	public bool isMetric = true;

	public string msg = "";

	private SerialIO comPort = new SerialIO(promptTimeoutValueSec);

	public ButtonConfig bc;

	public string xyTableCfgFullPath
	{
		get
		{
			return xyTableCfgPath;
		}
		set
		{
			xyTableCfgPath = value;
		}
	}

	public IOSTAT IoStatus
	{
		get
		{
			tmpIoStat = ioStat;
			if (tmpIoStat != IOSTAT.COMPLETE)
			{
				ioStat = IOSTAT.READY;
			}
			return tmpIoStat;
		}
	}

	public bool WaitForCmd
	{
		set
		{
			waitForSerialCmd = value;
		}
	}

	public void NoRetract_MoveTo_touch(string loc, bool useOffset = false, bool moveWhileDownOK = false)
	{
		bool retractWhenDone = false;
		if (!zMoveToAndPress(loc, useOffset, ref msg, moveDiagnal: false, moveWhileDownOK, retractWhenDone))
		{
			MessageBox.Show("Error:" + msg);
		}
	}

	public void Retract_MoveTo_touch(string loc, bool useOffset = false)
	{
		zRetract_partial(loc);
		bool retractWhenDone = false;
		bool moveWhileDownOK = false;
		if (!zMoveToAndPress(loc, useOffset, ref msg, moveDiagnal: false, moveWhileDownOK, retractWhenDone))
		{
			MessageBox.Show("Error:" + msg);
		}
	}

	public void Retract_MoveTo(string loc, bool useOffset = false, bool enablePartiialRetract = true, bool z1_retract = false, bool z2_retract = false)
	{
		if (enablePartiialRetract)
		{
			zMoveTo_NoPress_partialRetract(loc, enablePartiialRetract, useOffset, z1_retract, z2_retract);
			return;
		}
		zRetractAll();
		if (!zMoveTo_NoPress(loc, useOffset))
		{
			MessageBox.Show("Error in moving to " + loc);
		}
	}

	public void zRetract_partial(string target_location, bool retractz1 = false, bool retractz2 = false)
	{
		if (safeZoneStatus(target_location))
		{
			zRetract_partial(DUT_zone: true, retractz1, retractz2);
		}
		else
		{
			zRetract_partial(DUT_zone: false, retractz1, retractz2);
		}
	}

	public void zMoveToAndPress_partialRetract(string TartgetLOC, bool enablePartialRetract = false)
	{
		if (!enablePartialRetract)
		{
			zRetractAll();
		}
		else if (safeZoneStatus(TartgetLOC))
		{
			zRetract_partial(DUT_zone: true);
		}
		else
		{
			zRetract_partial();
		}
		string text = "";
		bool moveWhileDownOK = true;
		bool retractWhenDone = false;
		bool moveDiagnal = false;
		bool useOffsets = false;
		if (!zMoveToAndPress(TartgetLOC, useOffsets, ref text, moveDiagnal, moveWhileDownOK, retractWhenDone))
		{
			MessageBox.Show("Error:" + text);
		}
	}

	public void zMoveTo_NoPress_partialRetract(string TartgetLOC, bool enablePartialRetract = false, bool useOffsets = false, bool z1_retract = false, bool z2_retract = false)
	{
		if (!enablePartialRetract)
		{
			zRetractAll();
		}
		else if (safeZoneStatus(TartgetLOC))
		{
			zRetract_partial(DUT_zone: true, z1_retract, z2_retract);
		}
		else
		{
			zRetract_partial(DUT_zone: false, z1_retract, z2_retract);
		}
		string text = "";
		bool moveWhileDownOK = true;
		bool moveDiagnal = false;
		if (!zMoveTo_NoPress(TartgetLOC, useOffsets, moveDiagnal, moveWhileDownOK))
		{
			MessageBox.Show("Error:" + text);
		}
	}

	public bool safeZoneStatus(string targetLOC, bool useOffset = false)
	{
		try
		{
			string text = "";
			int x = 0;
			int y = 0;
			int z = 0;
			int z2 = 0;
			int x2 = 0;
			int y2 = 0;
			int z3 = 0;
			int z4 = 0;
			if (!GetPositions(ref x, ref y, ref z, ref z2))
			{
				text += "\r\nfail to get xyTable position info";
			}
			if (!GetCfgPOS(targetLOC, ref x2, ref y2, ref z3, ref z4, useOffset, ref text))
			{
				text += "failed to get xyTable position info";
			}
			if (iDUTZone_x > Math.Max(x2, x) && iDUTZone_y > Math.Max(y2, y))
			{
				return true;
			}
			return false;
		}
		catch (Exception ex)
		{
			msg += ex.Message;
			return false;
		}
	}

	public bool checkidDUTPresnt(bool reverse = false)
	{
		if (AutoStartIOSetup())
		{
			bool stat = false;
			string ioMsg = "";
			GetAutoStartStatus(ref stat, ref ioMsg, reverse);
			return stat;
		}
		MessageBox.Show("Error: AutoStartIOSetup");
		return false;
	}

	public void QuerySafetyZone()
	{
		string text = "";
		string stringConfigItemValue = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.XrefOffset), ref text);
		string stringConfigItemValue2 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.YrefOffset), ref text);
		string stringConfigItemValue3 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Z1GlobalOffset), ref text);
		string stringConfigItemValue4 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Z2GlobalOffset), ref text);
		int result = 0;
		int result2 = 0;
		int result3 = 0;
		int result4 = 0;
		if (!int.TryParse(stringConfigItemValue, out result))
		{
			result = 0;
		}
		if (!int.TryParse(stringConfigItemValue2, out result2))
		{
			result2 = 0;
		}
		if (!int.TryParse(stringConfigItemValue3, out result3))
		{
			result3 = 0;
		}
		if (!int.TryParse(stringConfigItemValue4, out result4))
		{
			result4 = 0;
		}
		result = (int)((double)result / 2.54);
		result2 = (int)((double)result2 / 2.54);
		result3 = (int)((double)result3 / 2.54);
		result4 = (int)((double)result4 / 2.54);
		string text2 = "0";
		string text3 = "0";
		string text4 = "0";
		string text5 = "0";
		string text6 = "0";
		string text7 = "0";
		text2 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.DUTZone_Max_X), ref text);
		text3 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.DUTZone_Max_Y), ref text);
		text4 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.DUTZone_safe_z1), ref text);
		text5 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.DUTZone_safe_z2), ref text);
		text6 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.AllZone_safe_z1), ref text);
		text7 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.AllZone_safe_z2), ref text);
		int result5 = 0;
		if (!int.TryParse(text2, out result5))
		{
			iDUTZone_x = 0;
		}
		else
		{
			iDUTZone_x = result + (int)((double)result5 / 2.54);
		}
		if (!int.TryParse(text3, out result5))
		{
			iDUTZone_y = 0;
		}
		else
		{
			iDUTZone_y = result2 + (int)((double)result5 / 2.54);
		}
		if (!int.TryParse(text4, out result5))
		{
			iDUTZone_safe_z1 = 0;
		}
		else
		{
			iDUTZone_safe_z1 = result3 + (int)((double)result5 / 2.54);
		}
		if (!int.TryParse(text5, out result5))
		{
			iDUTZone_safe_z2 = 0;
		}
		else
		{
			iDUTZone_safe_z2 = result4 + (int)((double)result5 / 2.54);
		}
		if (!int.TryParse(text6, out result5))
		{
			iDUTZone_all_z1 = 0;
		}
		else
		{
			iDUTZone_all_z1 = result3 + (int)((double)result5 / 2.54);
		}
		if (!int.TryParse(text7, out result5))
		{
			iDUTZone_all_z2 = 0;
		}
		else
		{
			iDUTZone_all_z2 = result4 + (int)((double)result5 / 2.54);
		}
	}

	public bool zRetract_partial(bool DUT_zone = false, bool retractz1 = false, bool retractz2 = false)
	{
		bool flag = true;
		int intvalue = 1000;
		int intvalue2 = 1000;
		flag &= SendCommand("qti_z1?" + '\n');
		flag &= ReadBuffer_getValue(ref intvalue);
		flag &= SendCommand("qti_z2?" + '\n');
		if (!(flag & ReadBuffer_getValue(ref intvalue2)))
		{
			msg = "Error: Send command failed. COM Port may not be connected.";
			ioStat = IOSTAT.ERROR;
			return false;
		}
		bool flag2 = false;
		if (!ControllerPortOk())
		{
			msg = "XY Controller COM port is not responding.";
			return false;
		}
		int num = iDUTZone_all_z1;
		int num2 = iDUTZone_all_z2;
		if (DUT_zone)
		{
			num = iDUTZone_safe_z1;
			num2 = iDUTZone_safe_z2;
		}
		if (retractz1 || intvalue > num)
		{
			if (!SendCommand(num + " qti_z1" + '\n'))
			{
				msg = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (!DUT_zone)
			{
				z1Down = false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
		}
		if (retractz2 || intvalue2 > num2)
		{
			if (!SendCommand(num2 + " qti_z2" + '\n'))
			{
				msg = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			if (!DUT_zone)
			{
				z1Down = false;
			}
		}
		return true;
	}

	private bool ReadBuffer_getValue(ref int intvalue)
	{
		bool flag = true;
		string text = "";
		intvalue = 0;
		Stopwatch stopwatch = new Stopwatch();
		stopwatch.Start();
		int num = 0;
		if (flag)
		{
			while (text == "" && num < 2)
			{
				text = comPort.ReadBuffer();
				num = stopwatch.Elapsed.Seconds;
			}
			if (num >= 2)
			{
				msg = "Error: Attempting to read the abs value for the Z actuator failed.";
				return false;
			}
			stopwatch.Stop();
			if (text.Contains("="))
			{
				int startIndex = text.IndexOf("=");
				text = text.Substring(startIndex);
				text = text.Replace("=", "");
				int num2 = text.IndexOf("ok");
				if (num2 <= 0)
				{
					msg = "Error: No abs value found for the Z actuator query.";
					return false;
				}
				text = text.Substring(0, num2);
			}
			if (!int.TryParse(text, out intvalue))
			{
				intvalue = 0;
			}
			return true;
		}
		msg = "Error: Attempting to read the abs value for the Z actuator failed.";
		return false;
	}

	public bool zMoveTo_NoPress(string xyLocation, bool useOffset = false, bool moveDiagnal = false, bool moveWhileDownOK = false)
	{
		string text = "";
		string xLoc = "";
		string yLoc = "";
		string zMax = "";
		string actuator = "";
		bool flag = true;
		string text2 = "";
		if (!ControllerPortOk())
		{
			text2 = "XY Controller COM port is not responding.";
			return false;
		}
		text = xyLocation;
		getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Zphone), ref text2);
		if (!QueryXyLocation2(text, ref xLoc, ref yLoc, ref zMax, ref actuator, useOffset, ref text2))
		{
			return false;
		}
		if (zMax == "")
		{
			zMax = "0";
		}
		_ = actuator == "Z1";
		if (CheckForKeepout(xLoc, yLoc))
		{
			if (!moveWhileDownOK)
			{
				flag = SendCommand("qti_z1_home  \r\n");
				if (!flag)
				{
					text2 = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
				flag &= SendCommand("qti_z2_home  \r\n");
				if (!flag)
				{
					text2 = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
			}
			if (!moveDiagnal)
			{
				flag &= SendCommand(xLoc + " qti_x " + '\n');
				if (!flag)
				{
					text2 = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
				flag &= SendCommand(yLoc + " qti_y " + '\n');
				if (!flag)
				{
					text2 = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
			}
			else
			{
				flag &= SendCommand(xLoc + " " + yLoc + " qti_xy " + '\n');
				if (!flag)
				{
					text2 = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
			}
			return flag;
		}
		text2 = " Error: Keepout area violated.";
		return false;
	}

	public bool MoveXYHome_Z_partialRetract()
	{
		try
		{
			bool flag = true;
			if (!ControllerPortOk())
			{
				msg = "XY Controller COM port is not responding.";
				return false;
			}
			int x = -1;
			int y = -1;
			int z = -1;
			int z2 = -1;
			GetPositions(ref x, ref y, ref z, ref z2);
			if (x > iDUTZone_x || y > iDUTZone_y)
			{
				zRetract_partial();
			}
			else
			{
				zRetract_partial(DUT_zone: true);
			}
			flag &= SendCommand("qti_xy_home" + '\n');
			if (!flag)
			{
				msg = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			return flag;
		}
		catch
		{
			msg = "Error: MoveXYHome_Z_partialRetract.";
			return false;
		}
	}

	public bool GetPositions(ref int x, ref int y, ref int z1, ref int z2)
	{
		bool flag = true;
		bool flag2 = true;
		flag &= SendCommand("qti_x?" + '\n');
		flag2 &= ReadBuffer_getValue(ref x);
		flag &= SendCommand("qti_y?" + '\n');
		flag2 &= ReadBuffer_getValue(ref y);
		flag &= SendCommand("qti_z1?" + '\n');
		flag2 &= ReadBuffer_getValue(ref z1);
		flag &= SendCommand("qti_z2?" + '\n');
		flag2 &= ReadBuffer_getValue(ref z2);
		if (!flag)
		{
			msg = "Error: Send command failed. COM Port may not be connected.";
			ioStat = IOSTAT.ERROR;
			return false;
		}
		if (!flag2)
		{
			msg = "Error: Parse info from buffer.";
			ioStat = IOSTAT.ERROR;
			return false;
		}
		return flag && flag2;
	}

	public bool GetCfgPOS(string locName, ref int x, ref int y, ref int z1, ref int z2, bool useOffset, ref string msg)
	{
		string xLoc = "";
		string yLoc = "";
		string zMax = "";
		string actuator = "";
		if (QueryXyLocation2(locName, ref xLoc, ref yLoc, ref zMax, ref actuator, useOffset, ref msg))
		{
			int.TryParse(xLoc, out x);
			int.TryParse(yLoc, out y);
			if (actuator.Trim().ToUpper() == "Z1")
			{
				int.TryParse(zMax, out z1);
				z2 = 0;
			}
			if (actuator.Trim().ToUpper() == "Z2")
			{
				int.TryParse(zMax, out z2);
				z1 = 0;
			}
			return true;
		}
		msg = "error getting loc info from cfg" + msg;
		return false;
	}

	private string getItemNAME(string s)
	{
		if (s.IndexOf("=") < 0)
		{
			return s = "";
		}
		s = s.Substring(0, s.IndexOf("="));
		s = s.Trim();
		return s;
	}

	private string getItemValue(string s)
	{
		if (s.IndexOf("=") < 0)
		{
			return s = "";
		}
		s = s.Remove(0, s.IndexOf("=") + 1);
		s = s.Trim();
		return s;
	}

	public bool OpenUserDefConfigFile(ref string msg)
	{
		string text = "";
		string text2 = "";
		string text3 = "";
		string text4 = "";
		string text5 = "";
		int num = -1;
		msg = "";
		buttons.Clear();
		try
		{
			using (reader = new StreamReader(xyTableCfgFullPath))
			{
				bool flag = false;
				while ((text4 = reader.ReadLine()) != null)
				{
					text4 = text4.ToUpper();
					if (text4.Contains(";"))
					{
						text4 = text4.Remove(text4.IndexOf(";"));
					}
					text4.Trim();
					if (text4.IndexOf("#") == 0)
					{
						continue;
					}
					if (text4.Contains("[") && text4.Contains("]"))
					{
						text = text4.Trim();
						if (text4.Contains("[SETUP]"))
						{
							text = "[SETUP]";
							continue;
						}
						text5 = text;
						text = text4.Trim();
						string tmpSection = text5.Trim('[', ']');
						num = buttons.FindIndex((ButtonConfig item) => item.Name == tmpSection);
						if (num >= 0)
						{
							msg = "Error in config file. Section \"[" + tmpSection + "]\" is already in the List.";
							text = "";
							flag = false;
							continue;
						}
						flag = true;
						AddNewListItem(tmpSection);
						num = buttons.FindIndex((ButtonConfig item) => item.Name == tmpSection);
					}
					else
					{
						if (text4.Length <= 3 || !text4.Contains("=") || !(text != ""))
						{
							continue;
						}
						text5 = text;
						if (text == "[SETUP]")
						{
							text2 = getItemNAME(text4);
							text3 = getItemValue(text4);
							if (!setupItems.ContainsKey(text2))
							{
								continue;
							}
							setupItems[text2] = text3;
							if (text2 == Enum.GetName(typeof(xySETUP), xySETUP.dimtype).ToUpper())
							{
								if (text3.ToUpper() == "IN" || text3 == "")
								{
									isMetric = false;
								}
								else
								{
									isMetric = true;
								}
							}
						}
						else
						{
							if (!(text.Trim() != "") || !flag)
							{
								continue;
							}
							buttons[num].GridX.GetType();
							text2 = getItemNAME(text4);
							text3 = getItemValue(text4);
							Enum.GetName(typeof(xyButtonParams), xyButtonParams.gridx).ToUpper();
							if (text2 == Enum.GetName(typeof(xyButtonParams), xyButtonParams.gridx).ToUpper())
							{
								buttons[num].GridX = text3;
							}
							if (text2 == Enum.GetName(typeof(xyButtonParams), xyButtonParams.gridy).ToUpper())
							{
								buttons[num].GridY = text3;
							}
							if (text2 == Enum.GetName(typeof(xyButtonParams), xyButtonParams.offsetX).ToUpper())
							{
								buttons[num].OffsetX = text3;
							}
							if (text2 == Enum.GetName(typeof(xyButtonParams), xyButtonParams.offsetY).ToUpper())
							{
								buttons[num].OffsetY = text3;
							}
							if (text2 == Enum.GetName(typeof(xyButtonParams), xyButtonParams.zmax).ToUpper())
							{
								buttons[num].Zmax = text3;
							}
							if (text2 == Enum.GetName(typeof(xyButtonParams), xyButtonParams.type).ToUpper())
							{
								if (text3 == "")
								{
									buttons[num].Type = "Z1";
								}
								else
								{
									buttons[num].Type = text3.ToUpper();
								}
							}
						}
					}
				}
			}
		}
		catch (Exception ex)
		{
			msg = "Error opening file: " + xyTableCfgFullPath + " Exception: " + ex.Message;
			return false;
		}
		return true;
	}

	public bool SaveConfigFile(string saveAsFileName, ref string msg)
	{
		try
		{
			string text = "";
			bool flag = false;
			string[] array;
			using (reader = new StreamReader(xyTableCfgFullPath))
			{
				string text2 = "";
				string text3 = "";
				string text4 = "";
				string sectionName = "";
				if (saveAsFileName != "")
				{
					flag = true;
				}
				if (!File.Exists(xyTableCfgFullPath))
				{
					msg = "Error: File not found.";
					return false;
				}
				array = File.ReadAllLines(xyTableCfgFullPath);
				reader.Close();
				bool flag2 = false;
				bool flag3 = false;
				for (int i = 0; i < array.Length; i++)
				{
					if (array[i].ToUpper().Contains("[SETUP]") && validateConfigLine(array[i].ToUpper(), "[SETUP]"))
					{
						flag3 = true;
						flag2 = false;
					}
					else if (!array[i].ToUpper().Contains("[SETUP]") && array[i].Contains("[") && array[i].Contains("]") && validateConfigLine(array[i].ToUpper(), "["))
					{
						flag2 = true;
						flag3 = false;
						string text5 = "";
						text5 = array[i].Trim();
						text5 = text5.Replace("[", "");
						text5 = text5.Replace("]", "");
						text5 = text5.Trim();
						sectionName = text5;
					}
					else if (flag3)
					{
						if (array[i].Contains("=") && validateConfigLine(array[i].ToUpper(), "="))
						{
							text2 = array[i].Substring(0, array[i].IndexOf("="));
							text2 = text2.Trim();
							text4 = getStringConfigItemValue(text2, ref text3);
							array[i] = insertNewParamVal(array[i], text4);
						}
					}
					else
					{
						if (!flag2 || !array[i].Contains("=") || !validateConfigLine(array[i].ToUpper(), "="))
						{
							continue;
						}
						int num = -1;
						text2 = array[i].Substring(0, array[i].IndexOf("="));
						text2 = text2.Trim();
						text2 = text2.ToUpper();
						text4 = "0";
						num = buttons.FindIndex((ButtonConfig item) => item.Name == sectionName);
						if (num > -1)
						{
							if (text2 == "GRIDX")
							{
								text4 = buttons[num].GridX;
							}
							if (text2 == "GRIDY")
							{
								text4 = buttons[num].GridY;
							}
							if (text2 == "OFFSETX")
							{
								text4 = buttons[num].OffsetX;
							}
							if (text2 == "OFFSETY")
							{
								text4 = buttons[num].OffsetY;
							}
							if (text2 == "TYPE")
							{
								text4 = buttons[num].Type;
							}
							if (text2 == "ZMAX")
							{
								text4 = buttons[num].Zmax;
							}
						}
						array[i] = insertNewParamVal(array[i], text4);
					}
				}
			}
			text = string.Join("\r\n", array);
			if (flag)
			{
				File.WriteAllText(saveAsFileName, text);
			}
			else
			{
				File.WriteAllText(xyTableCfgFullPath, text);
			}
		}
		catch (IOException ex)
		{
			msg = "Error saving to config file. " + ex.Message;
		}
		return true;
	}

	private bool GetConfigSectioIndexes(string cfg, string sectionName, ref int start, ref int end)
	{
		int num = 0;
		int num2 = -1;
		int num3 = -1;
		string text = "";
		int num4 = 0;
		start = cfg.IndexOf(sectionName);
		cfg = cfg.Substring(start);
		string[] array = cfg.Split('\n');
		for (int i = 0; i < array.Length; i++)
		{
			text = array[i];
			if (text.Contains("["))
			{
				num2 = text.IndexOf("#");
				num3 = text.IndexOf(";");
				if ((num2 > -1 || num3 > -1) && text.IndexOf("[") <= num2)
				{
					text.IndexOf("[");
				}
				num4 += text.Length;
				break;
			}
			num4 += text.Length;
		}
		end = cfg.IndexOf("[", num + sectionName.Length + 1);
		if (start < end)
		{
			return true;
		}
		return false;
	}

	private string convertStringArrToString(string[] fileArray)
	{
		new StringBuilder();
		string text = "";
		foreach (string text2 in fileArray)
		{
			text += text2;
		}
		text.Replace("\r", "\r\n");
		return text;
	}

	private bool validateConfigLine(string cfgLine, string strToValidate)
	{
		int num = -1;
		int num2 = -1;
		int num3 = -1;
		bool result = true;
		num = cfgLine.IndexOf(";");
		num2 = cfgLine.IndexOf("#");
		num3 = cfgLine.IndexOf(strToValidate);
		if (num > -1 && num < num3)
		{
			result = false;
		}
		if (num2 > -1 && num2 < num3)
		{
			result = false;
		}
		return result;
	}

	private string insertNewParamVal(string lineToParse, string newParamVal)
	{
		string text = lineToParse.Substring(0, lineToParse.IndexOf("="));
		string text2 = "";
		if (newParamVal.Length > 0)
		{
			int num = lineToParse.IndexOf("=");
			_ = lineToParse.Length;
			text2 = lineToParse.Substring(num + 1);
			if (text2.Contains(";"))
			{
				text2 = text2.Substring(0, text2.IndexOf(";"));
			}
			if (text2.Contains("#"))
			{
				text2 = text2.Substring(0, text2.IndexOf("#"));
			}
			text2 = text2.Trim();
			if (text2 == "")
			{
				throw new Exception("Non-Valid value for " + text);
			}
			lineToParse = lineToParse.Replace(text2, newParamVal);
		}
		return lineToParse;
	}

	private void QueryButtonConfig(string name, ref string xLoc, ref string yLoc, ref string offset, ref string zMax)
	{
		int num = buttons.FindIndex((ButtonConfig item) => item.Name == name);
		if (num > -1)
		{
			xLoc = buttons[num].GridX;
			yLoc = buttons[num].GridY;
			offset = buttons[num].OffsetX;
			zMax = buttons[num].Zmax;
		}
	}

	private void UpdateButtonConfig(string name, string xLoc, string yLoc, string offset, string zMax, string sectionName)
	{
		int num = buttons.FindIndex((ButtonConfig item) => item.Name == name);
		if (num > -1)
		{
			buttons[num].GridX = xLoc;
			buttons[num].GridY = yLoc;
			buttons[num].OffsetX = offset;
			buttons[num].Zmax = zMax;
			buttons[num].Type = sectionName;
		}
	}

	public bool AutoStartIOSetup()
	{
		bool flag = true;
		if (comPort.IsOpen())
		{
			if (!SendCommand("ioSetMode 5  3 \r\n"))
			{
				return false;
			}
			comPort.GetResponse();
		}
		return true;
	}

	public bool GetAutoStartStatus(ref bool stat, ref string ioMsg, bool reverse)
	{
		ioMsg = "";
		bool flag = true;
		stat = false;
		if (comPort.IsOpen())
		{
			AutoStartIOSetup();
			if (SendCommand("ioRead 5 \r\n"))
			{
				ioMsg = comPort.GetResponse();
				if (ioMsg.Contains("\r\n0"))
				{
					stat = (reverse ? true : false);
				}
				else
				{
					if (!ioMsg.Contains("\r\n1"))
					{
						return false;
					}
					stat = !reverse;
				}
				return stat;
			}
			ioMsg = "Error reading IO pin ( ioRead 5 ) ommand.";
			return false;
		}
		ioMsg = "Error: comport is not opened.";
		return false;
	}

	public int GetPresureSensorReading()
	{
		string ioMsg = "";
		int reading = -1;
		int pin = 3;
		int mode = 0;
		if (IOSetup(pin, mode, ref ioMsg))
		{
			if (GetIOReading(pin, ref reading, ref ioMsg))
			{
				return reading;
			}
			return -1;
		}
		return -1;
	}

	public bool IOSetup(int pin, int mode, ref string ioMsg)
	{
		if (pin > 5 || pin < 1)
		{
			ioMsg = "Error: invalid IO pin number - valid are 1 to 5";
			return false;
		}
		if (mode > 3 || mode < 0)
		{
			ioMsg = "Error: invalid pin mode number - valid are 0 to 3";
			return false;
		}
		bool flag = true;
		if (comPort.IsOpen())
		{
			if (!SendCommand("ioSetMode " + pin + " " + mode + " \r\n"))
			{
				ioMsg = "Error sending ioSetMode command.";
				return false;
			}
			ioMsg = comPort.GetResponse();
		}
		return true;
	}

	public bool GetIOReading(int pin, ref int reading, ref string ioMsg)
	{
		ioMsg = "";
		bool flag = true;
		reading = -1;
		if (comPort.IsOpen())
		{
			if (SendCommand("ioRead " + pin + " \r\n"))
			{
				ioMsg = comPort.GetResponse();
				if (IntFromStr(ioMsg, ref reading))
				{
					return true;
				}
				return false;
			}
			ioMsg = "Error reading IO pin (" + pin + ") ommand.";
			return false;
		}
		ioMsg = "Error: comport is not opened.";
		return false;
	}

	public bool IntFromStr(string in_str, ref int out_int)
	{
		try
		{
			StringBuilder stringBuilder = new StringBuilder();
			bool flag = false;
			foreach (char c in in_str)
			{
				if (c >= '0' && c <= '9')
				{
					stringBuilder.Append(c);
					flag = true;
				}
				else if (flag)
				{
					break;
				}
			}
			if (stringBuilder.Length == 0)
			{
				return false;
			}
			int.TryParse(stringBuilder.ToString(), out out_int);
			return true;
		}
		catch
		{
			return false;
		}
	}

	public bool Connect(string comPortValue = "", string cfgComBaud = "")
	{
		bool result = false;
		string text = "";
		string text2 = "";
		string text3 = "";
		int result2 = 0;
		if (string.IsNullOrEmpty(comPortValue))
		{
			text = Enum.GetName(typeof(xySETUP), xySETUP.comPortName);
			text2 = Enum.GetName(typeof(xySETUP), xySETUP.comPortBaud);
			comPortValue = getStringConfigItemValue(text, ref text3);
			cfgComBaud = getStringConfigItemValue(text2, ref text3);
		}
		if (!int.TryParse(cfgComBaud, out result2))
		{
			result2 = 0;
		}
		if (result2 == 0)
		{
			result2 = 4800;
		}
		if (comPortValue == "")
		{
			text3 = "COM Port name is empty. Please check the config file parameter for the COM port name.";
			return result;
		}
		result = comPort.Open(comPortValue, result2);
		if (!result)
		{
			text3 = "Unable to connect to COM Port \"" + comPortValue + "\" Baud = " + result2;
			return result;
		}
		return result;
	}

	public bool ConnectComPort(string portName, string buadRate)
	{
		bool result = false;
		string text = "";
		string text2 = "";
		int result2 = 0;
		text = portName;
		text2 = buadRate;
		if (!int.TryParse(text2, out result2))
		{
			result2 = 0;
		}
		if (result2 == 0)
		{
			result2 = 4800;
		}
		if (text == "")
		{
			return result;
		}
		result = comPort.Open(text, result2);
		if (!result)
		{
			_ = "Unable to connect to COM Port \"" + text + "\" Baud = " + result2;
			return result;
		}
		return result;
	}

	public void ClosePort()
	{
		if (comPort.IsOpen())
		{
			comPort.Close();
		}
	}

	public bool ControllerPortOk()
	{
		bool flag = true;
		if (comPort != null && comPort.IsOpen())
		{
			if (comPort.CheckControllerCOMport())
			{
				return true;
			}
			return false;
		}
		return false;
	}

	public bool SendRawCmd(string cmd, ref string retValue, ref string errMsg)
	{
		string text = "";
		string text2 = "";
		bool flag = true;
		if (!ControllerPortOk())
		{
			errMsg = "XY Controller COM port is not responding.";
			return false;
		}
		SendCommand(cmd);
		Stopwatch stopwatch = new Stopwatch();
		stopwatch.Start();
		int num = 0;
		if (flag)
		{
			while (text == "" && num < 2)
			{
				text = comPort.ReadBuffer();
				text2 += text;
				num = stopwatch.Elapsed.Seconds;
				Thread.Sleep(50);
			}
			if (num >= 2)
			{
				stopwatch.Stop();
				errMsg = "Error: Timeout occured attempting to read the input buffer.";
				return false;
			}
			_ = stopwatch.ElapsedMilliseconds;
			stopwatch.Stop();
			retValue = text2;
			return true;
		}
		stopwatch.Stop();
		errMsg = "s: Attempting to read the abs value for the Z actuator failed.";
		return false;
	}

	public bool setXyzSpeed(Speed spd, ref string msg, bool isMotor = true)
	{
		bool flag = true;
		string text = "";
		if (!ControllerPortOk())
		{
			msg = "XY Controller COM port is not responding.";
			return false;
		}
		switch (spd)
		{
		case Speed.DEFAULT_16:
			text = "16 ";
			break;
		case Speed.FAST_2:
			text = "2 ";
			break;
		case Speed.MED_4:
			text = "4 ";
			break;
		case Speed.HIGHEST_1:
			text = "1 ";
			break;
		}
		flag = ((!isMotor) ? (flag & SendCommand(text + "qti_setzstep" + '\n')) : (flag & SendCommand(text + "qti_setxystep" + '\n')));
		if (!flag)
		{
			msg = "Error: Send command failed. COM Port may not be connected.";
			ioStat = IOSTAT.ERROR;
			return false;
		}
		if (waitForSerialCmd)
		{
			msg += comPort.GetResponse();
		}
		return flag;
	}

	public bool RetractZ_ByPercent(zACT actuator, int percent, ref string msg)
	{
		bool flag = true;
		string text = "";
		string text2 = "";
		double result = 0.0;
		double num = 0.0;
		double num2 = 0.0;
		if (percent > 0 && percent < 101)
		{
			num2 = (double)percent * 0.01;
			if (actuator == zACT.LEVERPRESS)
			{
				text2 = "z2";
			}
			if (actuator == zACT.TOUCH)
			{
				text2 = "z1";
			}
			if (!ControllerPortOk())
			{
				msg = "XY Controller COM port is not responding.";
				return false;
			}
			flag &= SendCommand("qti_" + text2 + "?" + '\n');
			Stopwatch stopwatch = new Stopwatch();
			stopwatch.Start();
			int num3 = 0;
			if (flag)
			{
				while (text == "" && num3 < 2)
				{
					text = comPort.ReadBuffer();
					num3 = stopwatch.Elapsed.Seconds;
				}
				if (num3 >= 2)
				{
					msg = "Error: Attempting to read the abs value for the Z actuator failed.";
					return false;
				}
				stopwatch.Stop();
				if (text.Contains("="))
				{
					int startIndex = text.IndexOf("=");
					text = text.Substring(startIndex);
					text = text.Replace("=", "");
					int num4 = text.IndexOf("ok");
					if (num4 <= 0)
					{
						msg = "Error: No abs value found for the Z actuator query.";
						return false;
					}
					text = text.Substring(0, num4);
				}
				if (!double.TryParse(text, out result))
				{
					result = 0.0;
				}
				num = result * num2;
				num = result - num;
				flag &= SendCommand(num.ToString() + " qti_" + text2 + '\n');
				return true;
			}
			msg = "Error: Attempting to read the abs value for the Z actuator failed.";
			return false;
		}
		return true;
	}

	public bool RetractZ_ByValue(zACT actuator, int value, ref string msg)
	{
		bool flag = true;
		string text = "";
		string text2 = "";
		int result = 0;
		int num = 0;
		if (actuator == zACT.LEVERPRESS)
		{
			text2 = "z2";
		}
		if (actuator == zACT.TOUCH)
		{
			text2 = "z1";
		}
		if (!ControllerPortOk())
		{
			msg = "XY Controller COM port is not responding.";
			return false;
		}
		flag &= SendCommand("qti_" + text2 + "?" + '\n');
		Stopwatch stopwatch = new Stopwatch();
		stopwatch.Start();
		int num2 = 0;
		if (flag)
		{
			while (text == "" && num2 < 2)
			{
				text = comPort.ReadBuffer();
				num2 = stopwatch.Elapsed.Seconds;
			}
			if (num2 >= 2)
			{
				msg = "Error: Attempting to read the abs value for the Z actuator failed.";
				return false;
			}
			stopwatch.Stop();
			if (text.Contains("="))
			{
				int startIndex = text.IndexOf("=");
				text = text.Substring(startIndex);
				text = text.Replace("=", "");
				int num3 = text.IndexOf("ok");
				if (num3 <= 0)
				{
					msg = "Error: No abs value found for the Z actuator query.";
					return false;
				}
				text = text.Substring(0, num3);
			}
			if (!int.TryParse(text, out result))
			{
				result = 0;
			}
			num = result - value;
			if (num < 0)
			{
				num = 0;
			}
			flag &= SendCommand(num.ToString() + " qti_" + text2 + '\n');
			return true;
		}
		msg = "Error: Attempting to read the abs value for the Z actuator failed.";
		return false;
	}

	public Dictionary<string, string> GetSetupItems()
	{
		return setupItems;
	}

	public void UpdateSetupItem(xySETUP dictSetupItemName, string itemValue)
	{
		string text = "";
		text = Enum.GetName(typeof(xySETUP), dictSetupItemName);
		if (setupItems.ContainsKey(text))
		{
			setupItems[text] = itemValue;
		}
	}

	public List<string> GetButtonItemNames()
	{
		int num = 0;
		List<string> list = new List<string>();
		num = buttons.Count();
		for (int i = 0; i < num; i++)
		{
			list.Add(buttons[i].Name);
		}
		return list;
	}

	public ButtonConfig GetButtonValues(string buttonName)
	{
		ButtonConfig buttonConfig = new ButtonConfig();
		int num = buttons.FindIndex((ButtonConfig item) => item.Name == buttonName);
		if (num > -1)
		{
			buttonConfig.Name = buttons[num].Name;
			buttonConfig.GridX = buttons[num].GridX;
			buttonConfig.GridY = buttons[num].GridY;
			buttonConfig.OffsetX = buttons[num].OffsetX;
			buttonConfig.OffsetY = buttons[num].OffsetY;
			buttonConfig.Type = buttons[num].Type;
			buttonConfig.Zmax = buttons[num].Zmax;
		}
		return buttonConfig;
	}

	public void SetButtonValues(ButtonConfig bc)
	{
		int num = buttons.FindIndex((ButtonConfig item) => item.Name == bc.Name);
		if (num > -1)
		{
			buttons[num].GridX = bc.GridX;
			buttons[num].GridY = bc.GridY;
			buttons[num].OffsetX = bc.OffsetX;
			buttons[num].OffsetY = bc.OffsetY;
			buttons[num].Type = bc.Type;
			buttons[num].Zmax = bc.Zmax;
		}
	}

	public bool MoveToXY(string xyLocation, bool useOffset, ref string msg, bool moveDiagnal, bool moveWhileDownOK)
	{
		string text = "";
		string xLoc = "";
		string yLoc = "";
		string zMax = "";
		string actuator = "";
		bool flag = true;
		if (!ControllerPortOk())
		{
			msg = "XY Controller COM port is not responding.";
			return false;
		}
		ioStat = IOSTAT.INPROCESS;
		if ((z1Down || z2Down) && !moveWhileDownOK)
		{
			msg = "A 'Z' Acuator is in the down position, cannot move.";
			ioStat = IOSTAT.ERROR;
			return false;
		}
		text = xyLocation;
		if (QueryXyLocation2(text, ref xLoc, ref yLoc, ref zMax, ref actuator, useOffset, ref msg))
		{
			if (!moveDiagnal)
			{
				flag &= SendCommand(xLoc + " qti_x " + '\n');
				if (!flag)
				{
					msg = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
				flag &= SendCommand(yLoc + " qti_y " + '\n');
				if (!flag)
				{
					msg = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
			}
			else
			{
				flag &= SendCommand(xLoc + " " + yLoc + " qti_xy " + '\n');
				if (!flag)
				{
					msg = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
			}
			if (!flag)
			{
				ioStat = IOSTAT.ERROR;
				return false;
			}
			return true;
		}
		msg = "Error: Possible parameter missing.";
		ioStat = IOSTAT.ERROR;
		return false;
	}

	public bool MoveXYHome()
	{
		ioStat = IOSTAT.INPROCESS;
		bool flag = true;
		if (!ControllerPortOk())
		{
			msg = "XY Controller COM port is not responding.";
			return false;
		}
		flag = zUpDown(zACT.LEVERPRESS, "0", down: false);
		z2Down = false;
		flag &= zUpDown(zACT.TOUCH, "0", down: false);
		z1Down = false;
		flag &= SendCommand("qti_xy_home" + '\n');
		if (!flag)
		{
			msg = "Error: Send command failed. COM Port may not be connected.";
			ioStat = IOSTAT.ERROR;
			return false;
		}
		if (waitForSerialCmd)
		{
			comPort.GetResponse();
		}
		if (!flag)
		{
			ioStat = IOSTAT.ERROR;
			return flag;
		}
		ioStat = IOSTAT.COMPLETE;
		return flag;
	}

	public bool zUpDown(zACT actuator, string zDistance, bool down)
	{
		bool flag = true;
		string text = "";
		string text2 = "";
		string text3 = "";
		double num = 0.0;
		double num2 = 0.0;
		double result = 0.0;
		double num3 = 0.0;
		string text4 = "";
		text2 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Z1GlobalOffset), ref text4);
		text3 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Z2GlobalOffset), ref text4);
		msg = text4;
		if (!double.TryParse(text2, out result))
		{
			result = 0.0;
		}
		num = result;
		if (!double.TryParse(text3, out result))
		{
			result = 0.0;
		}
		num2 = result;
		if (!double.TryParse(zDistance, out result))
		{
			result = 0.0;
		}
		num3 = result;
		if (zDistance == "")
		{
			zDistance = " 0 ";
		}
		switch (actuator)
		{
		case zACT.LEVERPRESS:
			text = "z2 ";
			num3 += num2;
			break;
		case zACT.TOUCH:
			text = "z1 ";
			num3 += num;
			break;
		}
		zDistance = num3.ToString();
		if (down)
		{
			flag = SendCommand(zDistance + " qti_" + text + '\n');
			if (!flag)
			{
				msg = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			z1Down = true;
		}
		else
		{
			flag = SendCommand("qti_" + text + "_home" + '\n');
			if (!flag)
			{
				msg = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			z2Down = false;
		}
		return flag;
	}

	public bool zRetractAll(bool Retract_z1 = true, bool Retract_z2 = true)
	{
		bool flag = false;
		if (!ControllerPortOk())
		{
			msg = "XY Controller COM port is not responding.";
			return false;
		}
		if (Retract_z1)
		{
			flag = SendCommand("qti_z1_home " + '\n');
		}
		if (!flag)
		{
			msg = "Error: Send command failed. COM Port may not be connected.";
			ioStat = IOSTAT.ERROR;
			return false;
		}
		if (waitForSerialCmd)
		{
			comPort.GetResponse();
		}
		z1Down = false;
		if (Retract_z2)
		{
			flag &= SendCommand("qti_z2_home " + '\n');
		}
		if (!flag)
		{
			msg = "Error: Send command failed. COM Port may not be connected.";
			ioStat = IOSTAT.ERROR;
			return false;
		}
		if (waitForSerialCmd)
		{
			comPort.GetResponse();
		}
		z2Down = false;
		return true;
	}

	public bool zMoveToAndPress(string xyLocation, bool useOffsets, ref string msg, bool moveDiagnal, bool moveWhileDownOK, bool retractWhenDone = true)
	{
		string text = "";
		string xLoc = "";
		string yLoc = "";
		string zMax = "";
		string actuator = "";
		string text2 = "";
		bool flag = true;
		if (!ControllerPortOk())
		{
			msg = "XY Controller COM port is not responding.";
			return false;
		}
		text = xyLocation;
		getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Zphone), ref msg);
		if (!QueryXyLocation2(text, ref xLoc, ref yLoc, ref zMax, ref actuator, useOffsets, ref msg))
		{
			return false;
		}
		if (zMax == "")
		{
			zMax = "0";
		}
		text2 = ((!(actuator == "Z1")) ? "z2" : "z1");
		if (CheckForKeepout(xLoc, yLoc))
		{
			if (!moveWhileDownOK)
			{
				flag = SendCommand("qti_z1_home  \r\n");
				if (!flag)
				{
					msg = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
				flag &= SendCommand("qti_z2_home  \r\n");
				if (!flag)
				{
					msg = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
			}
			if (!moveDiagnal)
			{
				flag &= SendCommand(xLoc + " qti_x " + '\n');
				if (!flag)
				{
					msg = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
				flag &= SendCommand(yLoc + " qti_y " + '\n');
				if (!flag)
				{
					msg = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
			}
			else
			{
				flag &= SendCommand(xLoc + " " + yLoc + " qti_xy " + '\n');
				if (!flag)
				{
					msg = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
			}
			flag &= SendCommand(zMax + " qti_" + text2 + " \r\n");
			if (!flag)
			{
				msg = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			z1Down = true;
			if (!retractWhenDone)
			{
				return flag;
			}
			flag &= SendCommand("qti_z1_home \r\n");
			if (!flag)
			{
				msg = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			flag &= SendCommand("qti_z2_home \r\n");
			if (!flag)
			{
				msg = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			z1Down = false;
			z2Down = false;
			return flag;
		}
		msg = " Error: Keepout area violated.";
		return false;
	}

	public bool zTouchSwipe(string xy1, string xy2, bool useOffsets, bool retractWhenDone = true)
	{
		string text = "";
		string text2 = "";
		string xLoc = "";
		string yLoc = "";
		string text3 = "";
		string zMax = "";
		string actuator = "";
		bool flag = true;
		if (!ControllerPortOk())
		{
			text3 = "XY Controller COM port is not responding.";
			return false;
		}
		text = xy1;
		text2 = xy2;
		string stringConfigItemValue = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Zphone), ref text3);
		if (QueryXyLocation2(text, ref xLoc, ref yLoc, ref zMax, ref actuator, useOffsets, ref text3))
		{
			if (zMax == "")
			{
				zMax = stringConfigItemValue;
			}
			if (!CheckForKeepout(xLoc, yLoc))
			{
				return false;
			}
			flag = SendCommand(xLoc + " qti_x \r\n");
			if (!flag)
			{
				text3 = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			flag &= SendCommand(yLoc + " qti_y \r\n");
			if (!flag)
			{
				text3 = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			flag &= SendCommand(zMax + " qti_z1 \r\n");
			if (!flag)
			{
				text3 = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
		}
		if (QueryXyLocation2(text2, ref xLoc, ref yLoc, ref zMax, ref actuator, useOffsets, ref text3) && CheckForKeepout(xLoc, yLoc))
		{
			flag = SendCommand(xLoc + " " + yLoc + " qti_xy \r\n");
			if (!flag)
			{
				text3 = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			if (retractWhenDone)
			{
				flag &= SendCommand("z1_home  qti_z1 \r\n");
				if (!flag)
				{
					text3 = "Error: Send command failed. COM Port may not be connected.";
					ioStat = IOSTAT.ERROR;
					return false;
				}
				if (waitForSerialCmd)
				{
					comPort.GetResponse();
				}
			}
		}
		return flag;
	}

	private bool QueryXyLocation2(string locName, ref string xLoc, ref string yLoc, ref string zMax, ref string actuator, bool useOffset, ref string msg)
	{
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4 = 0;
		int num5 = 0;
		int num6 = 0;
		int num7 = 0;
		int num8 = 0;
		int num9 = 0;
		int num10 = 0;
		int num11 = 0;
		string text = "";
		string text2 = "";
		string text3 = "";
		string text4 = "";
		string s = "";
		string s2 = "";
		string text5 = "";
		string text6 = "";
		int num12 = buttons.FindIndex((ButtonConfig item) => item.Name == locName.ToUpper());
		if (num12 > -1)
		{
			xLoc = buttons[num12].GridX;
			yLoc = buttons[num12].GridY;
			s = buttons[num12].OffsetX;
			s2 = buttons[num12].OffsetY;
			actuator = buttons[num12].Type;
			zMax = buttons[num12].Zmax;
		}
		text = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Z2_XOffset), ref msg);
		text2 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Z2_YOffset), ref msg);
		text3 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.XrefOffset), ref msg);
		text4 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.YrefOffset), ref msg);
		text5 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Z1GlobalOffset), ref msg);
		text6 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Z2GlobalOffset), ref msg);
		int result = 0;
		if (!int.TryParse(text3, out result))
		{
			result = 0;
		}
		num8 = (int)((double)result / 2.54);
		if (!int.TryParse(text4, out result))
		{
			result = 0;
		}
		num9 = (int)((double)result / 2.54);
		if (!int.TryParse(text, out result))
		{
			result = 0;
		}
		num6 = (int)((double)result / 2.54);
		if (!int.TryParse(text2, out result))
		{
			result = 0;
		}
		num7 = (int)((double)result / 2.54);
		if (!int.TryParse(s, out result))
		{
			s = "0";
			result = 0;
		}
		num3 = (int)((double)result / 2.54);
		if (!int.TryParse(s2, out result))
		{
			s2 = "0";
			result = 0;
		}
		num4 = (int)((double)result / 2.54);
		if (!int.TryParse(xLoc, out result))
		{
			msg = "X location is not a valid number";
			return false;
		}
		num = (int)((double)result / 2.54);
		if (useOffset)
		{
			num += num3;
		}
		if (actuator == "Z2")
		{
			num -= num6;
		}
		xLoc = (num + num8).ToString();
		if (!int.TryParse(yLoc, out result))
		{
			msg = "Y location is not a valid number";
			return false;
		}
		num2 = (int)((double)result / 2.54);
		if (useOffset)
		{
			num2 += num4;
		}
		if (actuator == "Z2")
		{
			num2 -= num7;
		}
		yLoc = (num2 + num9).ToString();
		if (!int.TryParse(zMax, out result))
		{
			result = 0;
			zMax = "0";
		}
		num5 = result;
		if (!int.TryParse(text5, out result))
		{
			result = 0;
		}
		num10 = result;
		if (!int.TryParse(text6, out result))
		{
			result = 0;
		}
		num11 = result;
		if (actuator.ToUpper() == "Z1")
		{
			num5 += num10;
		}
		else if (actuator.ToUpper() == "Z2")
		{
			num5 += num11;
		}
		zMax = num5.ToString();
		if (xLoc == "" || yLoc == "")
		{
			msg = "Error: Missing parameter.";
			return false;
		}
		return true;
	}

	public string getStringConfigItemValue(string itemName, ref string msg)
	{
		string value = "";
		msg = "";
		itemName = itemName.ToUpper();
		if (!setupItems.TryGetValue(itemName, out value))
		{
			msg = msg + "Section " + itemName + " is invalid. ";
			return "";
		}
		return value;
	}

	private bool CheckForKeepout(string x, string y)
	{
		double num = 0.0;
		double num2 = 0.0;
		double result = 0.0;
		string text = "";
		string text2 = "";
		string text3 = "";
		string text4 = "";
		string text5 = "";
		if (!double.TryParse(x, out result))
		{
			result = 0.0;
		}
		num = result;
		if (!double.TryParse(y, out result))
		{
			result = 0.0;
		}
		num2 = result;
		string name = Enum.GetName(typeof(xySETUP), xySETUP.Q1KEEPOUTX1);
		text = getStringConfigItemValue(name, ref text5);
		name = Enum.GetName(typeof(xySETUP), xySETUP.Q1KEEPOUTX2);
		text2 = getStringConfigItemValue(name, ref text5);
		name = Enum.GetName(typeof(xySETUP), xySETUP.Q1KEEPOUTY1);
		text3 = getStringConfigItemValue(name, ref text5);
		name = Enum.GetName(typeof(xySETUP), xySETUP.Q1KEEPOUTY2);
		text4 = getStringConfigItemValue(name, ref text5);
		if (!double.TryParse(text, out result))
		{
			result = -1.0;
		}
		double num3 = result;
		if (!double.TryParse(text2, out result))
		{
			result = -1.0;
		}
		double num4 = result;
		if (!double.TryParse(text3, out result))
		{
			result = -1.0;
		}
		double num5 = result;
		if (!double.TryParse(text4, out result))
		{
			result = -1.0;
		}
		double num6 = result;
		if (num6 * num5 * num3 * num4 < 0.0)
		{
			text5 = " Error: Could not convert a config item to double for keepout calc.";
			return false;
		}
		if (num > num3 && num < num4 && num2 > num5 && num2 < num6)
		{
			text5 = " Error: Keepout area will be violated.";
			return false;
		}
		return true;
	}

	public bool MoveToRefOffsetPoint(zACT actuator, string msg)
	{
		bool flag = false;
		double result = 0.0;
		double num = 0.0;
		double num2 = 0.0;
		double num3 = 0.0;
		double num4 = 0.0;
		string text = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.XrefOffset), ref msg);
		string text2 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.YrefOffset), ref msg);
		string stringConfigItemValue = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Z2_XOffset), ref msg);
		string stringConfigItemValue2 = getStringConfigItemValue(Enum.GetName(typeof(xySETUP), xySETUP.Z2_YOffset), ref msg);
		if (!double.TryParse(text, out result))
		{
			text = "0";
		}
		num = result;
		if (!double.TryParse(text2, out result))
		{
			text2 = "0";
		}
		num2 = result;
		if (actuator == zACT.LEVERPRESS)
		{
			if (!double.TryParse(stringConfigItemValue, out result))
			{
				text = "0";
			}
			num3 = result;
			if (!double.TryParse(stringConfigItemValue2, out result))
			{
				text2 = "0";
			}
			num4 = result;
			num -= num3;
			num2 -= num4;
			text = num.ToString();
			text2 = num2.ToString();
		}
		if (CheckForKeepout(text, text2))
		{
			flag = SendCommand(text + " qti_x \r\n");
			if (!flag)
			{
				msg = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
			flag &= SendCommand(text2 + " qti_y \r\n");
			if (!flag)
			{
				msg = "Error: Send command failed. COM Port may not be connected.";
				ioStat = IOSTAT.ERROR;
				return false;
			}
			if (waitForSerialCmd)
			{
				comPort.GetResponse();
			}
		}
		if (!flag)
		{
			msg = "Error moving to reference offset point";
		}
		return flag;
	}

	public bool setDimensionType()
	{
		bool flag = false;
		if (!((!isMetric) ? SendCommand("0 qti_setmode " + Environment.NewLine) : SendCommand("1 qti_setmode " + Environment.NewLine)))
		{
			msg = "Error: Send command failed. COM Port may not be connected.";
			ioStat = IOSTAT.ERROR;
			return false;
		}
		if (waitForSerialCmd)
		{
			comPort.GetResponse();
		}
		return true;
	}

	private bool AddNewListItem(string newName)
	{
		int num = -1;
		num = buttons.FindIndex((ButtonConfig item) => item.Name == newName);
		if (num < 0)
		{
			buttons.Add(new ButtonConfig
			{
				Name = newName,
				GridX = "",
				GridY = "",
				OffsetX = "",
				OffsetY = "",
				Zmax = "",
				Type = ""
			});
			return true;
		}
		return false;
	}

	protected bool SendCommand(string cmd)
	{
		if (cmd == "")
		{
			return false;
		}
		if (comPort.IsOpen())
		{
			if (!comPort.Send(cmd))
			{
				return false;
			}
			return true;
		}
		return false;
	}
}
