using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
using QC.CorpTest.Libraries.QsprSchemaLibrary;
using QC.QSPRAutomationInterface;
using QC.QTMDotNetKernelInterface;

namespace QC.TestExecutionLibrary;

[QTMTestClass]
public class TestExecutionLibrary
{
	public struct SingleTestParameter
	{
		public string TestName { get; set; }

		public string ParamName { get; set; }

		public object ParamValue { get; set; }
	}

	public struct AllTestParameter
	{
		public string ParamName { get; set; }

		public object ParamValue { get; set; }
	}

	public struct SingleTestTimeout
	{
		public string TestName { get; set; }

		public int TimeoutValue { get; set; }

		public bool UseRegex { get; set; }
	}

	public enum ErrorBehavior
	{
		None,
		Email,
		Popup
	}

	public struct ErrorEmail
	{
		public string FromAddress { get; set; }

		public string SMTPServerName { get; set; }

		public string ToAddress { get; set; }
	}

	public enum WindowLayout
	{
		None,
		Vertical,
		Horizontal
	}

	private const string TEMP_TREE_DIRECTORY = "C:\\TEMP\\IPSTREES\\";

	private const string TEMP_LOG_DIRECTORY = "C:\\TEMP\\LOGS\\";

	private const string LOG_FILE_LIST_DIRECTORY = "C:\\Qualcomm\\QDART\\Temp\\";

	private const string TEMPORARY_LOG_FILE = "C:\\Temp\\TemplogFile.xml";

	private const string LOG_FILE_MANIFEST = "C:\\Qualcomm\\QDART\\Temp\\LogFileList.txt";

	private const string LOG_FILE_HEADER_PREFIX = "<?xml-stylesheet href=\"file://s:\\Stylesheets\\";

	private const string LOG_FILE_HEADER_POSTFIX = "\" type=\"text/xsl\"?>";

	private AutoResetEvent TreeFinishedEvent = new AutoResetEvent(initialState: false);

	private string Parameters_For_Retry_Dummy;

	private string Parameters_For_Email_Dummy;

	private string Parameters_For_Database_Dummy;

	private static bool SHOW_DEBUG = true;

	private static string xmlRootHead = "<Root>";

	private static string xmlValueHead = "<NewValue>";

	private static string xmlRootTail = "</Root>";

	private static string xmlValueTail = "</NewValue>";

	public static Dictionary<string, string> DLL_LIST = new Dictionary<string, string>
	{
		{ "SubSysCDMA2000_NET.dll", "S:\\Set Up Files\\DLL Updates\\SubSysCDMA2000\\Latest" },
		{ "SubSysGSM_NET.dll", "S:\\Set Up Files\\DLL Updates\\SubSysGSM\\V4.00.xx" },
		{ "SubSysHDR_NET.dll", "S:\\Set Up Files\\DLL Updates\\SubSysHDR\\Latest" },
		{ "SubSysLTE_NET.dll", "S:\\Set Up Files\\DLL Updates\\SubSysLTE\\V01.00.xx" },
		{ "SubSysMultiMode_NET.dll", "S:\\Set Up Files\\DLL Updates\\SubSysMultiMode\\Latest" },
		{ "SubSysRFCalibration_1X_NET.dll", "S:\\Set Up Files\\DLL Updates\\SubSysRFCalibration\\RFCal_1X_4.0\\Latest" },
		{ "SubSysRFCal_NET.dll", "S:\\Set Up Files\\DLL Updates\\SubSysRFCalibration\\RFCalibration_1.0" },
		{ "SubSysTDSCDMA_NET.dll", "S:\\Set Up Files\\DLL Updates\\SubSysTDSCDMA\\Latest" },
		{ "SubSysWCDMA_NET.dll", "S:\\Set Up Files\\DLL Updates\\SubSysWCDMA\\V4.00.xx" },
		{ "TestExecutionLibrary.dll", "S:\\Set Up Files\\DLL Updates\\IPSTestPlan\\IPS_TestPlanExecution\\Latest" }
	};

	public static string DLL_PATH = "C:\\HTE\\Tools\\SUITE-3G-EV\\Bin";

	private string fromAddress;

	private string toAddress;

	private string message;

	private string subject;

	private string smtpServer;

	private string errMsg;

	private string LOG_FILE_HEADER = "<?xml-stylesheet href=\"file://s:\\Stylesheets\\html_Regular_3.0_.xsl\" type=\"text/xsl\"?>";

	public QC.QSPRAutomationInterface.Application qsprApp { get; set; }

	public string[] UUTID { get; set; }

	public string LoadedTreePath { get; set; }

	public string TestVBS { get; set; }

	public string LogDestination { get; set; }

	public string DebugDestination { get; set; }

	public static StreamWriter DebugOutputWriter { get; set; }

	public static Process CurrentQSPRProcess { get; set; }

	public List<SingleTestParameter> SingleTestParameterValues { get; set; }

	public List<AllTestParameter> AllTestParameterValues { get; set; }

	public List<SingleTestTimeout> SingleTestTimeouts { get; set; }

	public Dictionary<string, string> LogItemValues { get; set; }

	public double TestVoltage { get; set; }

	public int TestTemperature { get; set; }

	public bool CurrentTestAborted { get; set; }

	public bool TemperatureRun { get; set; }

	public int TreeTimeout { get; set; }

	public bool Superstation { get; set; }

	public bool HasTemperatureChamber { get; set; }

	public bool FinalizeLoggingRun { get; set; }

	public bool KillQPSTOnTestFinish { get; set; }

	public string StylesheetXML { get; set; }

	public ErrorBehavior TestErrorBehaviorMajor { get; set; }

	public ErrorBehavior TestErrorBehaviorMinor { get; set; }

	public ErrorEmail TestErrorEmail { get; set; }

	public WindowLayout TestWindowLayout { get; set; }

	public bool GNSSLogging { get; set; }

	[QTMParameter(ParameterIOType.Input, TestList = "Exec_RunTestTree", Description = "Parameters for Retrying")]
	public string Parameters_For_Retry
	{
		get
		{
			return Parameters_For_Retry_Dummy;
		}
		set
		{
			Parameters_For_Retry_Dummy = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, TestList = "Set_ErrorBehavior", Description = "Parameters for Email")]
	public string Parameters_For_Email
	{
		get
		{
			return Parameters_For_Email_Dummy;
		}
		set
		{
			Parameters_For_Email_Dummy = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, TestList = "Set_LogDestinations", Description = "Parameters for Database")]
	public string Parameters_For_Database
	{
		get
		{
			return Parameters_For_Database_Dummy;
		}
		set
		{
			Parameters_For_Database_Dummy = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, TestList = "Exec_SendEmail", DefaultValue = "", Description = "")]
	public string FromAddress
	{
		get
		{
			return fromAddress;
		}
		set
		{
			fromAddress = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, TestList = "Exec_SendEmail", DefaultValue = "", Description = "")]
	public string ToAddress
	{
		get
		{
			return toAddress;
		}
		set
		{
			toAddress = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, TestList = "Exec_SendEmail", DefaultValue = "", Description = "Email message")]
	public string MessageBody
	{
		get
		{
			return message;
		}
		set
		{
			message = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, TestList = "Exec_SendEmail", DefaultValue = "From QSPR")]
	public string Subject
	{
		get
		{
			return subject;
		}
		set
		{
			subject = value;
		}
	}

	[QTMParameter(ParameterIOType.Input, TestList = "Exec_SendEmail", DefaultValue = "smtphost.qualcomm.com", Description = "The SMTP mail server")]
	public string SMTPServerName
	{
		get
		{
			return smtpServer;
		}
		set
		{
			smtpServer = value;
		}
	}

	[QTMParameter(ParameterIOType.Output, TestList = "Exec_SendEmail")]
	public string ErrorString
	{
		get
		{
			return errMsg;
		}
		set
		{
			errMsg = value;
		}
	}

	private bool CloseTestTree(bool DeleteTree, string TreeName)
	{
		bool flag = false;
		if ((TreeName == null || TreeName.Length == 0) && CurrentQSPRProcess != null)
		{
			try
			{
				CurrentQSPRProcess.Kill();
				flag = true;
				CurrentQSPRProcess = null;
				TimeStampedDebugMessage("Killed QSPR");
			}
			catch (Exception ex)
			{
				TimeStampedDebugMessage("Exception in killing tree:\n" + ex.ToString());
			}
		}
		else
		{
			Process[] processesByName = Process.GetProcessesByName("QSPR");
			foreach (Process process in processesByName)
			{
				string mainWindowTitle = process.MainWindowTitle;
				if (mainWindowTitle.Contains(TreeName))
				{
					process.Kill();
					TimeStampedDebugMessage("Killed " + mainWindowTitle);
					flag = true;
				}
			}
		}
		if (DeleteTree && LoadedTreePath != null)
		{
			if (LoadedTreePath.Contains("C:\\TEMP\\IPSTREES\\"))
			{
				try
				{
					File.Delete(LoadedTreePath);
					TimeStampedDebugMessage("Deleted: " + LoadedTreePath);
				}
				catch (Exception)
				{
					TimeStampedDebugMessage("Failed to delete tree: " + LoadedTreePath);
				}
			}
			else
			{
				TimeStampedDebugMessage("Cannot delete tree in non-temporary directory.");
			}
		}
		if (!flag)
		{
			TimeStampedDebugMessage("No QSPR Killed: " + TreeName);
		}
		qsprApp = null;
		LoadedTreePath = null;
		return true;
	}

	[QTMTest("Reset any custom values set for the current test")]
	[QTMParameter(ArgumentName = "ParametersToClear", TestList = "Exec_ClearOverrides", Description = "[Optional] A comma delimited list of parameters to clear. If blank, all parameters will be cleared")]
	public bool Exec_ClearOverrides(string ParametersToClear)
	{
		if (string.IsNullOrWhiteSpace(ParametersToClear))
		{
			UUTID = null;
			TestVBS = null;
			SingleTestParameterValues = null;
			AllTestParameterValues = null;
			LogItemValues = null;
			DebugOutputWriter = null;
			TestVoltage = 0.0;
			TreeTimeout = 0;
			LogDestination = null;
			DebugDestination = null;
			DebugOutputWriter = null;
			TestErrorBehaviorMinor = ErrorBehavior.None;
			TestErrorBehaviorMajor = ErrorBehavior.None;
			TestWindowLayout = WindowLayout.None;
			HasTemperatureChamber = true;
			KillQPSTOnTestFinish = true;
			TimeStampedLogMessage("Overrides Cleared");
		}
		else
		{
			string[] separator = new string[1] { "," };
			List<string> ParamsToClear = new List<string>(ParametersToClear.Split(separator, StringSplitOptions.RemoveEmptyEntries));
			if (SingleTestParameterValues != null)
			{
				SingleTestParameterValues = SingleTestParameterValues.Where((SingleTestParameter x) => !ParamsToClear.Contains(x.ParamName)).ToList();
			}
			if (AllTestParameterValues != null)
			{
				AllTestParameterValues = AllTestParameterValues.Where((AllTestParameter x) => !ParamsToClear.Contains(x.ParamName)).ToList();
			}
		}
		return true;
	}

	[QTMTest("This node will make sure all file paths are valid. !!!DOES NOT DETECT UNSAVED CHANGES!!!")]
	[QTMParameter(ArgumentName = "HaltExecutionOnFailure", TestList = "Exec_CheckPaths", DisplayHint = DisplayHints.YESNO, DefaultValue = "0", Description = "If yes, throw an exception which will halt the tree if broken file paths are found.")]
	[QTMParameter(ArgumentName = "Description", TestList = "Exec_CheckPaths", DisplayHint = DisplayHints.ONOFF, DefaultValue = "0", Description = "This node will make sure all file paths are valid. !!!DOES NOT DETECT UNSAVED CHANGES!!!")]
	public bool Exec_CheckPaths(string Description, bool HaltExecutionOnFailure)
	{
		GlobalVariable.GetGlobalVariable("TreeFileName", out var gvValue);
		TimeStampedDebugMessage("Checking Execution Tree for valid file paths...");
		QC.QSPRAutomationInterface.Application application = new QC.QSPRAutomationInterface.Application(hideQSPRWindow: true, gvValue, null, -1, null);
		XTTDocument activeDocument = application.ActiveDocument;
		TestNode testNode = activeDocument.GetTestNode("");
		int num = 0;
		int num2 = 0;
		while (!IsNodeNull(testNode))
		{
			string text = testNode.GetTestPropertyValue("RealName", 1).ToString();
			if (text == "QC.TestExecutionLibrary.TestExecutionLibrary.Exec_RunTestTree")
			{
				num++;
				string text2 = testNode.GetTestParameterValue("FilePath", 1).ToString().Replace("\"", "");
				if (!File.Exists(text2))
				{
					if (num2 == 0)
					{
						TimeStampedDebugMessage("The following nodes have broken links:\n");
					}
					num2++;
					string text3 = testNode.GetTestPropertyValue("TestName", 1).ToString();
					string arg = text3;
					TestNode testNode2 = testNode;
					while (testNode2.GetParentFolder() != null)
					{
						arg = string.Format("{0} -> {1}", testNode2.GetTestPropertyValue("TestName", 1).ToString(), arg);
						testNode2 = testNode2.GetParentFolder();
					}
					string text4 = $"\nTest Name\t{text3}\nHierarchy\t{arg}\nTarget File\t{text2}\n";
					TimeStampedErrorMessage(text4);
				}
			}
			testNode = testNode.GetNextNode();
		}
		application.Exit();
		if (num2 == 0)
		{
			TimeStampedDebugMessage("No invalid tests found, all files exist!");
			return true;
		}
		TimeStampedDebugMessage($"\nTotal Execution Nodes\t{num}\nNodes w/invalid paths\t{num2}\n");
		if (HaltExecutionOnFailure)
		{
			throw new Exception("Broken file paths found. Halting execution.");
		}
		return false;
	}

	[QTMTest("Delete all temporarily generated XTT files")]
	public bool Exec_DeleteTemporaryTreeFiles()
	{
		string[] files = Directory.GetFiles("C:\\TEMP\\IPSTREES\\", "*.xtt");
		string[] array = files;
		foreach (string text in array)
		{
			try
			{
				File.Delete(text);
				TimeStampedDebugMessage("Deleted: " + text);
			}
			catch (Exception)
			{
				TimeStampedDebugMessage("Error in deleting: " + text);
			}
		}
		TimeStampedLogMessage("Temporary trees deleted");
		return true;
	}

	[QTMParameter(ArgumentName = "DeleteTreeOnFinish", TestList = "Exec_RunTestTree", Description = "If False, tree will not be deleted after execution completes", DefaultValue = "True")]
	[QTMTest("Execute the specified test tree")]
	[QTMParameter(ArgumentName = "HWLevel", TestList = "Exec_RunTestTree", Description = "The Hardware Level of the Test. May have multiple comma delimited (ie \"L2,L3\")", UnitOfMeasure = "L2, L3, or L4")]
	[QTMParameter(ArgumentName = "ExecuteAutomatically", TestList = "Exec_RunTestTree", Description = "If False, tree will load but user must start it", DefaultValue = "True")]
	[QTMParameter(ArgumentName = "CloseOnFinish", TestList = "Exec_RunTestTree", Description = "If False, QSPR will remain open after the last device completes", DefaultValue = "True")]
	[QTMParameter(ArgumentName = "FilePath", TestList = "Exec_RunTestTree", Description = "The full path to the VBS or XTT", DisplayHint = DisplayHints.FILE, UnitOfMeasure = "XTT or VBS")]
	[QTMParameter(ArgumentName = "UseGPSLogging", TestList = "Exec_RunTestTree", Description = "If True, multiple log files will be moved to the target location", DefaultValue = "False")]
	[QTMParameter(ArgumentName = "NumberRetries", TestList = "Exec_RunTestTree", Description = "The number of retries, if the pass percentage falls within a certain range", UnitOfMeasure = "OPTIONAL", ParentName = "Parameters_For_Retry")]
	[QTMParameter(ArgumentName = "MaxPassPercentageRetryThreshold", TestList = "Exec_RunTestTree", Description = "The maximum percentage threshold for retrying a test", UnitOfMeasure = "1-100", ParentName = "Parameters_For_Retry")]
	[QTMParameter(ArgumentName = "MinPassPercentageRetryThreshold", TestList = "Exec_RunTestTree", Description = "The minimum percentage threshold for retrying a test", UnitOfMeasure = "1-100", ParentName = "Parameters_For_Retry")]
	[QTMParameter(ArgumentName = "SubstituteForVBS", TestList = "Exec_RunTestTree", Description = "The path to a VBS or XTT which will \"impersonate\" the file specified by FilePath", DisplayHint = DisplayHints.FILE, UnitOfMeasure = "XTT or VBS")]
	public bool Exec_RunTestTree(string FilePath, string HWLevel, bool ExecuteAutomatically, bool CloseOnFinish, bool DeleteTreeOnFinish, bool UseGPSLogging, int NumberRetries, int MaxPassPercentageRetryThreshold, int MinPassPercentageRetryThreshold, string SubstituteForVBS, out int durationSeconds, out string finishedLogFiles)
	{
		durationSeconds = 0;
		finishedLogFiles = null;
		bool flag = false;
		if (UUTID == null)
		{
			HandleErrorMessage("Failure: No UUT IDs found", isMajor: true);
			return false;
		}
		if (!string.IsNullOrWhiteSpace(SubstituteForVBS))
		{
			string text = SubstituteForVBS;
			SubstituteForVBS = FilePath;
			FilePath = text;
			Set_CustomLogItem("SubstituteForVBS", SubstituteForVBS);
		}
		else if (LogItemValues != null && LogItemValues.ContainsKey("SubstituteForVBS"))
		{
			LogItemValues.Remove("SubstituteForVBS");
		}
		if (FilePath != null && FilePath.Length != 0)
		{
			FilePath = FilePath.Replace("\"", "");
			if (!File.Exists(FilePath))
			{
				HandleErrorMessage("Failure: The file \"" + FilePath + "\" was not found", isMajor: false);
				return false;
			}
			if (!TemperatureRun && TestTemperature == 0)
			{
				TestTemperature = 25;
			}
			Set_CustomLogItem("SourceFile", FilePath);
			Set_CustomLogItem("MachineName", Environment.MachineName);
			string fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
			Set_CustomLogItem("ExecutionDLLVersion", fileVersion);
			GlobalVariable.GetGlobalVariable("TreeFileName", out var gvValue);
			gvValue = Path.GetFileName(gvValue);
			Set_CustomLogItem("ExecutionTree", gvValue);
			if (Path.GetExtension(FilePath).ToLower() == ".vbs")
			{
				int exitCode = 0;
				string xttPath = null;
				flag = true;
				int num = 1;
				while (num >= 0)
				{
					num--;
					try
					{
						if (!LoadTestTreeFromVBS(FilePath, out xttPath, out exitCode))
						{
							HandleErrorMessage("Unable to get tree generated by VBS: " + FilePath, isMajor: true);
							return false;
						}
					}
					catch (Exception ex)
					{
						TimeStampedDebugMessage("VBS Exception");
						TimeStampedDebugMessage(ex.ToString());
						return false;
					}
					if (exitCode != 2)
					{
						break;
					}
				}
				switch (exitCode)
				{
				case 0:
					TimeStampedDebugMessage("Exit code 0, clean tree");
					break;
				case 1:
					HandleErrorMessage("Exit code 1, VBS has errors. Continuing execution.", isMajor: false);
					break;
				case 2:
					HandleErrorMessage("Exit code 2, Perforce tree load failure", isMajor: true);
					return false;
				}
				LoadedTreePath = xttPath;
			}
			else
			{
				if (!(Path.GetExtension(FilePath).ToLower() == ".xtt"))
				{
					HandleErrorMessage("Failure: Invalid extension \"" + Path.GetExtension(FilePath).ToLower() + "\". Please specify an XTT or VBS file", isMajor: false);
					return false;
				}
				flag = true;
				try
				{
					string text2 = Path.Combine("C:\\TEMP\\IPSTREES\\", Path.GetFileName(FilePath));
					if (!Directory.Exists("C:\\TEMP\\IPSTREES\\"))
					{
						Directory.CreateDirectory("C:\\TEMP\\IPSTREES\\");
					}
					QC.QSPRAutomationInterface.Application application = new QC.QSPRAutomationInterface.Application(hideQSPRWindow: true, FilePath, null, -1, null);
					application.ActiveDocument.SaveAsQSPRFormat(text2);
					application.Exit();
					FilePath = text2;
					if (!File.Exists(FilePath))
					{
						throw new Exception("File not found");
					}
					TimeStampedDebugMessage("Copied XTT to temporary path: " + FilePath);
				}
				catch (Exception)
				{
					HandleErrorMessage("Failure: Failed to copy XTT to temporary directory", isMajor: false);
					return false;
				}
				LoadedTreePath = FilePath;
			}
			UnsetReadOnly(LoadedTreePath);
			string productVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;
			DebugMessage.Write("Log", "---------------------------------------------------------");
			DebugMessage.Write("Log", "Test Execution DLL " + productVersion);
			DebugMessage.Write("Log", "---------------------------------------------------------");
			TimeStampedLogMessage("Using XTT: " + LoadedTreePath);
			bool flag2 = true;
			List<string> list = new List<string>();
			for (int i = 0; i < UUTID.Length; i++)
			{
				if (UUTID[i] == null || UUTID[i].Length == 0)
				{
					continue;
				}
				UUTIDStatus(UUTID, i);
				if (DebugDestination != null && DebugDestination.Length != 0)
				{
					try
					{
						DebugOutputWriter = GenerateDebugFile(DebugDestination, UUTID[i]);
					}
					catch (Exception ex3)
					{
						TimeStampedDebugMessage("Fatal error generating debug output writer");
						TimeStampedDebugMessage(ex3.ToString());
					}
				}
				bool flag3 = true;
				string bestRetestLogFile = null;
				while (flag3)
				{
					if (CurrentQSPRProcess != null)
					{
						string loadedTreePath = LoadedTreePath;
						CloseTestTree(DeleteTree: false, null);
						LoadedTreePath = loadedTreePath;
					}
					Process[] processesByName = Process.GetProcessesByName("QSPR");
					TimeStampedDebugMessage("Launching tree with path: " + LoadedTreePath);
					DateTime now = DateTime.Now;
					qsprApp = new QC.QSPRAutomationInterface.Application(hideQSPRWindow: true, LoadedTreePath, "Green", -1, null);
					Process[] processesByName2 = Process.GetProcessesByName("QSPR");
					CurrentQSPRProcess = processDiff(processesByName, processesByName2);
					if (CurrentQSPRProcess != null)
					{
						TimeStampedDebugMessage("Got current QSPR Process: " + CurrentQSPRProcess.Id);
					}
					else
					{
						TimeStampedDebugMessage("Could not get current QSPR Process");
					}
					XTTDocument activeDocument = qsprApp.ActiveDocument;
					qsprApp.EnableRegexSupport = 0;
					List<string> list2 = new List<string>();
					TimeStampedLogMessage("Using UUT ID [" + i + "] " + UUTID[i]);
					if (activeDocument.SetUUTId(i, UUTID[i]) == 0)
					{
						list2.Add("Error setting UUT ID: [" + i + "] " + UUTID[i]);
					}
					if (flag)
					{
						try
						{
							Set_CustomLogItem("Temperature", TestTemperature.ToString());
							Set_CustomLogItem("Voltage", TestVoltage.ToString());
							if (string.IsNullOrWhiteSpace(HWLevel))
							{
								Clear_CustomLogItem("HWLevel");
							}
							else
							{
								Set_CustomLogItem("HWLevel", HWLevel);
							}
							TimeStampedDebugMessage("Performing Overrides:");
							list2.AddRange(setCustomTestValues(activeDocument));
							flag = false;
						}
						catch (Exception ex4)
						{
							list2.Add("Fatal setting custom test values: " + ex4.ToString());
						}
					}
					string text3 = string.Empty;
					if (GNSSLogging)
					{
						UseGPSLogging = true;
					}
					if (UseGPSLogging)
					{
						text3 = setGPSLogDestination(activeDocument);
					}
					if (list2.Count > 0)
					{
						string text4 = "The following errors were encountered:";
						foreach (string item in list2)
						{
							text4 = text4 + "\n" + item;
						}
						if (TestErrorBehaviorMinor == ErrorBehavior.Popup)
						{
							text4 += "\n\nDo you want to ignore these errors and run anyway?";
							if (MessageBox.Show(text4, "Test Tree Errors", MessageBoxButtons.YesNo) != DialogResult.Yes)
							{
								try
								{
									qsprApp.Exit();
								}
								catch (Exception)
								{
								}
								qsprApp = null;
								durationSeconds = durationSeconds;
								return false;
							}
						}
						else
						{
							HandleErrorMessage(text4, isMajor: false);
						}
					}
					qsprApp.MinimizeApp = 0;
					minimizeQSPR(LoadedTreePath);
					int num2 = RunWatchStatus(activeDocument, ExecuteAutomatically);
					DateTime now2 = DateTime.Now;
					durationSeconds += (int)(now2 - now).TotalSeconds;
					if (KillQPSTOnTestFinish)
					{
						KillAllQPST();
					}
					if (CurrentTestAborted)
					{
						TimeStampedDebugMessage("Test was aborted. Likely timed out.");
					}
					string qsprLogFile = GetQsprLogFilePath();
					bool flag4 = true;
					if (!FinalizeLoggingRun || qsprLogFile == null || qsprLogFile.Length == 0 || !File.Exists(qsprLogFile))
					{
						flag4 = false;
					}
					string text5 = null;
					int num3 = 0;
					if (UseGPSLogging && !string.IsNullOrWhiteSpace(text3))
					{
						TimeStampedDebugMessage("Moving GPS Log files: " + text3);
						ValidateLogDestination();
						string[] directories = Directory.GetDirectories(text3, "*", SearchOption.AllDirectories);
						for (int j = 0; j < directories.Length; j++)
						{
							_ = directories[j];
							FixGPSLogFolder(text3);
						}
						string[] directories2 = Directory.GetDirectories(text3, "*", SearchOption.AllDirectories);
						foreach (string text6 in directories2)
						{
							string path = text6.Replace(text3, "");
							string text7 = Path.Combine(LogDestination, path);
							if (!Directory.Exists(text7))
							{
								TimeStampedDebugMessage($"Creating Directory: {text7}");
								Directory.CreateDirectory(text7);
							}
							else
							{
								TimeStampedDebugMessage($"Directory Exists: {text7}");
							}
						}
						string[] files = Directory.GetFiles(text3, "*.*", SearchOption.AllDirectories);
						foreach (string text8 in files)
						{
							string path2 = text8.Replace(text3, "");
							string text9 = Path.Combine(LogDestination, path2);
							try
							{
								File.Copy(text8, text9);
								TimeStampedDebugMessage($"Copied file {text8} to {text9}");
							}
							catch (Exception ex6)
							{
								TimeStampedDebugMessage($"Failure copying file {text8} to {text9}: {ex6.ToString()}");
							}
						}
					}
					else if (GNSSLogging)
					{
						try
						{
							TimeStampedDebugMessage("Skipping processing for GNSS log file: " + qsprLogFile);
						}
						catch
						{
						}
					}
					else if (flag4)
					{
						try
						{
							TimeStampedDebugMessage("Moving local log file: " + qsprLogFile);
							prependXMLHeader(qsprLogFile);
							text5 = moveLogFile(ref qsprLogFile, Path.GetFileNameWithoutExtension(LoadedTreePath), ref bestRetestLogFile, durationSeconds);
							num3 = getPassPercentage(qsprLogFile);
							TimeStampedDebugMessage("Finished moving local log file: " + qsprLogFile);
							if (!File.Exists(text5))
							{
								TimeStampedDebugMessage("Log move failure. File does not exist: " + text5);
							}
							else
							{
								string unMappedPath = getUnMappedPath(text5);
								if (unMappedPath != null)
								{
									text5 = unMappedPath;
								}
								try
								{
									LogFileEntry(text5);
								}
								catch (Exception ex7)
								{
									TimeStampedDebugMessage("Failure in writing aggregate log file: \\n" + ex7.ToString());
								}
								if (bestRetestLogFile == null)
								{
									bestRetestLogFile = text5;
								}
							}
						}
						catch (Exception ex8)
						{
							TimeStampedDebugMessage("Log file move error:\n" + ex8.ToString());
							flag4 = false;
						}
					}
					DebugMessage.Write("Log", "--------------");
					DebugMessage.Write("Log", "| Results |");
					DebugMessage.Write("Log", "--------------");
					DebugMessage.Write("Log", "Started : " + now);
					DebugMessage.Write("Log", "Finished : " + now2);
					DebugMessage.Write("Log", "Duration : " + durationSeconds + " seconds");
					DebugMessage.Write("Log", "Result : Tree " + QSPRStatusString(num2));
					if (num3 != -1)
					{
						DebugMessage.Write("Log", "Pass % : " + num3);
					}
					if (UseGPSLogging && !string.IsNullOrWhiteSpace(text3))
					{
						DebugMessage.Write("Log", "GPS log file processing was used for this test");
					}
					else if (GNSSLogging)
					{
						DebugMessage.Write("Log", "Log file processing was disabled for this test (GNSS)");
					}
					else
					{
						if (qsprLogFile != null && File.Exists(qsprLogFile))
						{
							DebugMessage.Write("Log", "Original Log : " + qsprLogFile);
						}
						else
						{
							DebugMessage.Write("Log", "No Log File found for UUT ID " + i);
						}
						if (text5 != null && File.Exists(text5))
						{
							DebugMessage.Write("Log", "Moved Log : " + text5);
						}
						else
						{
							DebugMessage.Write("Log", "Failed to move log file");
							text5 = null;
						}
					}
					if (num2 != 6)
					{
						flag2 = false;
					}
					if (!flag2 && NumberRetries > 0 && num3 <= MaxPassPercentageRetryThreshold && num3 >= MinPassPercentageRetryThreshold)
					{
						NumberRetries--;
						flag3 = true;
						DebugMessage.Write("Log", "Threshold : " + MinPassPercentageRetryThreshold + " < " + num3 + " < " + MaxPassPercentageRetryThreshold);
						DebugMessage.Write("Log", "Retest: Retesting. " + NumberRetries + " remaining");
					}
					else
					{
						flag3 = false;
						list.Add(bestRetestLogFile);
						bestRetestLogFile = null;
						DebugMessage.Write("Log", "Retest : No retest");
						list.Add(text5);
					}
				}
				if (DebugOutputWriter != null)
				{
					try
					{
						DebugMessage.Write("Log", "Debug Log: " + ((FileStream)DebugOutputWriter.BaseStream).Name);
						DebugOutputWriter.Close();
						DebugOutputWriter = null;
					}
					catch (Exception ex9)
					{
						TimeStampedLogMessage("Error in creating debug log file:");
						TimeStampedLogMessage(ex9.ToString());
					}
				}
			}
			if (CloseOnFinish)
			{
				CloseTestTree(DeleteTreeOnFinish, null);
			}
			finishedLogFiles = string.Join(";", list.ToArray());
			return flag2;
		}
		HandleErrorMessage("Failure: No file provided", isMajor: false);
		return false;
	}

	[QTMParameter(ArgumentName = "emailSMTPServerName", TestList = "Set_ErrorBehavior", DefaultValue = "smtphost.qualcomm.com", Description = "The SMTP mail server", UnitOfMeasure = "EMAIL ONLY", ParentName = "Parameters_For_Email")]
	[QTMParameter(ArgumentName = "emailFromAddress", TestList = "Set_ErrorBehavior", DefaultValue = "", Description = "", UnitOfMeasure = "EMAIL ONLY", ParentName = "Parameters_For_Email")]
	[QTMParameter(ArgumentName = "BehaviorMajor", TestList = "Set_ErrorBehavior", DisplayHint = DisplayHints.ENUM_LIST, DefaultValue = "0", Description = "")]
	[QTMTest("Set the error behavior")]
	[QTMParameter(ArgumentName = "BehaviorMinor", TestList = "Set_ErrorBehavior", DisplayHint = DisplayHints.ENUM_LIST, DefaultValue = "0", Description = "")]
	[QTMParameter(ArgumentName = "emailToAddress", TestList = "Set_ErrorBehavior", DefaultValue = "", Description = "", UnitOfMeasure = "EMAIL ONLY", ParentName = "Parameters_For_Email")]
	public bool Set_ErrorBehavior(ErrorBehavior BehaviorMajor, ErrorBehavior BehaviorMinor, string emailFromAddress, string emailSMTPServerName, string emailToAddress)
	{
		TestErrorBehaviorMajor = BehaviorMajor;
		TestErrorBehaviorMinor = BehaviorMinor;
		if (TestErrorBehaviorMajor == ErrorBehavior.Email || TestErrorBehaviorMinor == ErrorBehavior.Email)
		{
			ErrorEmail testErrorEmail = default(ErrorEmail);
			testErrorEmail.FromAddress = emailFromAddress;
			testErrorEmail.SMTPServerName = emailSMTPServerName;
			testErrorEmail.ToAddress = emailToAddress;
			TestErrorEmail = testErrorEmail;
		}
		return true;
	}

	[QTMParameter(ArgumentName = "KillQPSTAfterEachTest", TestList = "Exec_RunTestTree", Description = "Whether or not to kill QPST after each test", DefaultValue = "True")]
	[QTMParameter(ArgumentName = "WindowArrangement", TestList = "Exec_RunTestTree", Description = "How the windows will be rearranged when the test is run", DisplayHint = DisplayHints.ENUM_LIST, DefaultValue = "2")]
	public bool Set_GeneralSettings(WindowLayout WindowArrangement, bool KillQPSTAfterEachTest)
	{
		TestWindowLayout = WindowArrangement;
		KillQPSTOnTestFinish = KillQPSTAfterEachTest;
		return true;
	}

	[QTMParameter(ArgumentName = "TreePath", Description = "The path to the temperature tree", UnitOfMeasure = "OPTIONAL")]
	[QTMParameter(ArgumentName = "hidden", Description = "True - Hide QSPR, False - Show QSPR", DefaultValue = "False")]
	[QTMTest("Set the temperature")]
	[QTMParameter(ArgumentName = "closeOnExit", Description = "If False, tree will remain open after finishing.", DefaultValue = "True")]
	[QTMParameter(ArgumentName = "hasTemperatureChamber", Description = "True - This station has a temperature chamber, False - This station has no temperature chamber", DefaultValue = "True")]
	[QTMParameter(ArgumentName = "degreesCelsius", Description = "The temperature", UnitOfMeasure = "Degrees (Celsius)")]
	[QTMParameter(ArgumentName = "soakTimeMinutes", Description = "The soak time", DefaultValue = "30", UnitOfMeasure = "Minutes")]
	public bool Set_Temperature(bool hasTemperatureChamber, int degreesCelsius, int soakTimeMinutes, bool hidden, bool closeOnExit, string TreePath)
	{
		TimeStampedDebugMessage("Setting Temperature");
		TestTemperature = degreesCelsius;
		TemperatureRun = true;
		HasTemperatureChamber = hasTemperatureChamber;
		if (!hasTemperatureChamber)
		{
			TimeStampedLogMessage("Unit has no temperature chamber, skipping test");
			return true;
		}
		TimeStampedDebugMessage("Checking QSPR Processes");
		Process[] processesByName = Process.GetProcessesByName("QSPR");
		TimeStampedDebugMessage("Launching QSPR");
		qsprApp = new QC.QSPRAutomationInterface.Application(hidden);
		TimeStampedDebugMessage("Checking QSPR Processes");
		Process[] processesByName2 = Process.GetProcessesByName("QSPR");
		Process process = processDiff(processesByName, processesByName2);
		TimeStampedDebugMessage("Got Temperature Tree Process: " + process.Id);
		XTTDocument xTTDocument = qsprApp.NewXTT();
		xTTDocument.DeleteTest("StartUp");
		xTTDocument.AddSUITEDll("C:\\HTE\\Tools\\SUITE-3G-EV\\Bin\\SubSysGSM_NET.dll");
		TestNode testNode = xTTDocument.GetTestNode("");
		TestNode testNode2 = testNode.CreateFolder("TimeOut " + soakTimeMinutes + "minutes");
		testNode2.AddTest("CGSM_GetUUTID", "Get UUT ID");
		testNode2.AddTest("CGSM_SwitchRFPath", "CGSM_SwitchRFPath");
		TestNode testNode3 = testNode2.AddTest("CGSM_QDARTInitializeDataLogging", "QDARTInit");
		testNode3.SetTestProperty("TreeMustRun", "True");
		TestNode testNode4 = testNode2.AddTest("CGSM_QDARTFinalizeDataLogging", "QDARTFinalize");
		testNode4.SetTestProperty("TreeMustRun", "True");
		testNode4.SetTestParameter("Use Fixed LogFile Path Name", 1, null, null);
		testNode4.SetTestParameter("File Path Name", "C:\\TEMP\\LOGS\\", null, null);
		testNode4.SetTestParameter("Stylesheet list", "html_Regular_3.0_.xsl", null, null);
		TestNode testNode5 = testNode3.CreateFolder("Set Temperature");
		TestNode testNode6 = testNode5.AddTest("CGSM_ConfigTemperature", "Set_Temperature_" + degreesCelsius + "C");
		testNode6.SetTestParameter("Temperature:SoakTime", degreesCelsius + ":0", null, null);
		testNode6.SetTestParameter("Temperature Tolerance", 5, null, null);
		testNode6.SetTestParameter("Temperature Setting Timeout", 30, null, null);
		TestNode testNode7 = testNode5.AddTest("CGSM_ConfigTemperature", "Soak_" + soakTimeMinutes + "_Min");
		testNode7.SetTestParameter("Temperature:SoakTime", degreesCelsius + ":" + soakTimeMinutes, null, null);
		testNode7.SetTestParameter("Temperature Tolerance", 5, null, null);
		testNode7.SetTestParameter("Temperature Setting Timeout", 30, null, null);
		ValidateLogDestination();
		TimeStampedLogMessage("Superstation: " + Superstation);
		string text = "Temperature";
		if (Superstation)
		{
			xTTDocument.SetUUTId(1, text);
		}
		else
		{
			xTTDocument.SetUUTId(0, text);
		}
		string text2 = Path.Combine("C:\\TEMP\\LOGS\\", "GSM__Temp__" + degreesCelsius + "C__X0__GSM4.0.xtt");
		if (File.Exists(text2))
		{
			try
			{
				File.Delete(text2);
			}
			catch
			{
			}
		}
		xTTDocument.SaveAsQSPRFormat(text2);
		int num = RunWatchStatus(xTTDocument, ExecuteImmediately: true);
		string text3 = GetQsprLogFilePath(text, "C:\\TEMP\\LOGS\\");
		ValidateLogDestination();
		try
		{
			string text4 = Path.Combine("C:\\TEMP\\LOGS\\", "Temperature");
			Directory.CreateDirectory(text4);
			text4 = Path.Combine(text4, Path.GetFileName(text3));
			if (!text4.Equals(text3))
			{
				File.Copy(text3, text4, overwrite: true);
				text3 = text4;
			}
			TimeStampedLogMessage("Temperature Log File: " + text3);
		}
		catch (Exception ex)
		{
			if (text3 == null)
			{
				text3 = "NULL";
			}
			TimeStampedLogMessage("Could not copy temperature log file: " + text3);
			TimeStampedLogMessage(ex.ToString());
		}
		prependXMLHeader(text3);
		if (closeOnExit)
		{
			try
			{
				process.Kill();
				TimeStampedDebugMessage("Killed temperature tree successfully");
			}
			catch
			{
			}
		}
		qsprApp = null;
		bool flag = num == 6;
		if (flag)
		{
			TimeStampedLogMessage("Temperature Tree SUCCESS");
		}
		else
		{
			TimeStampedLogMessage("Temperature Tree FAILURE");
		}
		return flag;
	}

	[QTMTest("Set the voltage")]
	[QTMParameter(ArgumentName = "voltage", Description = "The voltage", UnitOfMeasure = "V")]
	public bool Set_Voltage(double voltage)
	{
		TestVoltage = voltage;
		return true;
	}

	[QTMTest("Set the timeout for the entire tree")]
	[QTMParameter(ArgumentName = "TimeoutSeconds", Description = "Seconds before timeout", UnitOfMeasure = "Seconds")]
	[QTMParameter(ArgumentName = "TimeoutMinutes", Description = "Minutes before timeout", UnitOfMeasure = "Minutes")]
	public bool Set_Timeout_Tree(int TimeoutMinutes, int TimeoutSeconds)
	{
		TreeTimeout = TimeoutMinutes * 60 + TimeoutSeconds;
		return true;
	}

	[QTMParameter(ArgumentName = "testName", Description = "The test name")]
	[QTMParameter(ArgumentName = "timeout", Description = "The timeout", UnitOfMeasure = "Minutes")]
	[QTMTest("Set a timeout for a specific test")]
	public bool Set_Timeout_Test(string testName, int timeout)
	{
		if (SingleTestTimeouts == null)
		{
			SingleTestTimeouts = new List<SingleTestTimeout>();
		}
		if (testName.Length != 0)
		{
			SingleTestTimeout item = default(SingleTestTimeout);
			item.TestName = testName;
			item.TimeoutValue = timeout * 60;
			item.UseRegex = false;
			SingleTestTimeouts.Add(item);
			return true;
		}
		if (testName.Length == 0)
		{
			DebugMessage.Write("Log", "Could not set test parameter, Test Name was empty");
		}
		return false;
	}

	[QTMTest("Set a timeout for the test \"*Init*BSE*\"")]
	[QTMParameter(ArgumentName = "timeout", Description = "The timeout", UnitOfMeasure = "Minutes")]
	public bool Set_Timeout_InitBSE(int timeout)
	{
		if (SingleTestTimeouts == null)
		{
			SingleTestTimeouts = new List<SingleTestTimeout>();
		}
		SingleTestTimeout item = default(SingleTestTimeout);
		item.TestName = "(.*)Init(.*)BSE(.*)";
		item.TimeoutValue = timeout * 60;
		item.UseRegex = true;
		SingleTestTimeouts.Add(item);
		return true;
	}

	[QTMParameter(ArgumentName = "timeout", Description = "The timeout", UnitOfMeasure = "Minutes")]
	[QTMTest("Set a timeout for the test \"Set Phone Online\"")]
	public bool Set_Timeout_SetPhoneOnline(int timeout)
	{
		if (SingleTestTimeouts == null)
		{
			SingleTestTimeouts = new List<SingleTestTimeout>();
		}
		SingleTestTimeout item = default(SingleTestTimeout);
		item.TestName = "Set Phone Online";
		item.TimeoutValue = timeout * 60;
		item.UseRegex = false;
		SingleTestTimeouts.Add(item);
		return true;
	}

	[QTMParameter(ArgumentName = "timeout", Description = "The timeout", UnitOfMeasure = "Minutes")]
	[QTMTest("Set a timeout for the test \"*Wait*For*Registration*\"")]
	public bool Set_Timeout_WaitForRegistration(int timeout)
	{
		if (SingleTestTimeouts == null)
		{
			SingleTestTimeouts = new List<SingleTestTimeout>();
		}
		SingleTestTimeout item = default(SingleTestTimeout);
		item.TestName = "(.*)Wait(.*)For(.*)Registration(.*)";
		item.TimeoutValue = timeout * 60;
		item.UseRegex = true;
		SingleTestTimeouts.Add(item);
		return true;
	}

	[QTMParameter(ArgumentName = "timeout", Description = "The timeout", UnitOfMeasure = "Minutes")]
	[QTMTest("Set a timeout for the test \"*Start*Call*\"")]
	public bool Set_Timeout_StartCall(int timeout)
	{
		if (SingleTestTimeouts == null)
		{
			SingleTestTimeouts = new List<SingleTestTimeout>();
		}
		SingleTestTimeout item = default(SingleTestTimeout);
		item.TestName = "(.*)Start(.*)Call(.*)";
		item.TimeoutValue = timeout * 60;
		item.UseRegex = true;
		SingleTestTimeouts.Add(item);
		return true;
	}

	[QTMParameter(ArgumentName = "paramValue", Description = "The parameter value")]
	[QTMParameter(ArgumentName = "paramName", Description = "The parameter name")]
	[QTMParameter(ArgumentName = "testName", Description = "The test name")]
	[QTMTest("Change a parameter in the currently initialized test tree ")]
	public bool Set_TestParameter(string testName, string paramName, string paramValue)
	{
		if (SingleTestParameterValues == null)
		{
			SingleTestParameterValues = new List<SingleTestParameter>();
		}
		if (testName.Length != 0 && paramName.Length != 0 && paramValue != null)
		{
			SingleTestParameter item = default(SingleTestParameter);
			item.TestName = testName;
			item.ParamName = paramName;
			item.ParamValue = paramValue;
			SingleTestParameterValues.Add(item);
			return true;
		}
		if (testName.Length == 0)
		{
			DebugMessage.Write("Log", "Could not set test parameter, Test Name was empty");
		}
		else if (paramName.Length == 0)
		{
			DebugMessage.Write("Log", "Could not set test parameter, Param Name was empty");
		}
		else if (paramValue == null)
		{
			DebugMessage.Write("Log", "Could not set test parameter, Param Value was empty");
		}
		return false;
	}

	[QTMParameter(ArgumentName = "paramName", Description = "The parameter name")]
	[QTMParameter(ArgumentName = "paramValue", Description = "The parameter value")]
	[QTMTest("Change a parameter for all tests in the currently initialized test tree")]
	public bool Set_TestParameterAll(string paramName, string paramValue)
	{
		if (AllTestParameterValues == null)
		{
			AllTestParameterValues = new List<AllTestParameter>();
		}
		if (paramName.Length != 0 && paramValue != null)
		{
			AllTestParameter item = default(AllTestParameter);
			item.ParamName = paramName;
			item.ParamValue = paramValue;
			AllTestParameterValues.Add(item);
			return true;
		}
		if (paramName.Length == 0)
		{
			DebugMessage.Write("Log", "Could not set test parameter, Param Name was empty");
		}
		else if (paramValue == null)
		{
			DebugMessage.Write("Log", "Could not set test parameter, Param Value was empty");
		}
		return false;
	}

	[QTMParameter(ArgumentName = "RFVariant", TestList = "Set_LogDestinations", Description = "The RF Variant tested for the current test session (eg EU)", UnitOfMeasure = "OPTIONAL")]
	[QTMParameter(ArgumentName = "DebugOutputDirectory", TestList = "Set_LogDestinations", Description = "The output directory for the debug log", UnitOfMeasure = "OPTIONAL")]
	[QTMParameter(ArgumentName = "XMLOutputDirectory", TestList = "Set_LogDestinations", Description = "The output directory for the QSPR XML log")]
	[QTMParameter(ArgumentName = "DataType", TestList = "Set_LogDestinations", Description = "The Data Type for the current test session (eg DataPacket#1)", UnitOfMeasure = "OPTIONAL")]
	[QTMParameter(ArgumentName = "SWBuild", TestList = "Set_LogDestinations", Description = "The SW build for the current test session (eg MetaBuildxxx_RFPLFxxx)", UnitOfMeasure = "OPTIONAL")]
	[QTMParameter(ArgumentName = "ProjectName", TestList = "Set_LogDestinations", Description = "The project name for the current test session (eg MTP8x30_WTR1605)", UnitOfMeasure = "OPTIONAL", ParentName = "Parameters_For_Database")]
	[QTMParameter(ArgumentName = "TestPlanName", TestList = "Set_LogDestinations", Description = "The name of the test plan, must match an existing test plan", UnitOfMeasure = "RECOMMENDED", ParentName = "Parameters_For_Database")]
	[QTMTest("Set the output directories for log files")]
	public bool Set_LogDestinations(string XMLOutputDirectory, string DebugOutputDirectory, string RFVariant, string DataType, string SWBuild, string ProjectName, string TestPlanName)
	{
		LogDestination = XMLOutputDirectory;
		TimeStampedDebugMessage("Log destination is: " + LogDestination);
		if (LogDestination == null || LogDestination == string.Empty)
		{
			Exec_MessageBox("DATA LOSS", "Path given was empty. Execution will now terminate. Please restart testing after entering a valid log destination.");
			throw new Exception("Empty path given");
		}
		string pathRoot = Path.GetPathRoot(LogDestination);
		TimeStampedDebugMessage("Root of destination is: " + pathRoot);
		if (!pathRoot.StartsWith("\\\\"))
		{
			TimeStampedDebugMessage("Drive letter detected, possibly mapped");
			if (!Directory.Exists(pathRoot))
			{
				Exec_MessageBox("POSSIBLE DATA LOSS", "Could not locate root of path \"" + pathRoot + "\". Execution will now terminate. Please restart testing after entering a valid log destination.");
				throw new Exception("Drive letter not found");
			}
		}
		DebugDestination = DebugOutputDirectory;
		Set_CustomLogItem("TestPlanName", TestPlanName);
		Set_CustomLogItem("ProjectName", ProjectName);
		Set_CustomLogItem("RFVariant", RFVariant);
		Set_CustomLogItem("DataType", DataType);
		Set_CustomLogItem("SWBuild", SWBuild);
		return true;
	}

	[QTMParameter(ArgumentName = "logItemName", Description = "The name of the log item")]
	[QTMParameter(ArgumentName = "logItemValue", Description = "The value of the log item")]
	[QTMTest("Add a custom log item in the tree to be run")]
	public bool Set_CustomLogItem(string logItemName, string logItemValue)
	{
		if (logItemValue == null || logItemValue.Length == 0)
		{
			TimeStampedDebugMessage("Failed to add log item for " + logItemName + ", value is null");
			return false;
		}
		if (LogItemValues == null)
		{
			LogItemValues = new Dictionary<string, string>();
		}
		if (LogItemValues.ContainsKey(logItemName))
		{
			DebugMessage.Write("Log", "Overwriting existing value for " + logItemName);
		}
		LogItemValues[logItemName] = logItemValue;
		return true;
	}

	private void Clear_CustomLogItem(string logItemName)
	{
		if (LogItemValues != null && !string.IsNullOrWhiteSpace(logItemName) && LogItemValues.ContainsKey(logItemName))
		{
			LogItemValues.Remove(logItemName);
		}
	}

	[QTMParameter(ArgumentName = "isSuperstation", Description = "True if it this is a superstation, False otherwise", DefaultValue = "True")]
	[QTMParameter(ArgumentName = "PhoneThree", Description = "Phone 3")]
	[QTMParameter(ArgumentName = "PhoneFour", Description = "Phone 4")]
	[QTMTest("Set the UUT ID for the currently loaded tree")]
	[QTMParameter(ArgumentName = "PhoneOne", Description = "Phone 1")]
	[QTMParameter(ArgumentName = "PhoneTwo", Description = "Phone 2")]
	[QTMParameter(ArgumentName = "PhoneFive", Description = "Phone 5")]
	[QTMParameter(ArgumentName = "PhoneSix", Description = "Phone 6")]
	public bool Set_UUTIDs(bool isSuperstation, string PhoneOne, string PhoneTwo, string PhoneThree, string PhoneFour, string PhoneFive, string PhoneSix)
	{
		if ((PhoneOne == null || PhoneOne == "") && (PhoneTwo == null || PhoneTwo == "") && (PhoneThree == null || PhoneThree == "") && (PhoneFour == null || PhoneFour == "") && (PhoneFive == null || PhoneFive == "") && (PhoneSix == null || PhoneSix == ""))
		{
			Exec_MessageBox("No UUTIDs Provided", "No UUTIDs were specified. Execution will now terminate. Please restart testing after entering at least one UUTID.");
			throw new Exception("No UUTIDs Provided");
		}
		Superstation = isSuperstation;
		if (isSuperstation)
		{
			string[] uUTID = new string[7] { null, PhoneOne, PhoneTwo, PhoneThree, PhoneFour, PhoneFive, PhoneSix };
			UUTID = uUTID;
		}
		else
		{
			string[] uUTID2 = new string[6] { PhoneOne, PhoneTwo, PhoneThree, PhoneFour, PhoneFive, PhoneSix };
			UUTID = uUTID2;
		}
		return true;
	}

	[QTMParameter(ArgumentName = "FormatDescriptor", Description = "The path to the format descriptor", DisplayHint = DisplayHints.FILE)]
	[QTMParameter(ArgumentName = "FolderName", Description = "The name of the folder to mine. Matches against subfolder to: \\XMLOutputDirectory\\ExecutionTreeName\\...")]
	[QTMParameter(ArgumentName = "ExactFolderNameMatch", Description = "False - Any folders containing FolderName will be matched. True - Only folders exactly matching FolderName will be matched", DefaultValue = "False")]
	[QTMParameter(ArgumentName = "Grouping", Description = "The argument to be passed to data miner", Constraints = "-gd Temp;-gd Temp -gd Voltage;-gd Temp -cd Voltage;-gd Voltage -cd Temp", DisplayHint = DisplayHints.CONSTRAINTS)]
	[QTMParameter(ArgumentName = "BandValue", Description = "The name of the band to group by, if applicable", DefaultValue = "All")]
	[QTMParameter(ArgumentName = "Timeout", Description = "Maximum amount of time for dataminer to run", UnitOfMeasure = "Seconds")]
	[QTMParameter(ArgumentName = "OpenExcelOnCompletion", Description = "Open the output file after successful completion", DefaultValue = "False")]
	[QTMParameter(ArgumentName = "ExcludedFolderNames", UnitOfMeasure = "Separate by \";\"", Description = "EXACT names of folders to be excluded from data miner")]
	[QTMTest("Execute dataminer for the given parameters. Set_LogDestinations MUST BE RUN FIRST.")]
	public bool Exec_DataMiner(string FolderName, bool ExactFolderNameMatch, string Grouping, string BandValue, string FormatDescriptor, int Timeout, bool OpenExcelOnCompletion, string ExcludedFolderNames)
	{
		try
		{
			if (!File.Exists(FormatDescriptor))
			{
				TimeStampedDebugMessage("Format descriptor not found: " + FormatDescriptor);
				return false;
			}
			string text = null;
			string[] array = new string[3] { "C:\\DataMiner\\DataMiner.exe", "C:\\Program Files (x86)\\Qualcomm\\QDART\\QMine\\DataMiner\\dataminer.exe", "C:\\Program Files\\Qualcomm\\QDART\\QMine\\DataMiner\\dataminer.exe" };
			string[] array2 = array;
			foreach (string text2 in array2)
			{
				if (File.Exists(text2))
				{
					text = text2;
				}
			}
			if (text == null)
			{
				TimeStampedDebugMessage("Dataminer not found");
				return false;
			}
			string gvValue = null;
			GlobalVariable.GetGlobalVariable("TreeFileName", out gvValue);
			gvValue = Path.GetFileNameWithoutExtension(gvValue);
			if (LogDestination != null && LogDestination.Length != 0)
			{
				string text3 = Path.Combine(LogDestination, gvValue);
				if (Directory.Exists(text3))
				{
					TimeStampedDebugMessage("Base path for data miner is: " + text3);
					List<string> list = new List<string>();
					if (ExcludedFolderNames != null && ExcludedFolderNames.Length != 0)
					{
						char[] separator = new char[1] { ';' };
						string[] array3 = ExcludedFolderNames.Split(separator, StringSplitOptions.RemoveEmptyEntries);
						string[] array4 = array3;
						foreach (string text4 in array4)
						{
							list.Add(text4.ToLower());
						}
					}
					List<string> list2 = new List<string>();
					string[] directories = Directory.GetDirectories(text3);
					foreach (string text5 in directories)
					{
						string text6 = new DirectoryInfo(text5).Name.ToLower();
						if (list.Contains(text6))
						{
							TimeStampedDebugMessage("Skipping folder for datamine: " + text5);
						}
						else if (ExactFolderNameMatch && FolderName.ToLower() == text6)
						{
							TimeStampedDebugMessage("Adding folder for datamine: " + text5);
							list2.Add(text5);
						}
						else if (!ExactFolderNameMatch && text6.Contains(FolderName.ToLower()))
						{
							TimeStampedDebugMessage("Adding folder for datamine: " + text5);
							list2.Add(text5);
						}
					}
					string path = Path.Combine(text3, "Reports");
					path = Path.Combine(path, "Excel") + "\\";
					string text7 = path + FolderName + ".xlsx";
					if (File.Exists(text7))
					{
						int num = 0;
						do
						{
							num++;
							text7 = path + FolderName + num + ".xlsx";
							TimeStampedDebugMessage("Checking existance for: " + text7);
						}
						while (text7 == null || File.Exists(text7));
					}
					TimeStampedDebugMessage("Dataminer report file name: " + text7);
					if (!Directory.Exists(path))
					{
						Directory.CreateDirectory(path);
					}
					string text8 = "\"" + text + "\" ";
					foreach (string item in list2)
					{
						text8 = text8 + " -r \"" + item + "\"";
					}
					text8 = text8 + " -o \"" + text7 + "\" ";
					if (BandValue == null || BandValue.Length == 0)
					{
						BandValue = "All";
					}
					if (BandValue.CompareTo("All") != 0)
					{
						text8 = text8 + "-gd Band:=" + BandValue + " ";
					}
					string text9 = text8;
					text8 = text9 + Grouping + " -ss -lup -lsp -f \"" + FormatDescriptor + "\"";
					TimeStampedDebugMessage("Query:\n" + text8);
					string text10 = "C:\\Temp\\DataminerBatch.bat";
					if (File.Exists(text10))
					{
						File.Delete(text10);
					}
					File.WriteAllText(text10, text8);
					TimeStampedDebugMessage("Executing Dataminer");
					Process process = new Process();
					process.StartInfo.UseShellExecute = true;
					process.StartInfo.FileName = text10;
					process.Start();
					if (Timeout == 0)
					{
						process.WaitForExit();
					}
					else if (!process.WaitForExit(Timeout * 1000))
					{
						process.Kill();
						Process[] processesByName = Process.GetProcessesByName("dataminer");
						foreach (Process process2 in processesByName)
						{
							string mainWindowTitle = process2.MainWindowTitle;
							process2.Kill();
							TimeStampedDebugMessage("Killed " + mainWindowTitle);
						}
						TimeStampedDebugMessage("Dataminer timed out after " + Timeout + " seconds");
						return false;
					}
					File.Delete(text10);
					if (File.Exists(text7))
					{
						TimeStampedDebugMessage("File created: " + text7);
						TimeStampedLogMessage("Dataminer completed successfully!");
						TimeStampedLogMessage(text7);
						if (OpenExcelOnCompletion)
						{
							new Process();
							process.StartInfo.FileName = text7;
							process.Start();
						}
						return true;
					}
					TimeStampedDebugMessage("File not found: " + text7);
					TimeStampedLogMessage("Dataminer failed. Output file not found.");
					return false;
				}
				TimeStampedLogMessage("Base path does not exist: " + text3);
				return false;
			}
			TimeStampedLogMessage("No LogDestination set. Please run SetLogDestinations first.");
			return false;
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Error in executing dataminer:\n" + ex.ToString());
			return false;
		}
	}

	[QTMParameter(ArgumentName = "BatchFile", Description = "The full path to the batch file", DisplayHint = DisplayHints.FILE)]
	[QTMTest("Execute the specified batch file")]
	[QTMParameter(ArgumentName = "BatchTimeout", Description = "The number of seconds before the batch is killed")]
	public bool Exec_BatchFile(string BatchFile, int BatchTimeout)
	{
		BatchFile = BatchFile.Replace("\"", "");
		if (!File.Exists(BatchFile))
		{
			TimeStampedLogMessage("Batch file does not exist: " + BatchFile);
			return false;
		}
		TimeStampedDebugMessage("Executing: " + BatchFile);
		Process process = new Process();
		process.StartInfo.UseShellExecute = true;
		process.StartInfo.FileName = BatchFile;
		process.Start();
		if (BatchTimeout == 0)
		{
			process.WaitForExit();
		}
		else if (!process.WaitForExit(BatchTimeout * 1000))
		{
			process.Kill();
			TimeStampedDebugMessage("Batch file timed out after " + BatchTimeout + " seconds");
			return false;
		}
		return true;
	}

	[QTMTest("Clear all overrides before beginning. PLACE THIS TEST FIRST.")]
	public bool Set_InitializeOverrides()
	{
		return Exec_ClearOverrides(string.Empty);
	}

	[QTMParameter(ArgumentName = "Title", Description = "The title of the message window", DefaultValue = "Alert")]
	[QTMParameter(ArgumentName = "Content", Description = "The content of the message window")]
	[QTMTest("Launch a message box with the selected content.")]
	public bool Exec_MessageBox(string Title, string Content)
	{
		try
		{
			TimeStampedDebugMessage("MessageBox: " + Title + " - " + Content);
			MessageBox.Show(Content, Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
			return true;
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("MessageBox error:\n" + ex.ToString());
			return false;
		}
	}

	[DllImport("user32.dll")]
	private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

	private void minimizeQSPR(string xttPath)
	{
		Process[] processesByName = Process.GetProcessesByName("QSPR");
		foreach (Process process in processesByName)
		{
			if (process.MainWindowTitle.ToLower().Contains(xttPath.ToLower()))
			{
				ShowWindow(process.MainWindowHandle, 2);
			}
		}
	}

	private int RunWatchStatus(XTTDocument xttRunning, bool ExecuteImmediately)
	{
		xttRunning.TestDone += TestDoneHandler;
		xttRunning.GoNoGoDone += GoNoGoDoneHandler;
		xttRunning.SendStatus += SendStatusHandler;
		qsprApp.QsprExited += QsprExitedHandler;
		FinalizeLoggingRun = false;
		CurrentTestAborted = false;
		if (ExecuteImmediately)
		{
			TimeStampedLogMessage("Executing QSPR");
			xttRunning.GoNoGo();
		}
		else if (MessageBox.Show("A new QSPR has been opened with the tree specified. Would you like to run it right now? If you chose No, you must run the tree manually to continue.", "Test Plan Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
		{
			xttRunning.GoNoGo();
		}
		try
		{
			string gvValue = null;
			GlobalVariable.GetGlobalVariable("TreeFileName", out gvValue);
			string globalVariable = qsprApp.GetGlobalVariable("TreeFileName");
			TimeStampedDebugMessage("Left window is: " + gvValue);
			TimeStampedDebugMessage("Right window is: " + globalVariable);
			if (TestWindowLayout == WindowLayout.Vertical)
			{
				ReArrangeWindows(gvValue, globalVariable, horizontal: false);
			}
			else if (TestWindowLayout == WindowLayout.Horizontal)
			{
				ReArrangeWindows(gvValue, globalVariable, horizontal: true);
			}
			else
			{
				TimeStampedDebugMessage("Unused window layout: " + TestWindowLayout);
			}
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Error in changing window layout:\n" + ex.ToString());
		}
		TreeFinishedEvent.WaitOne();
		int goNoGoStatus = xttRunning.GoNoGoStatus;
		xttRunning.TestDone -= TestDoneHandler;
		xttRunning.GoNoGoDone -= GoNoGoDoneHandler;
		xttRunning.SendStatus -= SendStatusHandler;
		qsprApp.QsprExited -= QsprExitedHandler;
		try
		{
			if (qsprApp.GetGlobalVariable("QSPR_ABORT").ToLower() == "true")
			{
				CurrentTestAborted = true;
			}
		}
		catch
		{
			TimeStampedDebugMessage("Could not get abort information...");
		}
		return goNoGoStatus;
	}

	private List<string> setCustomTestValues(XTTDocument xttDoc)
	{
		List<string> list = new List<string>();
		if (TreeTimeout != 0)
		{
			try
			{
				TimeStampedDebugMessage("Setting Tree Timeout");
				string nodeDescription = xttDoc.GetNodeDescription("");
				TestNode testNode = xttDoc.GetTestNode(nodeDescription);
				int num = testNode.SetTestProperty("TreeTimeOut", TreeTimeout.ToString());
				if (num + testNode.SetTestProperty("TimeOutAction", "Abort") == 0)
				{
					list.Add("Could not set new timeout value. Test Name: " + nodeDescription + ", Value: " + TreeTimeout);
				}
				else
				{
					TimeStampedLogMessage("Tree Timeout: " + TreeTimeout + " seconds");
				}
			}
			catch (Exception ex)
			{
				list.Add("Fatal error setting tree timeout: " + ex.ToString());
			}
		}
		try
		{
			TimeStampedDebugMessage("Setting Individual Timeouts");
			if (SingleTestTimeouts != null)
			{
				TestNode testNode2 = xttDoc.GetTestNode("");
				while (!IsNodeNull(testNode2))
				{
					string text = testNode2.GetTestPropertyValue("TestName", 1).ToString();
					foreach (SingleTestTimeout singleTestTimeout in SingleTestTimeouts)
					{
						bool flag = false;
						if (singleTestTimeout.UseRegex)
						{
							Regex regex = new Regex(singleTestTimeout.TestName);
							Match match = regex.Match(text);
							if (match.Success)
							{
								flag = true;
							}
						}
						else if (text == singleTestTimeout.TestName)
						{
							flag = true;
						}
						if (flag)
						{
							TimeStampedLogMessage("Set timeout value: " + text + " - " + singleTestTimeout.TimeoutValue);
							testNode2.SetTestProperty("TestTimeOut", singleTestTimeout.TimeoutValue.ToString());
							testNode2.SetTestProperty("TimeOutAction", "Abort");
						}
					}
					testNode2 = testNode2.GetNextNode();
				}
			}
		}
		catch (Exception ex2)
		{
			TimeStampedDebugMessage("Fatal error setting timeouts: " + ex2.ToString());
			list.Add("Fatal error setting timeout for individual tests: " + ex2.ToString());
		}
		try
		{
			TimeStampedDebugMessage("Setting All Test Parameters");
			if (AllTestParameterValues != null)
			{
				foreach (AllTestParameter allTestParameterValue in AllTestParameterValues)
				{
					string paramName = allTestParameterValue.ParamName;
					object paramValue = allTestParameterValue.ParamValue;
					TimeStampedLogMessage("Setting parameter \"" + paramName + "\" for all tests: " + paramValue);
					if (xttDoc.SetTestParameterInAllTests(paramName, paramValue) == 0)
					{
						list.Add("Error setting test parameter in all tests. Parameter: " + paramName + ", Value: " + paramValue.ToString());
					}
				}
			}
		}
		catch (Exception ex3)
		{
			list.Add("Fatal error in setting all test parameters: " + ex3.ToString());
		}
		try
		{
			TimeStampedDebugMessage("Setting Single Test Parameters");
			if (SingleTestParameterValues != null)
			{
				foreach (SingleTestParameter singleTestParameterValue in SingleTestParameterValues)
				{
					string testName = singleTestParameterValue.TestName;
					string paramName2 = singleTestParameterValue.ParamName;
					object paramValue2 = singleTestParameterValue.ParamValue;
					TimeStampedLogMessage("Setting parameter \"" + paramName2 + "\" for test \"" + testName + "\": " + paramValue2);
					if (xttDoc.SetTestParameter(testName, paramName2, paramValue2) == 0)
					{
						list.Add("Error setting test parameter. Test: " + testName + ", Parameter: " + paramName2 + ", Value: " + paramValue2.ToString());
					}
				}
			}
		}
		catch (Exception ex4)
		{
			list.Add("Fatal error in setting single test parameters: " + ex4.ToString());
		}
		try
		{
			TimeStampedDebugMessage("Setting Voltage");
			xttDoc.SetTestParameterInAllTests("Voltage Level", TestVoltage);
			TimeStampedLogMessage("Voltage: " + TestVoltage);
		}
		catch (Exception ex5)
		{
			list.Add("Fatal error in setting voltage level: " + ex5.ToString());
		}
		try
		{
			TimeStampedDebugMessage("Setting Temperature");
			xttDoc.SetTestParameterInAllTests("Temp", TestTemperature);
			TimeStampedLogMessage("Temperature: " + TestTemperature);
		}
		catch (Exception ex6)
		{
			list.Add("Fatal error in setting temperature: " + ex6.ToString());
		}
		try
		{
			TimeStampedDebugMessage("Setting Logging Items");
			string text2 = insertLoggingItems(xttDoc);
			if (text2 != null)
			{
				list.Add(text2);
			}
		}
		catch (Exception ex7)
		{
			list.Add("Fatal error in inserting logging items: " + ex7.ToString());
		}
		xttDoc.Save();
		TimeStampedDebugMessage("Saving...");
		return list;
	}

	private string setGPSLogDestination(XTTDocument xttDoc)
	{
		try
		{
			string path = string.Format("GPSLog_{0}", DateTime.Now.ToString("yyyy_MM_dd-HH.mm.ss"));
			string text = Path.Combine("C:\\TEMP\\LOGS\\", path);
			if (!text.EndsWith(Path.DirectorySeparatorChar.ToString()))
			{
				text += Path.DirectorySeparatorChar;
			}
			TimeStampedDebugMessage("GPS Log Path is: " + text);
			Directory.CreateDirectory(text);
			if (xttDoc.SetTestParameter("FinalizeDataLogging", "File Path Name", text) == 0)
			{
				throw new Exception("Error setting test parameter");
			}
			return text;
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Fatal error using debug logging: " + ex.ToString());
			return string.Empty;
		}
	}

	private string insertLoggingItems(XTTDocument xttDoc)
	{
		string text = "Custom Log Items";
		GNSSLogging = false;
		string text2 = "";
		string text3 = "";
		string text4 = "";
		TestNode testNode = null;
		TestNode testNode2 = null;
		text3 = "Geting the parent folder to the finalize node";
		TestNode testNode3 = null;
		TestNode testNode4 = xttDoc.GetTestNode("");
		qsprApp.EnableRegexSupport = 1;
		string text5 = xttDoc.GetTestNode("(.*)Finalize(.*)Data(.*)Logging").GetTestPropertyValue("TestName", 1).ToString();
		qsprApp.EnableRegexSupport = 0;
		try
		{
			while (testNode4 != null && text5 != null && text5.Length != 0)
			{
				testNode4.GetTestPropertyValue("TestName", 1).ToString();
				if (testNode4.IsFolder() == 1)
				{
					TestNode testNode5 = testNode4.GetFirstChild();
					bool flag = false;
					while (!flag && testNode5 != null)
					{
						if (testNode5.GetTestPropertyValue("TestName", 1).ToString() == text5)
						{
							flag = true;
						}
						testNode5 = testNode5.GetNextSibling();
					}
					if (flag)
					{
						testNode3 = testNode4;
						break;
					}
				}
				testNode4 = testNode4.GetNextNode();
			}
			if (testNode3 != null)
			{
				TimeStampedDebugMessage("Parent folder name is: " + testNode3.GetTestPropertyValue("TestName", 1).ToString());
				testNode3.SetTestProperty("TreeMustRun", "True");
				text3 = "Unsetting TreeMustRun for Finalize folder's children";
				TestNode testNode6 = testNode3.GetFirstChild();
				while (!IsNodeNull(testNode6))
				{
					testNode6.SetTestProperty("TreeMustRun", "False");
					testNode6 = testNode6.GetNextSibling();
				}
			}
			else
			{
				TimeStampedLogMessage("WARNING: Could not find folder containing finalize node. Timeouts will likely result in data loss");
			}
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Fatal error setting parent folder of finalize data logging to TreeMustRun:\n" + ex.ToString());
			TimeStampedLogMessage("WARNING: Could not find folder containing finalize node. Timeouts will likely result in data loss");
		}
		try
		{
			text3 = "Getting the initialize data logging test node";
			qsprApp.EnableRegexSupport = 1;
			testNode = xttDoc.GetTestNode("(.*)Init(.*)Data(.*)Logging");
			qsprApp.EnableRegexSupport = 0;
			text3 = "Getting the prefix for this DLL";
			string text6 = testNode.GetTestPropertyValue("RealName", 1).ToString();
			text2 = text6.Substring(0, text6.IndexOf("Init"));
			if (text2 == "RFCal_QDART_")
			{
				text2 = "RFCal_";
			}
			else if (text2 == "GNSS_")
			{
				GNSSLogging = true;
			}
			TimeStampedDebugMessage("DLL Prefix is: " + text2);
			testNode.SetTestProperty("TestName", "InitializeDataLogging");
			testNode.SetTestProperty("TreeMustRun", "True");
		}
		catch (Exception ex2)
		{
			return "Fatal error adding QDART Init Data Logging during: " + text3 + "\n" + ex2.ToString();
		}
		try
		{
			text3 = "Getting the finalize data logging test node";
			qsprApp.EnableRegexSupport = 1;
			testNode2 = xttDoc.GetTestNode("(.*)Finalize(.*)Data(.*)Logging");
			qsprApp.EnableRegexSupport = 0;
			testNode2.SetTestParameter("File Path Name", "C:\\TEMP\\LOGS\\", "", "");
			testNode2.SetTestProperty("TestName", "FinalizeDataLogging");
			testNode2.SetTestProperty("TreeMustRun", "True");
		}
		catch (Exception ex3)
		{
			return "Fatal error adding QDART Finalize Data Logging during: " + text3 + "\n" + ex3.ToString();
		}
		try
		{
			string text7 = "Phone(.*)Loop";
			qsprApp.EnableRegexSupport = 1;
			TestNode testNode7 = xttDoc.GetTestNode(text7);
			qsprApp.EnableRegexSupport = 0;
			testNode7.SetLoopType(0, null, null, 0);
			TimeStampedLogMessage("Removed loop from : " + text7);
			xttDoc.SetTestParameterInAllTests("Phone Index", 1);
		}
		catch (Exception ex4)
		{
			return "Fatal error removing phone loop: " + ex4.ToString();
		}
		if (HasTemperatureChamber)
		{
			try
			{
				string text8 = null;
				text8 = ((!(text2 == "RFCal_")) ? (text2 + "ConfigTemperature") : "CWCDMAConfigTemperature");
				TestNode testNode8 = testNode.AddTest(text8, "ConfigTemperature_LogFileFix");
				testNode8.SetTestParameter("Temperature:SoakTime", TestTemperature + ":0", null, null);
				testNode8.SetTestParameter("Temperature Tolerance", 5, null, null);
				testNode8.SetTestParameter("Temperature Setting Timeout", 0, null, null);
			}
			catch (Exception ex5)
			{
				text4 = text4 + "Fatal error adding temperature logging node: " + ex5.ToString() + "\n";
			}
		}
		try
		{
			if (LogItemValues != null && LogItemValues.Count != 0)
			{
				testNode.CreateFolder(text);
				TestNode testNode9 = xttDoc.GetTestNode(text);
				if (IsNodeNull(testNode9))
				{
					return "Failed to find " + text;
				}
				TimeStampedLogMessage("Added: " + text);
				if (text2 == "CHDR")
				{
					text2 = "CHDR_";
				}
				string realName = text2 + "LogItem";
				if (LogItemValues != null)
				{
					foreach (string key in LogItemValues.Keys)
					{
						string text9 = key;
						testNode9.AddTest(realName, text9);
						TestNode testNode10 = xttDoc.GetTestNode(text9);
						testNode10.SetTestParameter("Log Test Name", text9, "", "");
						testNode10.SetTestParameter("Log Item Name", key, "", "");
						testNode10.SetTestParameter("Log Value", LogItemValues[key], "", "");
						testNode10.SetTestParameter("Log item(s) as parameter(s)?", "Yes", "", "");
						TimeStampedLogMessage("Added: " + text9);
					}
				}
			}
		}
		catch (Exception ex6)
		{
			text4 = text4 + "Fatal error adding custom log items: " + ex6.ToString() + "\n";
		}
		return text4;
	}

	public static bool FixGPSLogFolder(string logFolder)
	{
		try
		{
			string[] files = Directory.GetFiles(logFolder, "*.xml", SearchOption.TopDirectoryOnly);
			string[] directories = Directory.GetDirectories(logFolder, "*", SearchOption.TopDirectoryOnly);
			if (directories.Length == 1 && files.Length == 1)
			{
				string text = directories[0];
				string name = new DirectoryInfo(text).Name;
				string fullName = new DirectoryInfo(text).Parent.FullName;
				string arg = files[0];
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(files[0]);
				if (fileNameWithoutExtension.Contains(name))
				{
					string destDirName = Path.Combine(fullName, fileNameWithoutExtension);
					Directory.Move(text, destDirName);
					return true;
				}
				TimeStampedDebugMessage($"Could not match file {arg} with folder {text}");
				return false;
			}
			if (directories.Length == 1 && files.Length == 0)
			{
				return FixGPSLogFolder(directories[0]);
			}
			TimeStampedDebugMessage("Unexpected GPS log folder contents, cannot rename");
			return false;
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Fatal error renaming GPS folder: " + ex.ToString());
			return false;
		}
	}

	private void LogFileEntry(string logPath)
	{
		if (!Directory.Exists("C:\\Qualcomm\\QDART\\Temp\\"))
		{
			Directory.CreateDirectory("C:\\Qualcomm\\QDART\\Temp\\");
		}
		string text = Path.Combine("C:\\Qualcomm\\QDART\\Temp\\", "LogFileList_TestExecution.txt");
		try
		{
			if (!File.Exists(text))
			{
				TimeStampedDebugMessage("Creating aggregate log file: " + text);
				StreamWriter streamWriter = File.CreateText(text);
				TimeStampedDebugMessage("Created: " + text);
				streamWriter.WriteLine(logPath);
				streamWriter.Flush();
				streamWriter.Close();
			}
			TimeStampedDebugMessage("Appending to aggregate log file: " + text);
			File.AppendAllText(text, logPath + "\n");
			TimeStampedDebugMessage("Appended: " + logPath);
		}
		catch
		{
			TimeStampedDebugMessage("Error creating aggregate log file");
		}
	}

	[QTMTest(false)]
	public bool LoadTestTreeFromVBS(string vbsPath, out string xttPath, out int exitCode)
	{
		TestVBS = vbsPath;
		string text = "C:\\Windows\\system32\\CScript.exe";
		string text2 = "C:\\Windows\\syswow64\\CScript.exe";
		string text3 = null;
		text3 = ((!File.Exists(text2)) ? text : text2);
		string text4 = Path.GetFileNameWithoutExtension(vbsPath) + ".xtt";
		string vBSVersion = getVBSVersion(vbsPath);
		Set_CustomLogItem("VBSVersion", vBSVersion);
		string perforcePath = getPerforcePath(vbsPath);
		if (File.Exists(perforcePath))
		{
			TimeStampedDebugMessage("Found path to P4 tree: " + perforcePath);
		}
		else
		{
			TimeStampedDebugMessage("Failed to find path to P4 tree: " + perforcePath);
		}
		string path = text4.Replace("Xvc", vBSVersion);
		xttPath = Path.Combine("C:\\TEMP\\IPSTREES\\", path);
		if (File.Exists(xttPath))
		{
			try
			{
				TimeStampedDebugMessage("Predicted tree name already exists, deleting");
				File.Delete(xttPath);
			}
			catch (Exception ex)
			{
				TimeStampedDebugMessage("Delete failed:");
				TimeStampedDebugMessage(ex.ToString());
			}
		}
		Process[] processesByName = Process.GetProcessesByName("QSPR");
		TimeStampedDebugMessage("Running Script: " + vbsPath);
		Process process = new Process();
		process.StartInfo.UseShellExecute = false;
		process.StartInfo.RedirectStandardOutput = true;
		process.StartInfo.FileName = text3;
		process.StartInfo.Arguments = "\"" + vbsPath + "\"";
		process.StartInfo.CreateNoWindow = true;
		process.Start();
		process.WaitForExit();
		exitCode = process.ExitCode;
		Process[] processesByName2 = Process.GetProcessesByName("QSPR");
		Process[] array = processesByName2;
		foreach (Process process2 in array)
		{
			bool flag = true;
			Process[] array2 = processesByName;
			foreach (Process process3 in array2)
			{
				if (process2.Id == process3.Id)
				{
					flag = false;
					break;
				}
			}
			if (flag)
			{
				process2.Kill();
			}
		}
		File.Delete(Path.Combine("C:\\TEMP\\IPSTREES\\", text4));
		if (File.Exists(xttPath))
		{
			TimeStampedLogMessage("Exit code is: " + exitCode);
			if (exitCode == 2)
			{
				try
				{
					File.Delete(xttPath);
				}
				catch
				{
				}
				return false;
			}
			TimeStampedLogMessage("Tree created: " + xttPath);
			LoadedTreePath = xttPath;
			return true;
		}
		TimeStampedDebugMessage("Tree not found: " + xttPath);
		xttPath = null;
		return false;
	}

	private void TestDoneHandler(string testName, int testStatus)
	{
		string text = "Status [" + testStatus + "]: ";
		switch (testStatus)
		{
		case 1:
			text = "PASS: ";
			break;
		case 0:
			text = "FAIL: ";
			break;
		}
		if (testName == "FinalizeDataLogging")
		{
			FinalizeLoggingRun = true;
		}
		TimeStampedDebugMessage(text + testName);
	}

	private void SendStatusHandler(string status)
	{
		TimeStampedDebugMessage(status);
	}

	private void GoNoGoDoneHandler(int bPass)
	{
		TreeFinishedEvent.Set();
	}

	private void QsprExitedHandler(int exitCode)
	{
		TreeFinishedEvent.Set();
	}

	private void HandleErrorMessage(string errorMessage, bool isMajor)
	{
		ErrorBehavior errorBehavior = ErrorBehavior.None;
		ErrorEmail testErrorEmail = TestErrorEmail;
		errorBehavior = ((!isMajor) ? TestErrorBehaviorMinor : TestErrorBehaviorMajor);
		TimeStampedDebugMessage(errorMessage);
		switch (errorBehavior)
		{
		case ErrorBehavior.Popup:
			MessageBox.Show(errorMessage, "Execution Tree Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
			break;
		case ErrorBehavior.Email:
		{
			FromAddress = testErrorEmail.FromAddress;
			toAddress = testErrorEmail.ToAddress;
			GlobalVariable.GetGlobalVariable("TreeFileName", out var gvValue);
			gvValue = Path.GetFileName(gvValue);
			string machineName = Environment.MachineName;
			Subject = "Error on machine " + machineName + " running tree " + gvValue;
			MessageBody = errorMessage;
			SMTPServerName = testErrorEmail.SMTPServerName;
			Exec_SendEmail();
			break;
		}
		case ErrorBehavior.None:
			break;
		}
	}

	private static SqlConnection getDatabaseConnection()
	{
		try
		{
			SqlConnection sqlConnection = new SqlConnection("user id=QSPRAppUser;password=$1234Qual;server=cte-sql-dev2;database=QSPRDB_IPS; connection timeout=30");
			sqlConnection.Open();
			return sqlConnection;
		}
		catch (Exception)
		{
			return null;
		}
	}

	private static int? uspGetTestCaseExecutionDataByRID(int RID)
	{
		int? result = null;
		SqlCommand sqlCommand = new SqlCommand("tmef.uspGetTestCaseExecutionDataByRID");
		sqlCommand.CommandType = CommandType.StoredProcedure;
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append(xmlRootHead);
		stringBuilder.Append(xmlValueHead);
		stringBuilder.Append(xmlTagString(RID.ToString(), "TestCaseExecutionDataRID"));
		stringBuilder.Append(xmlValueTail);
		stringBuilder.Append(xmlRootTail);
		string value = stringBuilder.ToString();
		_ = SHOW_DEBUG;
		sqlCommand.Parameters.Add(new SqlParameter("@XmlInput", SqlDbType.Text)
		{
			Value = value
		});
		SqlDataReader sqlDataReader = executeCommand(sqlCommand);
		try
		{
			while (sqlDataReader.Read())
			{
				try
				{
					result = Convert.ToInt32(sqlDataReader["ExecutionStatusOptionsRID"]);
				}
				catch (Exception)
				{
				}
			}
		}
		catch (Exception)
		{
			return null;
		}
		sqlDataReader.Close();
		sqlCommand.Connection.Close();
		return result;
	}

	private static SqlDataReader executeCommand(SqlCommand dbCommand)
	{
		try
		{
			SqlConnection databaseConnection = getDatabaseConnection();
			SqlDataReader sqlDataReader = null;
			dbCommand.Connection = databaseConnection;
			return dbCommand.ExecuteReader();
		}
		catch (Exception)
		{
			return null;
		}
	}

	private static List<string> executeSimpleGet(string procedureName, string parameterName)
	{
		SqlConnection databaseConnection = getDatabaseConnection();
		List<string> list = new List<string>();
		SqlCommand sqlCommand = new SqlCommand(procedureName, databaseConnection);
		sqlCommand.CommandType = CommandType.StoredProcedure;
		SqlDataReader sqlDataReader = executeCommand(sqlCommand);
		try
		{
			while (sqlDataReader.Read())
			{
				list.Add(sqlDataReader[parameterName].ToString());
			}
		}
		catch (Exception)
		{
			return null;
		}
		sqlDataReader.Close();
		sqlCommand.Connection.Close();
		return list;
	}

	private static void genericRead(SqlDataReader dbReader)
	{
		int fieldCount = dbReader.FieldCount;
		for (int i = 0; i < fieldCount; i++)
		{
		}
		while (dbReader.Read())
		{
			for (int j = 0; j < fieldCount; j++)
			{
			}
		}
	}

	private static string xmlTagString(string value, string tag)
	{
		return "<" + tag + ">" + value + "</" + tag + ">";
	}

	[QTMParameter(ArgumentName = "LTE", Description = "SubSysLTE_NET.dll", DisplayHint = DisplayHints.CHECK, DefaultValue = "1")]
	[QTMParameter(ArgumentName = "RFCal_1X", Description = "SubSysRFCalibration_1X_NET.dll", DisplayHint = DisplayHints.CHECK, DefaultValue = "1")]
	[QTMParameter(ArgumentName = "GSM", Description = "SubSysGSM_NET.dll", DisplayHint = DisplayHints.CHECK, DefaultValue = "1")]
	[QTMParameter(ArgumentName = "RFCal", Description = "SubSysRFCal_NET.dll", DisplayHint = DisplayHints.CHECK, DefaultValue = "1")]
	[QTMParameter(ArgumentName = "TDSCDMA", Description = "SubSysTDSCDMA_NET.dll", DisplayHint = DisplayHints.CHECK, DefaultValue = "1")]
	[QTMParameter(ArgumentName = "WDCMA", Description = "SubSysWCDMA_NET.dll", DisplayHint = DisplayHints.CHECK, DefaultValue = "1")]
	[QTMParameter(ArgumentName = "TestExecutionLibrary", Description = "TestExecutionLibrary.dll", DisplayHint = DisplayHints.CHECK, DefaultValue = "1")]
	[QTMParameter(ArgumentName = "CDMA2000", Description = "SubSysCDMA2000_NET.dll", DisplayHint = DisplayHints.CHECK, DefaultValue = "1")]
	[QTMParameter(ArgumentName = "HDR", Description = "SubSysHDR_NET.dll", DisplayHint = DisplayHints.CHECK, DefaultValue = "1")]
	[QTMParameter(ArgumentName = "MultiMode", Description = "SubSysMultiMode_NET.dll", DisplayHint = DisplayHints.CHECK, DefaultValue = "1")]
	public static bool Exec_UpdateDLLs(bool CDMA2000, bool GSM, bool HDR, bool LTE, bool MultiMode, bool RFCal_1X, bool RFCal, bool TDSCDMA, bool WDCMA, bool TestExecutionLibrary)
	{
		if (CDMA2000)
		{
			RunDLLUpdate("SubSysCDMA2000_NET.dll");
		}
		if (GSM)
		{
			RunDLLUpdate("SubSysGSM_NET.dll");
		}
		if (HDR)
		{
			RunDLLUpdate("SubSysHDR_NET.dll");
		}
		if (LTE)
		{
			RunDLLUpdate("SubSysLTE_NET.dll");
		}
		if (MultiMode)
		{
			RunDLLUpdate("SubSysMultiMode_NET.dll");
		}
		if (RFCal_1X)
		{
			RunDLLUpdate("SubSysRFCalibration_1X_NET.dll");
		}
		if (RFCal)
		{
			RunDLLUpdate("SubSysRFCal_NET.dll");
		}
		if (TDSCDMA)
		{
			RunDLLUpdate("SubSysTDSCDMA_NET.dll");
		}
		if (WDCMA)
		{
			RunDLLUpdate("SubSysWCDMA_NET.dll");
		}
		if (TestExecutionLibrary)
		{
			RunDLLUpdate("TestExecutionLibrary.dll");
		}
		return true;
	}

	private static void RunDLLUpdate(string singleDLL)
	{
		try
		{
			string text = Path.Combine(DLL_PATH, singleDLL);
			TimeStampedDebugMessage(singleDLL);
			Version version = ((!File.Exists(text)) ? new Version(0, 0, 0, 0) : GetDLLVersion(text));
			string potentialUpdate = GetPotentialUpdate(DLL_LIST[singleDLL].Replace("S:\\", "\\\\na\\qctasw\\SUITE_SERVER\\"));
			string parsedVersion = GetParsedVersion(Path.GetFileNameWithoutExtension(potentialUpdate));
			if (parsedVersion == null)
			{
				return;
			}
			Version version2 = new Version(parsedVersion);
			TimeStampedDebugMessage("Current Version is " + version.ToString() + ", available version is " + version2);
			if (version2 > version)
			{
				string caption;
				string text2;
				if (version == new Version(0, 0, 0, 0))
				{
					caption = "DLL is missing";
					text2 = $"{singleDLL} is not installed on this computer. Would you like to install version {version2}?";
				}
				else
				{
					caption = "DLL update available";
					text2 = $"{singleDLL} has version {version.ToString()}. Version {version2} is available. Would you like to update?";
				}
				if (MessageBox.Show(text2, caption, MessageBoxButtons.YesNo) == DialogResult.Yes)
				{
					Process process = new Process();
					process.StartInfo.UseShellExecute = true;
					process.StartInfo.FileName = potentialUpdate;
					process.Start();
					process.WaitForExit();
				}
			}
			else
			{
				TimeStampedDebugMessage("Current version is up to date or better.\n");
			}
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Error running " + singleDLL + ":\n" + ex.ToString());
		}
	}

	private static Version GetDLLVersion(string fullPath)
	{
		FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(fullPath);
		return new Version(versionInfo.FileVersion.Replace(", ", "."));
	}

	private static string GetPotentialUpdate(string exePath)
	{
		string text = null;
		try
		{
			string[] files = Directory.GetFiles(exePath, "*_V*.exe");
			string[] array = files;
			foreach (string text2 in array)
			{
				if (text == null)
				{
					text = text2;
					continue;
				}
				DateTime lastWriteTime = File.GetLastWriteTime(text);
				DateTime lastWriteTime2 = File.GetLastWriteTime(text2);
				if (lastWriteTime2 > lastWriteTime)
				{
					text = text2;
				}
			}
			return text;
		}
		catch (Exception)
		{
			return null;
		}
	}

	private static string GetParsedVersion(string fileName)
	{
		int num = fileName.IndexOf("_V") + 2;
		string text = fileName.Substring(num, fileName.Length - num);
		char[] separator = new char[1] { '.' };
		string[] array = text.Split(separator, StringSplitOptions.RemoveEmptyEntries);
		if (array.Length == 4)
		{
			return text;
		}
		if (array.Length == 3)
		{
			if (array[2].Length == 4)
			{
				return array[0] + "." + array[1] + "." + array[2].Substring(0, 2) + "." + array[2].Substring(2, 2);
			}
			if (array[2].Length == 1 || array[2].Length == 2)
			{
				return array[0] + "." + array[1] + "." + array[2] + ".0";
			}
		}
		return null;
	}

	public bool Exec_SendEmail()
	{
		try
		{
			MailAddress from = new MailAddress(FromAddress);
			MailAddress to = new MailAddress(ToAddress);
			MailMessage mailMessage = new MailMessage(from, to);
			mailMessage.Subject = Subject;
			mailMessage.Body = MessageBody;
			try
			{
				SmtpClient smtpClient = new SmtpClient(SMTPServerName);
				smtpClient.Send(mailMessage);
				errMsg = "";
				return true;
			}
			catch (HttpListenerException ex)
			{
				errMsg = ex.Message;
				return false;
			}
		}
		catch (Exception ex2)
		{
			errMsg = ex2.Message;
			return false;
		}
	}

	private string moveLogFile(ref string qsprLogFile, string parentXTTName, ref string bestRetestLogFile, int durationSeconds)
	{
		TimeStampedDebugMessage("Processing Local Log File: " + qsprLogFile);
		TimeStampedDebugMessage("Log destination is: " + LogDestination);
		GlobalVariable.GetGlobalVariable("TreeFileName", out var gvValue);
		gvValue = Path.GetFileNameWithoutExtension(gvValue);
		TimeStampedDebugMessage("Execution Tree Name: " + gvValue);
		string highFolder = "";
		string vbsVersion = "";
		parseXTT(parentXTTName, out highFolder, out vbsVersion);
		string text = TestVoltage.ToString().Replace('.', 'p') + "V_" + TestTemperature.ToString().Replace('-', 'n') + "C";
		TimeStampedDebugMessage("Low Folder: " + text);
		TimeStampedDebugMessage("High Folder: " + highFolder);
		string text2 = getDestinationFileName(qsprLogFile, vbsVersion);
		if (CurrentTestAborted)
		{
			TimeStampedDebugMessage("Log file was aborted. Likely timed out.");
			string text3 = "_FAIL.xml";
			string text4 = "_PASS.xml";
			string newValue = "_ABORTED.xml";
			if (text2.Contains(text3))
			{
				text2 = text2.Replace(text3, newValue);
			}
			else if (text2.Contains(text4))
			{
				text2 = text2.Replace(text4, newValue);
			}
		}
		TimeStampedDebugMessage("Final File Name: " + text2);
		string directoryName = Path.GetDirectoryName(qsprLogFile);
		int num = 0;
		string text5 = text2;
		while (File.Exists(Path.Combine(directoryName, text5)))
		{
			num++;
			text5 = text2.Replace(".xml", "(" + num + ").xml");
		}
		text2 = text5;
		string text6 = Path.Combine(directoryName, text2);
		TimeStampedDebugMessage("Local Rename Target: " + text6);
		int num2 = 0;
		bool flag = false;
		while (num2 < 5)
		{
			try
			{
				if (qsprLogFile.ToLower() != text6.ToLower())
				{
					File.Move(qsprLogFile, text6);
					qsprLogFile = text6;
					flag = true;
					TimeStampedLogMessage("Success: " + qsprLogFile);
				}
			}
			catch (Exception ex)
			{
				TimeStampedDebugMessage("File rename error:\n" + ex.ToString());
				TimeStampedDebugMessage("Waiting to retry");
				Thread.Sleep(1000 * num2);
				num2++;
				continue;
			}
			break;
		}
		if (!flag)
		{
			TimeStampedDebugMessage("Unable to rename log file after " + num2 + " retries");
		}
		TimeStampedDebugMessage("Validating log destination: " + LogDestination);
		ValidateLogDestination();
		if (bestRetestLogFile != null && File.Exists(bestRetestLogFile))
		{
			TimeStampedDebugMessage("Previous best file was: " + bestRetestLogFile);
			int passPercentage = getPassPercentage(text2);
			int passPercentage2 = getPassPercentage(bestRetestLogFile);
			TimeStampedDebugMessage("Previous percentage: " + passPercentage2);
			TimeStampedDebugMessage("Current percentage: " + passPercentage);
			if (passPercentage2 >= passPercentage)
			{
				gvValue += "_RETEST";
				TimeStampedDebugMessage("Current log file was not better than previous. Log will be saved to retest folder.");
			}
			else if (passPercentage2 < passPercentage)
			{
				string text7 = bestRetestLogFile.Replace("\\" + gvValue + "\\", "\\" + gvValue + "_RETEST\\");
				File.Move(bestRetestLogFile, text7);
				TimeStampedDebugMessage("Current log file is better. Previous log file moved: " + text7);
				bestRetestLogFile = null;
			}
			else
			{
				TimeStampedDebugMessage("Both log files have the same pass percentage. Current log file will be saved to retest.");
				gvValue += "_RETEST";
			}
		}
		else
		{
			TimeStampedDebugMessage("No previously tested log detected.");
		}
		string path = Path.Combine(LogDestination, gvValue);
		path = Path.Combine(path, highFolder);
		path = Path.Combine(path, text);
		if (!Directory.Exists(path))
		{
			Directory.CreateDirectory(path);
		}
		string text8 = Path.Combine(path, text2);
		if (text8.Length > 260)
		{
			DateTime now = DateTime.Now;
			TimeStampedDebugMessage("File path exceeds 260 characters. Truncating.");
			string[] separator = new string[1] { "_" };
			string text9 = text2.Split(separator, StringSplitOptions.RemoveEmptyEntries)[0];
			object obj = text9;
			text9 = string.Concat(obj, "_", now.Hour, "h", now.Minute, "m", now.Second, "s.xml");
			TimeStampedDebugMessage("Truncated file name is: " + text9);
			text8 = Path.Combine(path, text9);
			string text10 = Path.Combine(Path.GetDirectoryName(qsprLogFile), text9);
			try
			{
				File.Move(qsprLogFile, text10);
				qsprLogFile = text10;
			}
			catch
			{
				TimeStampedDebugMessage("Failed to rename local log to truncated path");
			}
		}
		path = text8;
		TimeStampedDebugMessage("Destination path is: " + path);
		try
		{
			TimeStampedDebugMessage("Copying:\n" + qsprLogFile + "\n" + path);
			File.Copy(qsprLogFile, path, overwrite: true);
		}
		catch (Exception ex2)
		{
			TimeStampedLogMessage("COPY FAILED FOR FILE: " + qsprLogFile);
			TimeStampedDebugMessage(ex2.ToString());
		}
		return path;
	}

	private string getDestinationFileName(string logFilePath, string vbsVersion)
	{
		try
		{
			QsprConvertor qsprConvertor = new QsprConvertor();
			string text = qsprConvertor.GetShortFormattedXmlName(logFilePath).Replace("Superstation", "SS");
			TimeStampedDebugMessage("Unfixed Destination Name: " + text);
			string[] array = text.Split('_');
			string[] array2 = array;
			foreach (string text2 in array2)
			{
				if (text2.Contains("pcPass"))
				{
					string text3 = text2;
					string text4 = vbsVersion + "_" + GetIPSPassPercentage(logFilePath);
					TimeStampedDebugMessage("Adjusting pass percentage: " + text3 + " --> " + text4);
					text = text.Replace(text3, text4);
				}
			}
			return text;
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Failed to reformat log file name for: " + logFilePath + "\n" + ex.ToString());
			return logFilePath;
		}
	}

	private string GetIPSPassPercentage(string qsprFilePath)
	{
		string[] array = new string[13]
		{
			"Init", "WaitForRegistration", "HSDPA_Demod", "Utility", "GetFWVersion", "Statistics", "Preset", "InitPowerSupply", "EndCall", "PhoneMode",
			"CallSetup", "Network", "CheckPhone"
		};
		QsprConvertor qsprConvertor = new QsprConvertor();
		source qSPRSource = qsprConvertor.GetQSPRSource(qsprFilePath);
		TestColl validQSPRTestCollection = qsprConvertor.GetValidQSPRTestCollection(qSPRSource);
		int num = 0;
		int num2 = 0;
		foreach (Tests item in validQSPRTestCollection.Test)
		{
			try
			{
				bool flag = false;
				string[] array2 = array;
				foreach (string value in array2)
				{
					if (item.Name.Contains(value))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					DIValue dIValue = (DIValue)item.PassFail.DI[0];
					if (dIValue.V.Equals("PASS"))
					{
						num2++;
					}
					else if (dIValue.V.Equals("FAIL"))
					{
						num++;
					}
				}
			}
			catch
			{
			}
		}
		string text = "";
		if (num2 + num != 0)
		{
			return (int)((double)num2 / (double)(num2 + num) * 100.0) + "pcPass";
		}
		return 0 + "pcPass";
	}

	private string GetQsprLogFilePath(string SerialNumber, string QSPRLogFolderPath)
	{
		try
		{
			DirectoryInfo directoryInfo = new DirectoryInfo(QSPRLogFolderPath);
			FileInfo[] files = directoryInfo.GetFiles("*" + SerialNumber + "*.xml");
			FileInfo fileInfo = null;
			FileInfo[] array = files;
			foreach (FileInfo fileInfo2 in array)
			{
				if (fileInfo == null || fileInfo2.LastWriteTime > fileInfo.LastWriteTime)
				{
					fileInfo = fileInfo2;
				}
			}
			return fileInfo?.FullName;
		}
		catch (Exception)
		{
			return null;
		}
	}

	private string GetQsprLogFilePath()
	{
		using StreamReader streamReader = new StreamReader("C:\\Qualcomm\\QDART\\Temp\\LogFileList.txt");
		string text = null;
		string text2;
		while ((text2 = streamReader.ReadLine()) != null)
		{
			if (text2.Length != 0)
			{
				text = text2;
			}
		}
		TimeStampedLogMessage("Get log file from manifest: " + text);
		return text;
	}

	private int getPassPercentage(string qsprLogFilePath)
	{
		try
		{
			string[] separator = new string[1] { "_" };
			string[] array = qsprLogFilePath.Split(separator, StringSplitOptions.RemoveEmptyEntries);
			int result = -1;
			string[] array2 = array;
			foreach (string text in array2)
			{
				if (text.Contains("pcPass"))
				{
					result = Convert.ToInt32(text.Replace("pcPass", ""));
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Error in getting pass percentage:\n" + qsprLogFilePath + "\n" + ex.ToString());
			return -1;
		}
	}

	private void prependXMLHeader(string xmlFile)
	{
		if (xmlFile == null || xmlFile.Length == 0 || !File.Exists(xmlFile))
		{
			return;
		}
		if (File.Exists("C:\\Temp\\TemplogFile.xml"))
		{
			File.Delete("C:\\Temp\\TemplogFile.xml");
		}
		if (!Directory.Exists(Path.GetDirectoryName("C:\\Temp\\TemplogFile.xml")))
		{
			Directory.CreateDirectory(Path.GetDirectoryName("C:\\Temp\\TemplogFile.xml"));
		}
		StreamWriter streamWriter = new StreamWriter("C:\\Temp\\TemplogFile.xml");
		StreamReader streamReader = new StreamReader(xmlFile);
		bool flag = true;
		try
		{
			string text;
			while ((text = streamReader.ReadLine()) != null)
			{
				if (StylesheetXML != null && StylesheetXML.Length != 0)
				{
					LOG_FILE_HEADER = "<?xml-stylesheet href=\"file://s:\\Stylesheets\\" + StylesheetXML + "\" type=\"text/xsl\"?>";
				}
				if (flag && text.CompareTo(LOG_FILE_HEADER) != 0)
				{
					streamWriter.WriteLine(LOG_FILE_HEADER);
					flag = false;
				}
				streamWriter.WriteLine(text);
				streamWriter.Flush();
			}
			streamReader.Close();
			streamWriter.Close();
			File.Copy("C:\\Temp\\TemplogFile.xml", xmlFile, overwrite: true);
			File.Delete("C:\\Temp\\TemplogFile.xml");
		}
		catch (Exception ex)
		{
			TimeStampedLogMessage("Fatal error in prepending XML header: " + ex.ToString());
		}
	}

	private StreamWriter GenerateDebugFile(string debugOutputDirectory, string singleUUTID)
	{
		if (!Directory.Exists(debugOutputDirectory))
		{
			Directory.CreateDirectory(debugOutputDirectory);
		}
		DateTime now = DateTime.Now;
		string text = now.ToString("ddMMMyyyy");
		string text2 = now.ToString("HH") + "h" + now.ToString("mm") + "m" + now.ToString("ss") + "s";
		string path = "DEBUGLOG_" + singleUUTID + "_" + text + "_" + text2 + ".txt";
		string path2 = Path.Combine(debugOutputDirectory, path);
		if (!File.Exists(path2))
		{
			try
			{
				return File.CreateText(path2);
			}
			catch (Exception)
			{
				return null;
			}
		}
		return File.AppendText(path2);
	}

	private void ValidateLogDestination()
	{
		TimeStampedDebugMessage("Destination is: " + LogDestination);
		if (LogDestination == null || LogDestination.Length == 0)
		{
			LogDestination = "C:\\TEMP\\LOGS\\";
		}
		else if (!Directory.Exists(LogDestination))
		{
			Directory.CreateDirectory(LogDestination);
		}
	}

	[QTMTest(false)]
	public static void parseXTT(string singleTree, out string highFolder, out string vbsVersion)
	{
		new Dictionary<int, int>();
		new Dictionary<string, int>();
		string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(singleTree);
		string[] separator = new string[1] { "__" };
		string[] array = fileNameWithoutExtension.Split(separator, StringSplitOptions.RemoveEmptyEntries);
		int num = -1;
		Regex regex = new Regex("X[0-9]+$");
		for (int num2 = array.Length - 1; num2 >= 0; num2--)
		{
			Match match = regex.Match(array[num2]);
			if (match.Success || array[num2].ToLower() == "xvc")
			{
				num = num2;
				break;
			}
		}
		if (num > 0)
		{
			highFolder = array[num - 1];
			vbsVersion = array[num];
		}
		else
		{
			highFolder = fileNameWithoutExtension;
			vbsVersion = null;
		}
	}

	private void UnsetReadOnly(string fileName)
	{
		try
		{
			File.SetAttributes(fileName, FileAttributes.Normal);
			TimeStampedDebugMessage("File attributes set to normal");
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("File attribute failure: " + ex.ToString());
		}
	}

	private static bool IsNodeNull(TestNode singleNode)
	{
		try
		{
			singleNode.GetTestPropertyValue("RealName", 1).ToString();
			return false;
		}
		catch (Exception)
		{
			return true;
		}
	}

	private static string QSPRStatusString(int status)
	{
		return status switch
		{
			6 => "Passed", 
			7 => "Failed", 
			3 => "Running", 
			8 => "Exception", 
			-99 => "Undetermined", 
			_ => "Unknown Value " + status, 
		};
	}

	private static void TimeStampedLogMessage(string message)
	{
		DebugMessage.Write("Log", string.Concat(DateTime.Now, ": ", message));
		TimeStampedDebugMessage(message);
	}

	private static void TimeStampedErrorMessage(string message)
	{
		DebugMessage.Write("Error", string.Concat(DateTime.Now, ": ", message));
		TimeStampedDebugMessage(message);
	}

	private static void TimeStampedDebugMessage(string message)
	{
		string text = string.Concat(DateTime.Now, ": ", message);
		if (DebugOutputWriter != null)
		{
			try
			{
				DebugOutputWriter.WriteLine(text);
				DebugOutputWriter.Flush();
			}
			catch (Exception)
			{
			}
		}
		DebugMessage.Write("Debug", text);
	}

	private static void TimeStampedWarningMessage(string message)
	{
		DebugMessage.Write("Warning", string.Concat(DateTime.Now, ": ", message));
		TimeStampedDebugMessage(message);
	}

	[DllImport("user32.dll", SetLastError = true)]
	internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

	[DllImport("user32.dll")]
	private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

	[QTMTest(false)]
	public static void ReArrangeWindows(string treeNameLeft, string treeNameRight, bool horizontal)
	{
		try
		{
			string text = "QSPR - ";
			string text2 = " Tree ID: -1";
			string newValue = " * " + text2;
			string text3 = text + treeNameLeft + text2;
			IntPtr intPtr = FindWindow(null, text3);
			if (intPtr == IntPtr.Zero)
			{
				intPtr = FindWindow(null, text3.Replace(text2, newValue));
			}
			TimeStampedDebugMessage("Handle for " + treeNameLeft + " is: " + intPtr);
			string text4 = text + treeNameRight + text2;
			IntPtr intPtr2 = FindWindow(null, text4);
			if (intPtr2 == IntPtr.Zero)
			{
				intPtr2 = FindWindow(null, text4.Replace(text2, newValue));
			}
			TimeStampedDebugMessage("Handle for " + treeNameRight + " is: " + intPtr2);
			if (intPtr != IntPtr.Zero && intPtr2 != IntPtr.Zero)
			{
				Screen screen = Screen.AllScreens[0];
				int width = screen.WorkingArea.Width;
				int height = screen.WorkingArea.Height;
				ShowWindow(intPtr, 3);
				ShowWindow(intPtr2, 3);
				if (horizontal)
				{
					MoveWindow(intPtr, 0, 0, width, height / 2, bRepaint: true);
					MoveWindow(intPtr2, 0, height / 2, width, height / 2, bRepaint: true);
				}
				else
				{
					MoveWindow(intPtr, 0, 0, width / 2, height, bRepaint: true);
					MoveWindow(intPtr2, width / 2, 0, width / 2, height, bRepaint: true);
				}
			}
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Could not reposition windows:\n" + ex.ToString());
		}
	}

	private string getTemperatureFromTempVoltFolder(string folder)
	{
		try
		{
			string name = new DirectoryInfo(folder).Name;
			return name.Split('_')[1];
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Error parsing tempvolt folder name: " + folder + "\n" + ex.ToString());
			return null;
		}
	}

	private string getVoltageFromTempVoltFolder(string folder)
	{
		try
		{
			string name = new DirectoryInfo(folder).Name;
			return name.Split('_')[0];
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Error parsing tempvolt folder name: " + folder + "\n" + ex.ToString());
			return null;
		}
	}

	private Process processDiff(Process[] pre, Process[] post)
	{
		Process result = null;
		foreach (Process process in post)
		{
			bool flag = false;
			foreach (Process process2 in pre)
			{
				if (process2.Id == process.Id)
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				result = process;
				break;
			}
		}
		return result;
	}

	private void UUTIDStatus(string[] UUTs, int currentIndex)
	{
		string text = "Execution Progress:";
		string text2 = "                                              ";
		for (int i = 0; i < UUTs.Length; i++)
		{
			if (UUTs[i] != null && UUTs[i].Length != 0)
			{
				text = text + "\n" + text2;
				text = ((i >= currentIndex) ? (text + "[   ]") : (text + "[X]"));
				text += UUTs[i];
				if (i == currentIndex)
				{
					text += " <-- Executing";
				}
			}
		}
		TimeStampedLogMessage(text);
	}

	private static string getUnMappedPath(string logFilePath)
	{
		try
		{
			TimeStampedDebugMessage("Attempting to unmap: " + logFilePath);
			char c = logFilePath[0];
			if (logFilePath[1] == ':' && c != 'c' && c != 'C')
			{
				string path = DriveResolver(c);
				string text = Path.Combine(path, logFilePath.Replace(c + ":\\", ""));
				TimeStampedDebugMessage("Translated to path: " + text);
				if (File.Exists(text))
				{
					TimeStampedDebugMessage("Path found");
					return text;
				}
			}
			return null;
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Error in unmapping path: \n" + ex.ToString());
			return null;
		}
	}

	private static string DriveResolver(char driveLetter)
	{
		try
		{
			RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("Network");
			RegistryKey registryKey2 = registryKey.OpenSubKey(string.Concat(driveLetter));
			string text = registryKey2.GetValue("RemotePath").ToString();
			TimeStampedDebugMessage(driveLetter + " has actual path " + text);
			return text;
		}
		catch (Exception ex)
		{
			TimeStampedDebugMessage("Failure unmapping drive:\n" + ex.Message);
			return null;
		}
	}

	private void KillAllQPST()
	{
		Process[] processes = Process.GetProcesses();
		Process[] array = processes;
		foreach (Process process in array)
		{
			if (process.ProcessName.StartsWith("QPST"))
			{
				string processName = process.ProcessName;
				int id = process.Id;
				try
				{
					process.Kill();
					TimeStampedDebugMessage("Killed QPST process with name " + processName + " and PID " + id);
				}
				catch (Exception ex)
				{
					TimeStampedDebugMessage("Unable to kill QPST process with name " + processName + " and PID " + id + ":\n" + ex.ToString());
				}
			}
		}
	}

	[QTMTest(false)]
	public static string getVBSVersion(string vbsPath)
	{
		string text = "VersionVBS=";
		string result = "X0";
		StreamReader streamReader = new StreamReader(vbsPath);
		string text2;
		while ((text2 = streamReader.ReadLine()) != null)
		{
			text2 = text2.Trim();
			if (text2.StartsWith(text))
			{
				result = text2.Replace(text, "").Replace("\"", "");
			}
		}
		streamReader.Close();
		return result;
	}

	private static string modifyVBS(string vbsPath)
	{
		string text = Path.Combine("C:\\TEMP\\IPSTREES\\", Path.GetFileName(vbsPath));
		Directory.CreateDirectory("C:\\TEMP\\IPSTREES\\");
		StreamReader streamReader = new StreamReader(vbsPath);
		StreamWriter streamWriter = new StreamWriter(text);
		string text2 = "\\\\isis\\umts\\Automation\\DVT_vbs_scripts\\etc\\open_qspr_tree_set_temp_dir.vbs";
		string newValue = "\\\\freight\\CTADS\\Projects\\IPS\\Prototype\\open_qspr_tree_set_temp_dir_hidden.vbs";
		string text3 = "\\\\isis\\umts\\Automation\\DVT_vbs_scripts\\etc\\post_amble.vbs";
		string newValue2 = "\\\\freight\\CTADS\\Projects\\IPS\\Prototype\\post_amble.vbs";
		string text4;
		while ((text4 = streamReader.ReadLine()) != null)
		{
			if (text4.Contains(text2))
			{
				text4 = text4.Replace(text2, newValue);
			}
			if (text4.Contains(text3))
			{
				text4 = text4.Replace(text3, newValue2);
			}
			streamWriter.WriteLine(text4);
			streamWriter.Flush();
		}
		streamReader.Close();
		streamWriter.Close();
		return text;
	}

	private static string getPerforcePath(string vbsPath)
	{
		try
		{
			StreamReader streamReader = new StreamReader(vbsPath);
			string text = "Perforce_TestTree=";
			string text2;
			while ((text2 = streamReader.ReadLine()) != null)
			{
				if (text2.Contains(text))
				{
					text2 = text2.Replace(text, "");
					text2 = text2.Replace("\"", "");
					streamReader.Close();
					return text2;
				}
			}
			streamReader.Close();
		}
		catch
		{
		}
		return null;
	}
}
