using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;

namespace QTMDataFormat;

public class FormatFunctions
{
	public static class ColumnExtendedProperties
	{
		public const string ItemValues = "ItemValues";

		public const string Parent = "Parent";
	}

	public static class Suffixes
	{
		public const string ParamRunTimeUpperLimit = "__UL";

		public const string ParamRunTimeLowerLimit = "__LL";
	}

	public delegate void DelegateProcessRow(FormatProcessEventArgs e);

	public enum FormatOptions
	{
		Expanded,
		WideView,
		LongView,
		NoFormat,
		LongWideView
	}

	private const int SESSIONID = 0;

	private const int UUT_SN = 1;

	private const int MCN = 2;

	private const int TREEID = 3;

	private const int TESTERID = 4;

	private const int TESTNAME = 5;

	private const int PARAMNAME = 6;

	private const int LL_COL = 7;

	private const int DATA_COL = 8;

	private const int UL_COL = 9;

	private const int DATA_COL_STRING = 10;

	private const int TIMESTAMP = 13;

	private const int VISITNUM = 15;

	private const int LOOPCONDITION = 18;

	private const int TESTTIME = 3;

	private const int WORKSTATION = 6;

	private const int GLOBALRESULTS = 7;

	private const int PARAM_INDEX = 19;

	private const int ARRAY_PARM_LL_COL = 20;

	private const int ARRAY_PARAM_VALUE_COL = 21;

	private const int ARRAY_PARAM_UL_COL = 22;

	private const int DEFAULT_ROUNDING_DECIMALS = 4;

	public const string LOOP_CONDITION_COLUMN_NAME = "ScnValue";

	public const string PARAM_ARRAY_INDEX_COLUMN_NAME = "ArrayParamIndex";

	public const string ARRAY_NUM_RESULT_COLUMN_NAME = "ArrayResult";

	public const string ARRAY_LOWER_LIMIT_COLUMN_NAME = "ArrayLowerLimit";

	public const string ARRAY_UPPER_LIMIT_COLUMN_NAME = "ArrayUpperLimit";

	public const string ARRAY_CHAR_RESULT_COLUMN_NAME = "ArrayParamCharResult";

	public const string PARAM_NUM_RESULT_COLUMN_NAME = "NumValue";

	public const string PARAM_LOWER_LIMIT_COLUMN_NAME = "LowerLimit";

	public const string PARAM_UPPER_LIMIT_COLUMN_NAME = "UpperLimit";

	public const string PARAM_CHAR_RESULT_COLUMN_NAME = "CharValue";

	public const string PARAM_NAME_COLUMN_NAME = "ParameterName";

	public const string PARAM_RESULT_COLUMN_NAME = "ParamResult";

	public const string PARAM_PASS_FAIL_COLUMN_NAME = "ParamPassFail";

	public const string TEST_NAME_COLUMN_NAME = "TestName";

	public const string TEST_RESULT_COLUMN_NAME = "TestResult";

	public const string SESSION_DATA_R_ID_COLUMN_NAME = "SessionDataRID";

	public const string RUN_TITLE_COLUMN_NAME = "RunTitle";

	public const string UNIT_OF_MEASURE_COLUMN_NAME = "UOM";

	public const string NODE_DATA_RID_COLUMN_NAME = "NodeDataRID";

	public const string DATA_IDENTIFIER = "DataIdentifier";

	public const string UUT_SN_COLUMN_NAME = "UUT_SN";

	public const string START_TIME_COLUMN_NAME = "StartTime";

	public const string TEST_RESULT_PASS = "Passed";

	public const string TEST_RESULT_FAIL = "Failed";

	public const string RUN_TITLE_VALUE_SEPARATOR = "__";

	public const string RUN_TTITLE_ITEM_SEPARATOR = "_ _";

	public const string LOOP_SCENARIO_SEPARATOR = "_._";

	public const string LOOP_ITEM_SEPARATOR = "_ _";

	public const string LOOP_VALUE_SEPARATOR = "__";

	public const string LOOPCONDITIONS_TOBE_IGNORED = "RetryCount";

	public const string LAST_VISIT_LOOPCONDITION = "LastVisit";

	public const string LAST_VISIT_LOOPCONDITION_VALUE_1 = "LastVisit__1";

	public const string PRIME_KEY = "PRIME_KEY";

	private const char ARRAYPARAM_SEP = ':';

	private const int MAX_NO_OF_LOOPS = 20;

	public static string[] LOOPVALUE_SEP = new string[1] { "__" };

	public static string LOOPS_SEP = "_._";

	public static string LOOPSCENARIO_SEP = "_ _";

	public static char SEP = ',';

	private static object objLockWideViewObject = new object();

	private static object objLockLongViewObject = new object();

	private static object objLockParseDelimitedColumn = new object();

	private static FormatArgs _fargs;

	private static DataTable currentWideView;

	private static DataTable currentExpandedView;

	private static DataTable currentLongView;

	private static List<string> currentWideViewParamColumms;

	private static Dictionary<string, ParameterInfo> currentParamInfoDictionary;

	private static volatile bool cancel = false;

	public static FormatArgs FormattedArguments => _fargs;

	public static DataTable CurrentWideView
	{
		get
		{
			lock (objLockWideViewObject)
			{
				return currentWideView;
			}
		}
	}

	public static DataTable CurrentExpandedView
	{
		get
		{
			lock (objLockWideViewObject)
			{
				return currentExpandedView;
			}
		}
	}

	public static DataTable CurrentLongView
	{
		get
		{
			lock (objLockLongViewObject)
			{
				return currentLongView;
			}
		}
	}

	public static List<string> CurrentWideViewParamColumms
	{
		get
		{
			lock (objLockWideViewObject)
			{
				return currentWideViewParamColumms;
			}
		}
	}

	public static Dictionary<string, ParameterInfo> CurrentParamInfoDictionary
	{
		get
		{
			lock (objLockWideViewObject)
			{
				return currentParamInfoDictionary;
			}
		}
	}

	public static void Cancel()
	{
		cancel = true;
	}

	public static void ResetViews()
	{
		lock (objLockWideViewObject)
		{
			cancel = false;
			currentLongView = null;
			currentWideView = null;
			currentParamInfoDictionary = null;
			currentWideViewParamColumms = null;
		}
		lock (objLockLongViewObject)
		{
			currentExpandedView = null;
		}
	}

	public static DataTable CreateParamOnlyDataReader(SqlDataReader dr, out int NumResultCol, bool includeParamIndexColumn)
	{
		NumResultCol = 0;
		DataTable Results = new DataTable("MyDataTable");
		Results.Columns.Add("UUT_SN", Type.GetType("System.String"));
		Results.Columns.Add("LoopConditions", Type.GetType("System.String"));
		Results.Columns.Add("TestName", Type.GetType("System.String"));
		Results.Columns.Add("ParamName", Type.GetType("System.String"));
		if (includeParamIndexColumn)
		{
			Results.Columns.Add("ParamIndex", Type.GetType("System.String"));
		}
		Results.Columns.Add("LL", Type.GetType("System.String"));
		Results.Columns.Add("Value", Type.GetType("System.String"));
		Results.Columns.Add("UL", Type.GetType("System.String"));
		NumResultCol = Results.Columns["Value"].Ordinal - 1;
		while (dr.Read())
		{
			object[] array = new object[dr.FieldCount];
			dr.GetValues(array);
			string text = ((array[18] is DBNull) ? "" : ((string)array[18]));
			try
			{
				DataRow dataRow = Results.NewRow();
				dataRow["UUT_SN"] = (string)array[1];
				dataRow["LoopConditions"] = text;
				dataRow["TestName"] = (string)array[5];
				if (array[19] is DBNull)
				{
					dataRow["ParamName"] = (string)array[6];
					if (!(array[8] is DBNull))
					{
						dataRow["Value"] = ((double)array[8]).ToString();
					}
					else if (!(array[10] is DBNull))
					{
						dataRow["Value"] = (string)array[10];
					}
					if (includeParamIndexColumn)
					{
						dataRow["ParamIndex"] = "";
					}
					try
					{
						dataRow["UL"] = ((double)array[9]).ToString();
						dataRow["LL"] = ((double)array[7]).ToString();
					}
					catch
					{
						dataRow["UL"] = " ";
						dataRow["LL"] = " ";
					}
				}
				else
				{
					if (includeParamIndexColumn)
					{
						dataRow["ParamName"] = (string)array[6];
						dataRow["ParamIndex"] = ((int)array[19]).ToString();
					}
					else
					{
						dataRow["ParamName"] = (string)array[6] + "_" + (int)array[19];
					}
					dataRow["Value"] = (double)array[21];
					try
					{
						dataRow["UL"] = (double)array[22];
						dataRow["LL"] = (double)array[20];
					}
					catch
					{
					}
				}
				FormatLoopValue(text, ref Results, ref dataRow);
				Results.Rows.Add(dataRow);
			}
			catch
			{
			}
		}
		Results.Columns.Remove("LoopConditions");
		return Results;
	}

	public static DataTable FormatInXmlReader(SqlDataReader dr, FormatOptions Options, out double[,] LimitsArray, out int FirstParamCol)
	{
		bool flag = false;
		LimitsArray = new double[2, 250];
		DataTable dataTable = new DataTable("MyDataTable");
		dataTable.Columns.Add("PRIME_KEY", Type.GetType("System.String"));
		DataColumn[] array = new DataColumn[1] { dataTable.Columns["PRIME_KEY"] };
		dataTable.Columns.Add("UUT_SN", Type.GetType("System.String"));
		dataTable.Columns.Add("LoopConditions", Type.GetType("System.String"));
		DataView defaultView = dataTable.DefaultView;
		defaultView.Sort = "PRIME_KEY";
		FirstParamCol = -1;
		while (dr.Read())
		{
			object[] array2 = new object[dr.FieldCount];
			dr.GetValues(array2);
			string text = (string)array2[5];
			string text2 = (string)array2[6];
			string text3 = ((array2[18] is DBNull) ? "" : ((string)array2[18]));
			string text4 = text2;
			switch (Options)
			{
			case FormatOptions.Expanded:
				text4 = ((!(text3 != "")) ? (text + SEP + text2) : (text + SEP + text2 + SEP + text3));
				break;
			case FormatOptions.WideView:
				text4 = text + " " + text2;
				break;
			}
			if (!(array2[19] is DBNull))
			{
				text4 = text4 + "_" + (int)array2[19];
				flag = true;
			}
			else
			{
				flag = false;
			}
			if (dataTable.Columns[text4] == null)
			{
				dataTable.Columns.Add(text4, Type.GetType("System.String"));
				if (FirstParamCol == -1)
				{
					FirstParamCol = dataTable.Columns[text4].Ordinal;
				}
				try
				{
					if (!flag)
					{
						LimitsArray[0, dataTable.Columns[text4].Ordinal - FirstParamCol] = (double)array2[7];
						LimitsArray[1, dataTable.Columns[text4].Ordinal - FirstParamCol] = (double)array2[9];
					}
					else
					{
						LimitsArray[0, dataTable.Columns[text4].Ordinal - FirstParamCol] = (double)array2[20];
						LimitsArray[1, dataTable.Columns[text4].Ordinal - FirstParamCol] = (double)array2[22];
					}
				}
				catch
				{
					LimitsArray[0, dataTable.Columns[text4].Ordinal - FirstParamCol] = double.NaN;
					LimitsArray[1, dataTable.Columns[text4].Ordinal - FirstParamCol] = double.NaN;
				}
			}
			int num = (int)array2[0];
			string text5 = ((Options != 0) ? (num + text3) : num.ToString());
			try
			{
				int num2 = defaultView.Find(text5);
				if (num2 == -1)
				{
					DataRow dataRow = dataTable.NewRow();
					dataRow["PRIME_KEY"] = text5;
					dataRow["UUT_SN"] = (string)array2[1];
					dataRow["LoopConditions"] = text3;
					if (!flag)
					{
						if (!(array2[8] is DBNull))
						{
							dataRow[text4] = ((double)array2[8]).ToString();
						}
						else if (!(array2[10] is DBNull))
						{
							dataRow[text4] = (string)array2[10];
						}
						else
						{
							dataRow[text4] = " ";
						}
					}
					else
					{
						dataRow[text4] = ((double)array2[21]).ToString();
					}
					dataTable.Rows.Add(dataRow);
					continue;
				}
				DataRow dataRow2 = dataTable.Rows[num2];
				dataRow2.BeginEdit();
				if (!flag)
				{
					if (!(array2[8] is DBNull))
					{
						dataRow2[text4] = ((double)array2[8]).ToString();
					}
					else if (!(array2[10] is DBNull))
					{
						dataRow2[text4] = (string)array2[10];
					}
					else
					{
						dataRow2[text4] = " ";
					}
				}
				else
				{
					dataRow2[text4] = ((double)array2[21]).ToString();
				}
				dataTable.AcceptChanges();
			}
			catch (Exception arg)
			{
				Console.WriteLine("Something bad happened : {0}", arg);
			}
		}
		try
		{
			dataTable.Columns.Remove("PRIME_KEY");
			FirstParamCol--;
			if (Options == FormatOptions.Expanded)
			{
				dataTable.Columns.Remove("LoopConditions");
				FirstParamCol--;
			}
		}
		catch
		{
		}
		return dataTable;
	}

	public static DataTable CreateParamOnlyData(DataSet ds, out int NumResultCol, bool includeParamIndexColumn, bool includevisitnumber, ArrayList NewColumnsAdded)
	{
		cancel = false;
		NumResultCol = 0;
		DataTable Results = new DataTable("MyDataTable");
		Results.Columns.Add("UUT_SN", Type.GetType("System.String"));
		Results.Columns.Add("TimeStamp", Type.GetType("System.String"));
		if (includevisitnumber)
		{
			Results.Columns.Add("VisitNumber", Type.GetType("System.String"));
		}
		Results.Columns.Add("LoopConditions", Type.GetType("System.String"));
		Results.Columns.Add("TestName", Type.GetType("System.String"));
		Results.Columns.Add("ParamName", Type.GetType("System.String"));
		if (includeParamIndexColumn)
		{
			Results.Columns.Add("ParamIndex", Type.GetType("System.String"));
		}
		Results.Columns.Add("LL", Type.GetType("System.String"));
		Results.Columns.Add("Value", Type.GetType("System.String"));
		Results.Columns.Add("UL", Type.GetType("System.String"));
		NumResultCol = Results.Columns["Value"].Ordinal - 1;
		Hashtable hashtable = new Hashtable();
		if (NewColumnsAdded.Count > 0)
		{
			foreach (string item in NewColumnsAdded)
			{
				Results.Columns.Add(item, Type.GetType("System.String"));
				hashtable[item] = ds.Tables[0].Columns[item].Ordinal;
			}
		}
		if (ds.Tables.Count == 0)
		{
			return null;
		}
		DataTable dataTable = ds.Tables[0];
		int num = 0;
		foreach (DataRow row in dataTable.Rows)
		{
			if (cancel)
			{
				break;
			}
			object[] itemArray = row.ItemArray;
			string text2 = ((itemArray[18] is DBNull) ? "" : ((string)itemArray[18]));
			try
			{
				DataRow dataRow2 = Results.NewRow();
				dataRow2["UUT_SN"] = (string)itemArray[1];
				dataRow2["TimeStamp"] = itemArray[13].ToString();
				if (includevisitnumber)
				{
					dataRow2["VisitNumber"] = itemArray[15].ToString();
				}
				dataRow2["LoopConditions"] = text2;
				dataRow2["TestName"] = (string)itemArray[5];
				if (NewColumnsAdded.Count > 0)
				{
					foreach (string item2 in NewColumnsAdded)
					{
						int num2 = int.Parse(hashtable[item2].ToString());
						dataRow2[item2] = itemArray[num2].ToString();
					}
				}
				if (itemArray[19] is DBNull)
				{
					dataRow2["ParamName"] = (string)itemArray[6];
					if (!(itemArray[8] is DBNull))
					{
						dataRow2["Value"] = ((double)itemArray[8]).ToString();
					}
					else if (!(itemArray[10] is DBNull))
					{
						dataRow2["Value"] = (string)itemArray[10];
					}
					if (includeParamIndexColumn)
					{
						dataRow2["ParamIndex"] = "";
					}
					try
					{
						dataRow2["UL"] = ((double)itemArray[9]).ToString();
						dataRow2["LL"] = ((double)itemArray[7]).ToString();
					}
					catch
					{
						dataRow2["UL"] = " ";
						dataRow2["LL"] = " ";
					}
				}
				else
				{
					if (includeParamIndexColumn)
					{
						dataRow2["ParamName"] = (string)itemArray[6];
						dataRow2["ParamIndex"] = ((int)itemArray[19]).ToString();
					}
					else
					{
						dataRow2["ParamName"] = (string)itemArray[6] + "_" + (int)itemArray[19];
					}
					dataRow2["Value"] = (double)itemArray[21];
					try
					{
						dataRow2["UL"] = (double)itemArray[22];
						dataRow2["LL"] = (double)itemArray[20];
					}
					catch
					{
					}
				}
				FormatLoopValue(text2, ref Results, ref dataRow2);
				Results.Rows.Add(dataRow2);
			}
			catch
			{
			}
			num++;
		}
		Results.Columns.Remove("LoopConditions");
		return Results;
	}

	public static DataTable GetDataInLongView(ref FormatArgs fargs, out string errorMessage, ref bool isCancelled)
	{
		lock (objLockLongViewObject)
		{
			errorMessage = "";
			List<string> list = new List<string>();
			list.Add("TestName");
			list.Add("ParameterName");
			list.Add("UpperLimit");
			list.Add("LowerLimit");
			list.Add("NumValue");
			list.Add("CharValue");
			DataTable dataTable;
			if (currentLongView != null)
			{
				dataTable = currentLongView.Copy();
			}
			else
			{
				if (fargs.DataSource == null)
				{
					return null;
				}
				if (cancel)
				{
					isCancelled = true;
					errorMessage = "Long View Formatting was cancelled";
					cancel = false;
					return null;
				}
				dataTable = new DataTable("LongViewResults");
				DataTable dataSource = fargs.DataSource;
				dataTable = dataSource.Clone();
				if (dataSource.Columns.Contains("ParamResult"))
				{
					list.Add("ParamResult");
				}
				if (dataSource.Columns.Contains("TestName") && dataSource.Columns.Contains("ParameterName") && dataSource.Columns.Contains("ScnValue"))
				{
					dataTable.Columns.Add("DataIdentifier", typeof(string));
				}
				int i = 0;
				try
				{
					cancel = false;
					new Dictionary<string, bool>();
					for (i = 0; i < dataSource.Rows.Count; i++)
					{
						if (cancel)
						{
							isCancelled = true;
							errorMessage = "Long View Formatting was cancelled";
							cancel = false;
							return null;
						}
						DataRow dataRow = dataSource.Rows[i];
						DataRow dataRow2 = dataTable.NewRow();
						if (dataSource.Columns.Contains("TestName") && dataSource.Columns.Contains("ParameterName") && dataSource.Columns.Contains("ScnValue"))
						{
							dataRow2["DataIdentifier"] = string.Concat(dataRow["TestName"], ";", dataRow["ParameterName"], ";", dataRow["ScnValue"]);
						}
						dataRow2.ItemArray = dataRow.ItemArray;
						if (dataSource.Columns.Contains("ArrayParamIndex") && !(dataRow2["ArrayParamIndex"] is DBNull))
						{
							if (!(dataRow2["ArrayResult"] is DBNull))
							{
								dataRow2["NumValue"] = dataRow2["ArrayResult"];
							}
							if (!(dataRow2["ArrayParamCharResult"] is DBNull))
							{
								dataRow2["CharValue"] = dataRow2["ArrayParamCharResult"];
							}
							if (!(dataRow2["ArrayLowerLimit"] is DBNull))
							{
								dataRow2["LowerLimit"] = dataRow2["ArrayLowerLimit"];
							}
							if (!(dataRow2["ArrayUpperLimit"] is DBNull))
							{
								dataRow2["UpperLimit"] = dataRow2["ArrayUpperLimit"];
							}
							if (!fargs.SelectedColumns.Contains("ArrayParamIndex"))
							{
								string text = "";
								string text2 = "";
								try
								{
									text = dataRow2["ParameterName"].ToString();
								}
								catch
								{
									text = "";
								}
								try
								{
									text2 = dataRow2["ArrayParamIndex"].ToString();
								}
								catch
								{
									text2 = "";
								}
								dataRow2["ParameterName"] = text + "_" + text2;
							}
						}
						if (!(dataRow2["LowerLimit"] is DBNull))
						{
							_ = (double)dataRow2["LowerLimit"];
						}
						if (!(dataRow2["UpperLimit"] is DBNull))
						{
							_ = (double)dataRow2["UpperLimit"];
						}
						if (dataRow2["NumValue"] != null && double.TryParse(dataRow2["NumValue"].ToString(), out var result))
						{
							TryGetRoundedValue(result, 4, out result);
							dataRow2["NumValue"] = result;
						}
						dataTable.Rows.Add(dataRow2);
					}
				}
				catch (Exception ex)
				{
					errorMessage = "Error creating Long View for the row index " + i + " - " + ex.Message;
				}
				currentLongView = dataTable.Copy();
			}
			List<string> list2 = new List<string>();
			foreach (DataColumn column in dataTable.Columns)
			{
				list2.Add(column.ColumnName);
			}
			if (fargs.EnableColumnSelection)
			{
				foreach (string item in list2)
				{
					if (list.Contains(item))
					{
						continue;
					}
					if (fargs.DoNotDisplayColumns.Contains(item))
					{
						if (dataTable.Columns.Contains(item))
						{
							dataTable.Columns.Remove(item);
						}
					}
					else if (fargs.AvailableColumns.Contains(item) && !fargs.SelectedColumns.Contains(item) && dataTable.Columns.Contains(item))
					{
						dataTable.Columns.Remove(item);
					}
				}
			}
			if (fargs.IsQMTDatabase && dataTable.Columns.Contains("UUT_SN"))
			{
				dataTable.Columns.Remove("UUT_SN");
			}
			if (fargs.EnableColumnSelection)
			{
				int num = 0;
				if (fargs.ColumnsBeforeCalculatedColumns.Count > 0)
				{
					foreach (string columnsBeforeCalculatedColumn in fargs.ColumnsBeforeCalculatedColumns)
					{
						if (columnsBeforeCalculatedColumn.Length > 0 && dataTable.Columns.Contains(columnsBeforeCalculatedColumn))
						{
							try
							{
								dataTable.Columns[columnsBeforeCalculatedColumn].SetOrdinal(num);
								num++;
							}
							catch
							{
							}
						}
					}
				}
				List<string> list3 = new List<string>();
				foreach (DataColumn column2 in dataTable.Columns)
				{
					if (!fargs.ColumnsAfterCalculatedColumns.Contains(column2.ColumnName) && !fargs.ColumnsBeforeCalculatedColumns.Contains(column2.ColumnName))
					{
						list3.Add(column2.ColumnName);
					}
				}
				foreach (string item2 in list3)
				{
					try
					{
						if (item2.Length > 0 && dataTable.Columns.Contains(item2))
						{
							dataTable.Columns[item2].SetOrdinal(num);
							num++;
						}
					}
					catch
					{
					}
				}
				if (fargs.ColumnsAfterCalculatedColumns.Count > 0)
				{
					foreach (string columnsAfterCalculatedColumn in fargs.ColumnsAfterCalculatedColumns)
					{
						if (columnsAfterCalculatedColumn.Length > 0 && dataTable.Columns.Contains(columnsAfterCalculatedColumn))
						{
							try
							{
								dataTable.Columns[columnsAfterCalculatedColumn].SetOrdinal(num);
								num++;
							}
							catch
							{
							}
						}
					}
				}
			}
			return dataTable;
		}
	}

	public static DataTable GetDataInLongWideView(ref FormatArgs fargs, out string errorMessage, out int rowGroupingColumnsCount, ref bool isCancelled)
	{
		errorMessage = "";
		isCancelled = false;
		rowGroupingColumnsCount = -1;
		_fargs = fargs;
		string name = string.Empty;
		string name2 = string.Empty;
		DataTable dataSource = fargs.DataSource;
		DataTable dataTable = new DataTable();
		TypePrecedenceRuleImplementer typePrecedenceRuleImplementer = new TypePrecedenceRuleImplementer();
		dataSource = ApplyLoopConditionFilter(dataSource, "LastVisit__1");
		if (dataSource == null)
		{
			return null;
		}
		if (fargs.DataSource.Columns.Contains("TestName") && fargs.DataSource.Columns.Contains("ParameterName") && fargs.DataSource.Columns.Contains("ScnValue"))
		{
			dataTable.Columns.Add("DataIdentifier", typeof(string));
		}
		SerialNumberCollection serialNumberCollection = new SerialNumberCollection();
		Dictionary<string, Dictionary<SerialNumberInfoItem, ValueInfo>> dictionary = new Dictionary<string, Dictionary<SerialNumberInfoItem, ValueInfo>>();
		int num = 3;
		foreach (DataRow row in dataSource.Rows)
		{
			string text = Convert.ToString(row[DatabaseColumns.TreeIDColumnName]);
			if (dataSource.Columns.Contains(DatabaseColumns.NodeDataRIDColumnName))
			{
				Convert.ToString(row[DatabaseColumns.NodeDataRIDColumnName]);
			}
			string text2 = Convert.ToString(row[DatabaseColumns.TestNameColumnName]);
			string text3 = Convert.ToString(row[DatabaseColumns.ParamNameColumnName]);
			string text4 = Convert.ToString(row[DatabaseColumns.LoopConditionColumnName]);
			string text5 = Convert.ToString(row[DatabaseColumns.ParamUpperLimitColumnName]);
			string text6 = Convert.ToString(row[DatabaseColumns.ParamLowerLimitColumnName]);
			if (text4.Contains("RetryCount"))
			{
				text4 = RemoveLoopCondition(text4, "RetryCount");
			}
			if (text4.Contains("LastVisit"))
			{
				text4 = RemoveLoopCondition(text4, "LastVisit");
			}
			string text7 = text + "$" + text2 + "$" + text3;
			if (!fargs.IgnoreLimits)
			{
				string text8 = text7;
				text7 = text8 + "$" + text5 + "$" + text6;
				num = 5;
			}
			text7 = text7 + "$" + text4;
			string uUT_SN = row[DatabaseColumns.SerialNoColumnName].ToString();
			SerialNumberInfoItem serialNumberInfoItem = new SerialNumberInfoItem();
			serialNumberInfoItem.UUT_SN = uUT_SN;
			serialNumberInfoItem.Workstation = row[DatabaseColumns.WorkstationColumnName].ToString();
			serialNumberInfoItem.VisitNum = row[DatabaseColumns.VisitNumColumnName].ToString();
			serialNumberInfoItem.SerialInfoValueType = typeof(object);
			string text9 = Convert.ToString(row[DatabaseColumns.ParamNumResultColumnName]);
			string text10 = Convert.ToString(row[DatabaseColumns.ParamCharResultColumnName]);
			Dictionary<SerialNumberInfoItem, ValueInfo> dictionary2 = (dictionary.ContainsKey(text7) ? dictionary[text7] : new Dictionary<SerialNumberInfoItem, ValueInfo>(new SerialNumberInfoItem.SerialInfoComparer()));
			try
			{
				Type typeFromHandle;
				if (text9.Length > 0)
				{
					if (dictionary2.ContainsKey(serialNumberInfoItem))
					{
						ValueInfo valueInfo = dictionary2[serialNumberInfoItem];
						valueInfo.Occurance++;
						valueInfo.ParameterValue = valueInfo.ParameterValue + "#$#" + text9;
					}
					else
					{
						ValueInfo valueInfo2 = new ValueInfo();
						valueInfo2.Occurance++;
						valueInfo2.ParameterValue = text9;
						dictionary2.Add(serialNumberInfoItem, valueInfo2);
					}
					typeFromHandle = typeof(double);
				}
				else
				{
					if (dictionary2.ContainsKey(serialNumberInfoItem))
					{
						ValueInfo valueInfo3 = dictionary2[serialNumberInfoItem];
						valueInfo3.Occurance++;
						valueInfo3.ParameterValue = valueInfo3.ParameterValue + "_" + text10;
					}
					else
					{
						ValueInfo valueInfo4 = new ValueInfo();
						valueInfo4.Occurance++;
						valueInfo4.ParameterValue = text10;
						dictionary2.Add(serialNumberInfoItem, valueInfo4);
					}
					typeFromHandle = typeof(string);
				}
				serialNumberInfoItem.SerialInfoValueType = typePrecedenceRuleImplementer.GetTypeByPrecedence(typeFromHandle, serialNumberInfoItem.SerialInfoValueType);
			}
			catch (Exception)
			{
			}
			dictionary[text7] = dictionary2;
			if (!serialNumberCollection.Contains(serialNumberInfoItem))
			{
				serialNumberCollection.Add(serialNumberInfoItem);
			}
		}
		dataTable.Columns.Add(DatabaseColumns.TreeIDColumnName);
		dataTable.Columns.Add(DatabaseColumns.TestNameColumnName);
		dataTable.Columns.Add(DatabaseColumns.ParamNameColumnName);
		if (!fargs.IgnoreLimits)
		{
			dataTable.Columns.Add(DatabaseColumns.ParamLowerLimitColumnName, typeof(double));
			dataTable.Columns.Add(DatabaseColumns.ParamUpperLimitColumnName, typeof(double));
		}
		dataTable.Columns.Add(DatabaseColumns.LoopConditionColumnName);
		List<string> distinctSerialNumbers = serialNumberCollection.GetDistinctSerialNumbers();
		int num2 = 0;
		foreach (SerialNumberInfoItem item in serialNumberCollection)
		{
			if (distinctSerialNumbers.Contains(item.UUT_SN))
			{
				dataTable.Columns.Add(item.UUT_SN, item.SerialInfoValueType);
				if (num2 == 0)
				{
					name = item.UUT_SN;
				}
				if (num2 == serialNumberCollection.Count - 1)
				{
					name2 = item.UUT_SN;
				}
			}
			else
			{
				dataTable.Columns.Add(item.ToString(), item.SerialInfoValueType);
				if (num2 == 0)
				{
					name = item.ToString();
				}
				if (num2 == serialNumberCollection.Count - 1)
				{
					name2 = item.ToString();
				}
			}
			num2++;
		}
		foreach (string key in dictionary.Keys)
		{
			DataRow dataRow2 = dataTable.NewRow();
			try
			{
				string text11 = key;
				string[] array = text11.Split('$');
				if (fargs.DataSource.Columns.Contains("TestName") && fargs.DataSource.Columns.Contains("ParameterName") && fargs.DataSource.Columns.Contains("ScnValue"))
				{
					dataRow2["DataIdentifier"] = array[1] + ";" + array[2] + ";" + array[num];
				}
				dataRow2[DatabaseColumns.TreeIDColumnName] = array[0];
				dataRow2[DatabaseColumns.TestNameColumnName] = array[1];
				dataRow2[DatabaseColumns.ParamNameColumnName] = array[2];
				dataRow2[DatabaseColumns.LoopConditionColumnName] = array[num];
				if (!fargs.IgnoreLimits)
				{
					double result = double.NaN;
					double result2 = double.NaN;
					double.TryParse(array[4], out result);
					double.TryParse(array[3], out result2);
					dataRow2[DatabaseColumns.ParamLowerLimitColumnName] = result;
					dataRow2[DatabaseColumns.ParamUpperLimitColumnName] = result2;
				}
			}
			catch
			{
			}
			try
			{
				Dictionary<SerialNumberInfoItem, ValueInfo> dictionary3 = dictionary[key];
				foreach (SerialNumberInfoItem item2 in serialNumberCollection)
				{
					if (dictionary3.ContainsKey(item2))
					{
						if (distinctSerialNumbers.Contains(item2.UUT_SN))
						{
							dataRow2[item2.UUT_SN] = dictionary3[item2].GetFinalParametricValue();
						}
						else
						{
							dataRow2[item2.ToString()] = dictionary3[item2].GetFinalParametricValue();
						}
					}
				}
			}
			catch
			{
			}
			dataTable.Rows.Add(dataRow2);
		}
		List<string> loopconditioncolumns = null;
		string errorMessage2 = "";
		dataTable = ParseLoopConditions(dataTable, removedelimitedcolumn: true, out loopconditioncolumns, out errorMessage2);
		for (int i = 0; i < loopconditioncolumns.Count; i++)
		{
			string name3 = loopconditioncolumns[i];
			dataTable.Columns[name3].SetOrdinal(dataTable.Columns[DatabaseColumns.ParamNameColumnName].Ordinal + i + 1);
		}
		if (errorMessage2.Length > 0)
		{
			if (errorMessage.Length > 0)
			{
				errorMessage += ", ";
			}
			errorMessage = errorMessage + "Error Parsing loop conditions - " + errorMessage2;
		}
		dataTable.Columns["DataIdentifier"].SetOrdinal(dataTable.Columns.Count - 1);
		fargs.UnitsColumnStartIndex = dataTable.Columns[name].Ordinal;
		fargs.UnitsColumnEndIndex = dataTable.Columns[name2].Ordinal;
		rowGroupingColumnsCount = dataTable.Columns.Count - serialNumberCollection.Count - 1;
		return dataTable;
	}

	private static void GenerateGroupingColumns(List<string> columnGroupingColumns, DataTable tableData)
	{
		List<string> list = new List<string>();
		list.Add(DatabaseColumns.SerialNoColumnName);
		list.Add(DatabaseColumns.WorkstationColumnName);
		list.Add(DatabaseColumns.VisitNumColumnName);
		DataTable dataTable = tableData.DefaultView.ToTable(distinct: true, list.ToArray());
		DataTable dataTable2 = tableData.DefaultView.ToTable(true, DatabaseColumns.SerialNoColumnName);
		if (dataTable2.Rows.Count == dataTable.Rows.Count)
		{
			columnGroupingColumns.Add(DatabaseColumns.SerialNoColumnName);
		}
		else
		{
			columnGroupingColumns.AddRange(list);
		}
	}

	private static void AddExistingColumnsToRowGrouping(FormatArgs fargs, DataTable tableData, List<string> rowGroupingColumns)
	{
		List<string> list = new List<string>();
		list.AddRange(fargs.ColumnsBeforeCalculatedColumns);
		list.AddRange(fargs.ColumnsAfterCalculatedColumns);
		foreach (string item in list)
		{
			if (tableData.Columns.Contains(item))
			{
				rowGroupingColumns.Add(item);
			}
		}
	}

	private static string MergeCharNumValues(DataTable tableData)
	{
		DataColumn dataColumn = new DataColumn("ParameterValue");
		tableData.Columns.Add(dataColumn);
		foreach (DataRow row in tableData.Rows)
		{
			string text = row[DatabaseColumns.ParamCharResultColumnName].ToString();
			row[dataColumn] = (string.IsNullOrEmpty(text) ? row[DatabaseColumns.ParamNumResultColumnName] : text);
		}
		return dataColumn.ColumnName;
	}

	private static void ReOrderDataTable(DataTable tableData, List<string> prefixColumnsList, List<string> suffixColumnsList)
	{
		int num = 0;
		foreach (string prefixColumns in prefixColumnsList)
		{
			if (tableData.Columns.Contains(prefixColumns))
			{
				tableData.Columns[prefixColumns].SetOrdinal(num++);
			}
		}
		num = tableData.Columns.Count - (prefixColumnsList.Count + suffixColumnsList.Count) - 1;
		foreach (string suffixColumns in suffixColumnsList)
		{
			if (!tableData.Columns.Contains(suffixColumns))
			{
				tableData.Columns[suffixColumns].SetOrdinal(num++);
			}
		}
	}

	public static DataTable GetDataInLongWideView(ref FormatArgs fargs, out string errorMessage, ref bool isCancelled)
	{
		int rowGroupingColumnsCount = 0;
		return GetDataInLongWideView(ref fargs, out errorMessage, out rowGroupingColumnsCount, ref isCancelled);
	}

	public static void AddDataIdentifierColumn(DataTable dataTable)
	{
		if (!dataTable.Columns.Contains("DataIdentifier"))
		{
			DataColumn dataColumn = new DataColumn("DataIdentifier", typeof(string));
			dataColumn.Expression = $"ISNULL([{DatabaseColumns.TestNameColumnName}],'') + ';' + ISNULL([{DatabaseColumns.ParamNameColumnName}],'') + ';' + ISNULL([{DatabaseColumns.LoopConditionColumnName}],'')";
			dataTable.Columns.Add(dataColumn);
		}
	}

	private static DataTable GetPivotedData(DataTable tableData, List<string> columnGroupingColumns, List<string> rowGroupingColumns, string valueColumn, MultipleValuesOccuredEventHandler multipleValuesOccuredEventHandler)
	{
		PivotTableGenerator pivotTableGenerator = new PivotTableGenerator();
		pivotTableGenerator.ColumnGroupingFields = columnGroupingColumns;
		pivotTableGenerator.RowGroupingFields = rowGroupingColumns;
		pivotTableGenerator.ValueField = valueColumn;
		pivotTableGenerator.MultipleValuesOccured += multipleValuesOccuredEventHandler;
		pivotTableGenerator.Pivot(tableData);
		return pivotTableGenerator.PivotedDataTable;
	}

	private static void PivotMultipleValuesHandler(object sender, MultipleValuesOccuredEventArgs e)
	{
		double num = double.NaN;
		double num2 = 0.0;
		int num3 = 0;
		foreach (DataRow sourceRow in e.SourceRows)
		{
			string text = Convert.ToString(sourceRow[e.ValueField]);
			if (double.TryParse(Convert.ToString(text), out var _))
			{
				num2 += Convert.ToDouble(text);
				num3++;
			}
		}
		if (num3 > 0)
		{
			num = num2 / (double)num3;
			e.Result = num;
		}
		else
		{
			e.Result = DBNull.Value;
		}
	}

	private static DataTable ParseDelimitedColumns(DataTable tableData, out List<string> runtitleColumns, out List<string> loopConditionColumns, bool removeLoopConditionColumn, bool removeRuntitleColumn)
	{
		string errorMessage = string.Empty;
		tableData = ParseLoopConditions(tableData, removeLoopConditionColumn, out loopConditionColumns, out errorMessage);
		if (errorMessage.Length > 0)
		{
			throw new Exception($"Error parsing loop conditions - {errorMessage}");
		}
		tableData = ParseRunTitle(tableData, removeRuntitleColumn, out runtitleColumns, out errorMessage);
		if (errorMessage.Length > 0)
		{
			throw new Exception($"Error parsing run title conditions - {errorMessage}");
		}
		return tableData;
	}

	private static DataTable ApplyLoopConditionFilter(DataTable tbl, string loopCondition)
	{
		DataView defaultView = tbl.DefaultView;
		defaultView.RowFilter = $"{DatabaseColumns.LoopConditionColumnName} LIKE '%{loopCondition}%'";
		DataTable dataTable = defaultView.ToTable();
		if (dataTable.Rows.Count == 0)
		{
			dataTable = tbl;
			dataTable.DefaultView.RowFilter = "";
		}
		return dataTable;
	}

	public static DataTable RemoveTestsWithNoParameters(DataTable tbl)
	{
		DataView defaultView = tbl.DefaultView;
		defaultView.RowFilter = string.Format("({0} IS NOT NULL) OR ({0} <> '')", DatabaseColumns.ParamNameColumnName);
		return defaultView.ToTable();
	}

	private static void RemoveLoopCondition(DataTable tbl, string removeCondition)
	{
		foreach (DataRow row in tbl.Rows)
		{
			row[DatabaseColumns.LoopConditionColumnName] = RemoveLoopCondition(row[DatabaseColumns.LoopConditionColumnName].ToString(), removeCondition);
		}
	}

	private static string RemoveLoopCondition(string scnValue, string removeCondition)
	{
		if (scnValue == removeCondition)
		{
			return string.Empty;
		}
		string text = string.Empty;
		int num = scnValue.IndexOf(removeCondition);
		int num2 = -1;
		if (num > 0)
		{
			text = scnValue.Substring(0, num - "_ _".Length);
			num2 = scnValue.IndexOf("_ _", num);
		}
		if (num2 != -1)
		{
			if (num > 0)
			{
				return text + scnValue.Substring(num2);
			}
			return text + scnValue.Substring(num2 + "_ _".Length);
		}
		return scnValue;
	}

	public static DataTable GetFilteredTable(ref FormatArgs fargs, out string errorMessage)
	{
		errorMessage = "";
		try
		{
			if (fargs.DataSource == null)
			{
				return null;
			}
			DataTable dataTable = fargs.DataSource.Copy();
			List<string> list = new List<string>();
			foreach (DataColumn column in dataTable.Columns)
			{
				list.Add(column.ColumnName);
			}
			foreach (string item in list)
			{
				if (fargs.DoNotDisplayColumns.Contains(item))
				{
					if (dataTable.Columns.Contains(item) && !fargs.RequiredColumns.Contains(item))
					{
						dataTable.Columns.Remove(item);
					}
				}
				else if (fargs.AvailableColumns.Contains(item) && !fargs.SelectedColumns.Contains(item) && item != "SessionDataRID" && dataTable.Columns.Contains(item))
				{
					dataTable.Columns.Remove(item);
				}
			}
			int num = 0;
			if (fargs.ColumnsBeforeCalculatedColumns.Count > 0)
			{
				foreach (string columnsBeforeCalculatedColumn in fargs.ColumnsBeforeCalculatedColumns)
				{
					if (columnsBeforeCalculatedColumn.Length > 0 && dataTable.Columns.Contains(columnsBeforeCalculatedColumn))
					{
						try
						{
							dataTable.Columns[columnsBeforeCalculatedColumn].SetOrdinal(num);
							num++;
						}
						catch
						{
						}
					}
				}
			}
			List<string> list2 = new List<string>();
			foreach (DataColumn column2 in dataTable.Columns)
			{
				if (!fargs.ColumnsAfterCalculatedColumns.Contains(column2.ColumnName) && !fargs.ColumnsBeforeCalculatedColumns.Contains(column2.ColumnName))
				{
					list2.Add(column2.ColumnName);
				}
			}
			foreach (string item2 in list2)
			{
				try
				{
					dataTable.Columns[item2].SetOrdinal(num);
					num++;
				}
				catch
				{
				}
			}
			if (fargs.ColumnsAfterCalculatedColumns.Count > 0)
			{
				foreach (string columnsAfterCalculatedColumn in fargs.ColumnsAfterCalculatedColumns)
				{
					if (columnsAfterCalculatedColumn.Length > 0 && dataTable.Columns.Contains(columnsAfterCalculatedColumn))
					{
						try
						{
							dataTable.Columns[columnsAfterCalculatedColumn].SetOrdinal(num);
							num++;
						}
						catch
						{
						}
					}
				}
			}
			if (fargs.IsQMTDatabase && dataTable.Columns.Contains("SerialID"))
			{
				dataTable.Columns["SerialID"].SetOrdinal(0);
			}
			else if (dataTable.Columns.Contains("UUT_SN"))
			{
				dataTable.Columns["UUT_SN"].SetOrdinal(0);
			}
			if (fargs.ParameterColumns.Count > 0)
			{
				try
				{
					fargs.ParameterColumnsStartIndex = dataTable.Columns[fargs.ParameterColumns[0]].Ordinal;
				}
				catch
				{
				}
				try
				{
					fargs.ParameterColumnsEndIndex = dataTable.Columns[fargs.ParameterColumns[fargs.ParameterColumns.Count - 1]].Ordinal;
				}
				catch
				{
				}
			}
			return dataTable;
		}
		catch (Exception ex)
		{
			errorMessage = "Error retrieving column filtered table - " + ex.Message;
			return null;
		}
	}

	public static DataTable FormatInXml(DataSet ds, FormatOptions Options, out double[,] LimitsArray, out int FirstParamCol)
	{
		return FormatInXml(ds, Options, out LimitsArray, out FirstParamCol, new ArrayList(), includevisitnum: false, ignoreloop: false);
	}

	public static DataTable FormatInXml(DataSet ds, FormatOptions Options, out double[,] LimitsArray, out int FirstParamCol, ArrayList NewColumnsAdded, bool includevisitnum, bool ignoreloop)
	{
		cancel = false;
		bool flag = false;
		int count = ds.Tables[0].Rows.Count;
		LimitsArray = new double[2, count];
		DataTable dataTable = new DataTable("MyDataTable");
		dataTable.Columns.Add("PRIME_KEY", Type.GetType("System.String"));
		dataTable.PrimaryKey = new DataColumn[1] { dataTable.Columns["PRIME_KEY"] };
		dataTable.Columns.Add("UUT_SN", Type.GetType("System.String"));
		dataTable.Columns.Add("TimeStamp", Type.GetType("System.String"));
		if (includevisitnum)
		{
			dataTable.Columns.Add("VisitNumber", Type.GetType("System.String"));
		}
		dataTable.Columns.Add("LoopConditions", Type.GetType("System.String"));
		Hashtable hashtable = new Hashtable();
		if (NewColumnsAdded.Count > 0)
		{
			foreach (string item in NewColumnsAdded)
			{
				dataTable.Columns.Add(item, Type.GetType("System.String"));
				hashtable[item] = ds.Tables[0].Columns[item].Ordinal;
			}
		}
		DataView defaultView = dataTable.DefaultView;
		defaultView.Sort = "PRIME_KEY";
		FirstParamCol = -1;
		if (ds.Tables.Count == 0)
		{
			return null;
		}
		DataTable dataTable2 = ds.Tables[0];
		List<string> list = new List<string>();
		StringDictionary stringDictionary = new StringDictionary();
		foreach (DataRow row2 in dataTable2.Rows)
		{
			object[] itemArray = row2.ItemArray;
			string text2 = (string)itemArray[5];
			string text3 = (string)itemArray[6];
			if (stringDictionary.ContainsKey(text3))
			{
				string text4 = stringDictionary[text3].ToString();
				if (!(text4 == text2) && !list.Contains(text3))
				{
					list.Add(text3);
				}
			}
			stringDictionary[text3] = text2;
		}
		int num = 0;
		foreach (DataRow row3 in dataTable2.Rows)
		{
			if (cancel)
			{
				break;
			}
			object[] itemArray2 = row3.ItemArray;
			string text5 = (string)itemArray2[5];
			string text6 = (string)itemArray2[6];
			string text7 = text6;
			if (list.Contains(text6))
			{
				text7 = text5 + SEP + text6;
			}
			string text8 = ((itemArray2[18] is DBNull) ? "" : ((string)itemArray2[18]));
			if (Options == FormatOptions.Expanded && text8 != "")
			{
				text7 = text7 + SEP + text8;
			}
			if (!(itemArray2[19] is DBNull))
			{
				text7 = text7 + "_" + (int)itemArray2[19];
				flag = true;
			}
			else
			{
				flag = false;
			}
			if (dataTable.Columns[text7] == null)
			{
				dataTable.Columns.Add(text7, Type.GetType("System.String"));
				if (FirstParamCol == -1)
				{
					FirstParamCol = dataTable.Columns[text7].Ordinal;
				}
				try
				{
					if (!flag)
					{
						LimitsArray[0, dataTable.Columns[text7].Ordinal - FirstParamCol] = (double)itemArray2[7];
						LimitsArray[1, dataTable.Columns[text7].Ordinal - FirstParamCol] = (double)itemArray2[9];
					}
					else
					{
						LimitsArray[0, dataTable.Columns[text7].Ordinal - FirstParamCol] = (double)itemArray2[20];
						LimitsArray[1, dataTable.Columns[text7].Ordinal - FirstParamCol] = (double)itemArray2[22];
					}
				}
				catch
				{
					LimitsArray[0, dataTable.Columns[text7].Ordinal - FirstParamCol] = -99999.0;
					LimitsArray[1, dataTable.Columns[text7].Ordinal - FirstParamCol] = 99999.0;
				}
			}
			int num2 = (int)itemArray2[0];
			string text9 = ((Options == FormatOptions.Expanded) ? num2.ToString() : ((!ignoreloop) ? (num2 + text8) : num2.ToString()));
			try
			{
				dataTable.Rows.Find(text9);
				int num3 = defaultView.Find(text9);
				if (num3 == -1)
				{
					DataRow dataRow3 = dataTable.NewRow();
					dataRow3["PRIME_KEY"] = text9;
					dataRow3["UUT_SN"] = (string)itemArray2[1];
					dataRow3["TimeStamp"] = itemArray2[13].ToString();
					if (includevisitnum)
					{
						dataRow3["VisitNumber"] = itemArray2[15].ToString();
					}
					if (NewColumnsAdded.Count > 0)
					{
						foreach (string item2 in NewColumnsAdded)
						{
							int num4 = int.Parse(hashtable[item2].ToString());
							dataRow3[item2] = itemArray2[num4].ToString();
						}
					}
					dataRow3["LoopConditions"] = text8;
					if (!flag)
					{
						if (!(itemArray2[8] is DBNull))
						{
							dataRow3[text7] = ((double)itemArray2[8]).ToString();
						}
						else if (!(itemArray2[10] is DBNull))
						{
							dataRow3[text7] = (string)itemArray2[10];
						}
						else
						{
							dataRow3[text7] = " ";
						}
					}
					else
					{
						dataRow3[text7] = ((double)itemArray2[21]).ToString();
					}
					dataTable.Rows.Add(dataRow3);
				}
				else
				{
					DataRow row = defaultView[num3].Row;
					row.BeginEdit();
					if (!flag)
					{
						if (!(itemArray2[8] is DBNull))
						{
							row[text7] = ((double)itemArray2[8]).ToString();
						}
						else if (!(itemArray2[10] is DBNull))
						{
							row[text7] = (string)itemArray2[10];
						}
						else
						{
							row[text7] = " ";
						}
					}
					else
					{
						row[text7] = ((double)itemArray2[21]).ToString();
					}
					dataTable.AcceptChanges();
				}
			}
			catch (Exception arg)
			{
				Console.WriteLine("Something bad happened : {0}", arg);
			}
			num++;
		}
		try
		{
			dataTable.PrimaryKey = null;
			dataTable.Columns.Remove("PRIME_KEY");
			FirstParamCol--;
			if (Options == FormatOptions.Expanded || ignoreloop)
			{
				dataTable.Columns.Remove("LoopConditions");
				FirstParamCol--;
			}
		}
		catch
		{
		}
		return dataTable;
	}

	public static bool TryGetRoundedValue(double dbValue, int noOfDecimalsAfterZero, out double roundedDbValue)
	{
		roundedDbValue = dbValue;
		string text = Convert.ToString(dbValue);
		if (text.Length > 0)
		{
			int decimals = noOfDecimalsAfterZero;
			string pattern = "[.][0]+";
			Regex regex = new Regex(pattern);
			if (regex.IsMatch(text))
			{
				Match match = regex.Match(text);
				decimals = match.Length - 1 + noOfDecimalsAfterZero;
			}
			if (decimal.TryParse(text, out var result))
			{
				result = decimal.Round(result, decimals);
				roundedDbValue = decimal.ToDouble(result);
				return true;
			}
			return false;
		}
		return false;
	}

	public static DataTable GetDataInExpandedOrWideView(ref FormatArgs fargs, out string errorMessage, ref bool isCancelled)
	{
		lock (objLockWideViewObject)
		{
			errorMessage = "";
			DataTable dataTable = new DataTable("WideViewResults");
			bool flag = false;
			if (fargs.SelectedFormatOption == FormatOptions.Expanded)
			{
				if (currentExpandedView == null)
				{
					flag = true;
				}
			}
			else if (fargs.SelectedFormatOption == FormatOptions.WideView && currentWideView == null)
			{
				flag = true;
			}
			try
			{
				if (!flag)
				{
					dataTable = ((fargs.SelectedFormatOption != 0) ? currentWideView.Copy() : currentExpandedView.Copy());
				}
				else
				{
					currentParamInfoDictionary = new Dictionary<string, ParameterInfo>();
					currentWideViewParamColumms = new List<string>();
					if (fargs.DataSource == null)
					{
						return null;
					}
					if (cancel)
					{
						isCancelled = true;
						errorMessage = "Wide View Formatting was cancelled";
						cancel = false;
						return null;
					}
					DataTable tbl = fargs.DataSource.Copy();
					tbl = RemoveTestsWithNoParameters(tbl);
					tbl = ApplyLoopConditionFilter(tbl, "LastVisit__1");
					foreach (DataColumn column in tbl.Columns)
					{
						DataColumn dataColumn2 = new DataColumn(column.ColumnName);
						foreach (string key in column.ExtendedProperties.Keys)
						{
							dataColumn2.ExtendedProperties[key] = column.ExtendedProperties[key];
						}
						if (column.DataType != typeof(string))
						{
							dataColumn2.DataType = column.DataType;
						}
						else
						{
							dataColumn2.DataType = typeof(string);
						}
						dataTable.Columns.Add(dataColumn2);
					}
					List<string> list = new List<string>();
					string text = "";
					if (cancel)
					{
						isCancelled = true;
						errorMessage = "Wide View Formatting was cancelled";
						cancel = false;
						return null;
					}
					dataTable.Columns.Add("PRIME_KEY", Type.GetType("System.String"));
					dataTable.PrimaryKey = new DataColumn[1] { dataTable.Columns["PRIME_KEY"] };
					dataTable.Columns["PRIME_KEY"].SetOrdinal(0);
					int count = dataTable.Columns.Count;
					DataView defaultView = dataTable.DefaultView;
					defaultView.Sort = "PRIME_KEY";
					DataTable dataTable2 = tbl.DefaultView.ToTable(true, "TestName", "ParameterName");
					foreach (DataRow row2 in tbl.Rows)
					{
						try
						{
							if (cancel)
							{
								isCancelled = true;
								errorMessage = "Wide View Formatting was cancelled";
								cancel = false;
								return null;
							}
							string text2;
							try
							{
								text2 = row2["TestName"].ToString();
							}
							catch
							{
								text2 = "";
							}
							string text3;
							try
							{
								text3 = row2["ParameterName"].ToString();
							}
							catch
							{
								text3 = "";
							}
							List<string> list2 = new List<string>();
							List<string> list3 = new List<string>();
							if (!list2.Contains(text3))
							{
								DataRow[] array = dataTable2.Select("ParameterName = '" + text3 + "'");
								if (array.Length > 1)
								{
									list3.Add(text3);
								}
								list2.Add(text3);
							}
							string text4 = "";
							text4 = ((!list3.Contains(text3)) ? text3 : (text3 + " (" + text2 + ")"));
							if (tbl.Columns.Contains("ScnValue") && row2["ScnValue"] != null)
							{
								text = row2["ScnValue"].ToString();
							}
							if (text.Contains("RetryCount"))
							{
								text = RemoveLoopCondition(text, "RetryCount");
							}
							if (text.Contains("LastVisit"))
							{
								text = RemoveLoopCondition(text, "LastVisit");
							}
							if (fargs.SelectedFormatOption == FormatOptions.Expanded && text.Length > 0)
							{
								text4 = text4 + " (" + text + ")";
							}
							bool flag2 = false;
							if (tbl.Columns.Contains("ArrayParamIndex"))
							{
								if (!(row2["ArrayParamIndex"] is DBNull))
								{
									text4 = text4 + "_" + row2["ArrayParamIndex"].ToString();
									flag2 = true;
								}
								else
								{
									flag2 = false;
								}
							}
							else
							{
								flag2 = false;
							}
							if (dataTable.Columns.Contains(text4) && dataTable.Columns[text4].Ordinal < count)
							{
								text4 = "[Parameter] " + text4;
							}
							if (!dataTable.Columns.Contains(text4))
							{
								bool flag3 = false;
								flag3 = (flag2 ? (!(row2["ArrayResult"] is DBNull)) : (!(row2["NumValue"] is DBNull)));
								string columnName = text4 + "__LL";
								dataTable.Columns.Add(columnName, typeof(double));
								if (flag3)
								{
									dataTable.Columns.Add(text4, typeof(double));
								}
								else
								{
									dataTable.Columns.Add(text4, typeof(string));
								}
								string columnName2 = text4 + "__UL";
								dataTable.Columns.Add(columnName2, typeof(double));
								fargs.NumberOfColumnsAdded++;
								list.Add(text4);
								fargs.ParameterColumns.Add(text4);
								currentWideViewParamColumms.Add(text4);
								if (fargs.ParameterColumnsStartIndex == -1)
								{
									fargs.ParameterColumnsStartIndex = dataTable.Columns[text4].Ordinal;
								}
								fargs.ParameterColumnsEndIndex = dataTable.Columns[text4].Ordinal;
								_ = dataTable.Columns[text4].Ordinal;
								_ = fargs.ParameterColumnsStartIndex;
								ParameterInfo parameterInfo = new ParameterInfo();
								double upperLimit = double.NaN;
								double lowerLimit = double.NaN;
								string units = "-";
								try
								{
									if (flag2)
									{
										upperLimit = double.Parse(Convert.ToString(row2["ArrayUpperLimit"]));
										lowerLimit = double.Parse(Convert.ToString(row2["ArrayLowerLimit"]));
									}
									else
									{
										upperLimit = double.Parse(Convert.ToString(row2["UpperLimit"]));
										lowerLimit = double.Parse(Convert.ToString(row2["LowerLimit"]));
									}
									if (tbl.Columns.Contains("UOM"))
									{
										units = row2["UOM"].ToString();
									}
								}
								catch
								{
								}
								parameterInfo.UpperLimit = upperLimit;
								parameterInfo.LowerLimit = lowerLimit;
								parameterInfo.Units = units;
								currentParamInfoDictionary[text4] = parameterInfo;
							}
							long result;
							try
							{
								string s = Convert.ToString(row2["SessionDataRID"]);
								if (!long.TryParse(s, out result))
								{
									errorMessage += "\r\nNo SessionDataRid found";
									result = -1L;
								}
							}
							catch
							{
								errorMessage += "\r\nNo SessionDataRid found";
								result = -1L;
							}
							if (result <= -1)
							{
								continue;
							}
							string text5 = ((fargs.SelectedFormatOption == FormatOptions.Expanded) ? result.ToString() : ((!fargs.IgnoreLoopConditions) ? (result + text) : result.ToString()));
							string text6 = text5;
							try
							{
								int num = 0;
								while (true)
								{
									int num2 = defaultView.Find(text5);
									if (num2 > -1)
									{
										DataRow row = defaultView[num2].Row;
										if (row == null)
										{
											continue;
										}
										if (row[text4] is DBNull)
										{
											if (!flag2)
											{
												if (!(row2["NumValue"] is DBNull))
												{
													double roundedDbValue = (double)row2["NumValue"];
													TryGetRoundedValue(roundedDbValue, 4, out roundedDbValue);
													row[text4] = roundedDbValue.ToString();
												}
												else if (!(row2["CharValue"] is DBNull))
												{
													row[text4] = (string)row2["CharValue"];
												}
												row[text4 + "__LL"] = row2["LowerLimit"];
												row[text4 + "__UL"] = row2["UpperLimit"];
											}
											else
											{
												if (!(row2["ArrayResult"] is DBNull))
												{
													double roundedDbValue2 = (double)row2["ArrayResult"];
													TryGetRoundedValue(roundedDbValue2, 4, out roundedDbValue2);
													row[text4] = roundedDbValue2.ToString();
												}
												else if (!(row2["ArrayParamCharResult"] is DBNull))
												{
													row[text4] = (string)row2["ArrayParamCharResult"];
												}
												row[text4 + "__UL"] = row2["ArrayUpperLimit"];
												row[text4 + "__LL"] = row2["ArrayLowerLimit"];
											}
											break;
										}
										text5 = text6 + "%%" + num;
										num++;
										continue;
									}
									DataRow dataRow2 = dataTable.NewRow();
									dataRow2["PRIME_KEY"] = text5;
									foreach (DataColumn column2 in tbl.Columns)
									{
										try
										{
											if (!(row2[column2.ColumnName] is DBNull))
											{
												dataRow2[column2.ColumnName] = row2[column2.ColumnName];
											}
										}
										catch
										{
										}
									}
									if (!flag2)
									{
										try
										{
											if (!(row2["NumValue"] is DBNull))
											{
												double roundedDbValue3 = (double)row2["NumValue"];
												TryGetRoundedValue(roundedDbValue3, 4, out roundedDbValue3);
												dataRow2[text4] = roundedDbValue3.ToString();
											}
											else if (!(row2["CharValue"] is DBNull))
											{
												dataRow2[text4] = (string)row2["CharValue"];
											}
											else
											{
												dataRow2[text4] = " ";
											}
											dataRow2[text4 + "__LL"] = row2["LowerLimit"];
											dataRow2[text4 + "__UL"] = row2["UpperLimit"];
										}
										catch
										{
										}
									}
									else
									{
										try
										{
											if (!(row2["ArrayResult"] is DBNull))
											{
												double roundedDbValue4 = (double)row2["ArrayResult"];
												TryGetRoundedValue(roundedDbValue4, 4, out roundedDbValue4);
												dataRow2[text4] = roundedDbValue4.ToString();
											}
											else if (!(row2["ArrayParamCharResult"] is DBNull))
											{
												dataRow2[text4] = (string)row2["ArrayParamCharResult"];
											}
											dataRow2[text4 + "__UL"] = row2["ArrayUpperLimit"];
											dataRow2[text4 + "__LL"] = row2["ArrayLowerLimit"];
										}
										catch
										{
										}
									}
									dataTable.Rows.Add(dataRow2);
									break;
								}
							}
							catch
							{
							}
						}
						catch
						{
						}
					}
					try
					{
						dataTable.PrimaryKey = null;
						dataTable.Columns.Remove("PRIME_KEY");
						fargs.ParameterColumnsStartIndex--;
						if (fargs.SelectedFormatOption == FormatOptions.Expanded || fargs.IgnoreLoopConditions)
						{
							dataTable.Columns.Remove("ScnValue");
							fargs.ParameterColumnsStartIndex--;
						}
					}
					catch
					{
					}
					if (fargs.IsQMTDatabase)
					{
						if (dataTable.Columns.Contains("UUT_SN"))
						{
							if (dataTable.Columns["UUT_SN"].Ordinal < fargs.ParameterColumnsStartIndex)
							{
								fargs.ParameterColumnsStartIndex--;
							}
							if (dataTable.Columns["UUT_SN"].Ordinal < fargs.ParameterColumnsEndIndex)
							{
								fargs.ParameterColumnsEndIndex--;
							}
							dataTable.Columns.Remove("UUT_SN");
						}
					}
					else if (dataTable.Columns.Contains("SerialID"))
					{
						if (dataTable.Columns["SerialID"].Ordinal < fargs.ParameterColumnsStartIndex)
						{
							fargs.ParameterColumnsStartIndex--;
						}
						if (dataTable.Columns["SerialID"].Ordinal < fargs.ParameterColumnsEndIndex)
						{
							fargs.ParameterColumnsEndIndex--;
						}
						dataTable.Columns.Remove("SerialID");
					}
					if (dataTable.Columns.Contains("TestName"))
					{
						dataTable.Columns.Remove("TestName");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("ParameterName"))
					{
						dataTable.Columns.Remove("ParameterName");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("UpperLimit"))
					{
						dataTable.Columns.Remove("UpperLimit");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("ArrayUpperLimit"))
					{
						dataTable.Columns.Remove("ArrayUpperLimit");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("LowerLimit"))
					{
						dataTable.Columns.Remove("LowerLimit");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("ArrayLowerLimit"))
					{
						dataTable.Columns.Remove("ArrayLowerLimit");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("CharValue"))
					{
						dataTable.Columns.Remove("CharValue");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("ArrayParamCharResult"))
					{
						dataTable.Columns.Remove("ArrayParamCharResult");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("NumValue"))
					{
						dataTable.Columns.Remove("NumValue");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("ArrayResult"))
					{
						dataTable.Columns.Remove("ArrayResult");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("ArrayParamIndex"))
					{
						dataTable.Columns.Remove("ArrayParamIndex");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("ParamPassFail"))
					{
						dataTable.Columns.Remove("ParamPassFail");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("SessionDataRID"))
					{
						dataTable.Columns.Remove("SessionDataRID");
						fargs.ParameterColumnsStartIndex--;
					}
					if (dataTable.Columns.Contains("NodeDataRID"))
					{
						dataTable.Columns.Remove("NodeDataRID");
						fargs.ParameterColumnsStartIndex--;
					}
					if (fargs.ParameterColumns.Count > 0)
					{
						fargs.ParameterColumnsStartIndex = dataTable.Columns[fargs.ParameterColumns[0]].Ordinal;
						fargs.ParameterColumnsEndIndex = dataTable.Columns[fargs.ParameterColumns[fargs.ParameterColumns.Count - 1]].Ordinal;
					}
					else
					{
						fargs.ParameterColumnsStartIndex = -1;
						fargs.ParameterColumnsEndIndex = -1;
					}
					if (fargs.SelectedFormatOption == FormatOptions.Expanded)
					{
						currentExpandedView = dataTable.Copy();
					}
					else if (fargs.SelectedFormatOption == FormatOptions.WideView)
					{
						currentWideView = dataTable.Copy();
					}
					_fargs = fargs;
				}
				fargs.ParameterColumnsStartIndex = _fargs.ParameterColumnsStartIndex;
				fargs.ParameterColumnsEndIndex = _fargs.ParameterColumnsEndIndex;
				fargs.ParameterColumns = _fargs.ParameterColumns;
				if (!fargs.IncludeParamRunTimeLimits)
				{
					List<string> list4 = new List<string>();
					foreach (DataColumn column3 in dataTable.Columns)
					{
						string text7 = column3.ColumnName + "__UL";
						string text8 = column3.ColumnName + "__LL";
						if (dataTable.Columns.Contains(text7))
						{
							list4.Add(text7);
						}
						if (dataTable.Columns.Contains(text8))
						{
							list4.Add(text8);
						}
					}
					foreach (string item in list4)
					{
						if (dataTable.Columns.Contains(item))
						{
							dataTable.Columns.Remove(item);
						}
					}
				}
				return dataTable;
			}
			catch (Exception ex)
			{
				errorMessage = "Error retrieving wide view - " + ex.Message;
				return null;
			}
		}
	}

	public static bool IsNumeric(string valueString)
	{
		double result;
		return double.TryParse(valueString, out result);
	}

	public static DataTable ParseRunTitle(DataTable sourceTable, bool removedelimitedcolumn, out List<string> runtitlecolumns, out string errorMessage)
	{
		return ParseRunTitle(sourceTable, removedelimitedcolumn, null, null, out runtitlecolumns, out errorMessage);
	}

	public static DataTable ParseRunTitle(DataTable sourceTable, bool removedelimitedcolumn, BackgroundWorker backgroundWorker, DoWorkEventArgs e, out List<string> runtitlecolumns, out string errorMessage)
	{
		lock (objLockParseDelimitedColumn)
		{
			DataTable dataTable = null;
			if (sourceTable.Columns.Contains("RunTitle"))
			{
				errorMessage = "";
				if (backgroundWorker != null)
				{
					if (backgroundWorker.WorkerSupportsCancellation && backgroundWorker.CancellationPending)
					{
						errorMessage = "Error parsing Run Title - User Cancelled";
						e.Cancel = true;
						runtitlecolumns = new List<string>();
						return null;
					}
					if (backgroundWorker.WorkerReportsProgress)
					{
						backgroundWorker.ReportProgress(0, "Parsing Run Titles ....");
					}
				}
				dataTable = ParseDelimitedItemColumn(sourceTable, "RunTitle", "", "_ _", "__", "RUNTITLE_", backgroundWorker, e, out runtitlecolumns, out errorMessage);
				if (dataTable != null && removedelimitedcolumn && dataTable.Columns.Contains("RunTitle"))
				{
					dataTable.Columns.Remove("RunTitle");
				}
			}
			else
			{
				errorMessage = string.Empty;
				runtitlecolumns = new List<string>();
				dataTable = sourceTable;
			}
			return dataTable;
		}
	}

	public static DataTable ParseLoopConditions(DataTable sourceTable, bool removedelimitedcolumn, out List<string> loopconditioncolumns, out string errorMessage)
	{
		return ParseLoopConditions(sourceTable, removedelimitedcolumn, null, null, out loopconditioncolumns, out errorMessage);
	}

	public static DataTable ParseLoopConditions(DataTable sourceTable, bool removedelimitedcolumn, BackgroundWorker backgroundWorker, DoWorkEventArgs e, out List<string> loopconditioncolumns, out string errorMessage)
	{
		lock (objLockParseDelimitedColumn)
		{
			errorMessage = "";
			if (backgroundWorker != null)
			{
				if (backgroundWorker.WorkerSupportsCancellation && backgroundWorker.CancellationPending)
				{
					errorMessage = "Error parsing loop conditions - User Cancelled";
					e.Cancel = true;
					loopconditioncolumns = new List<string>();
					return null;
				}
				if (backgroundWorker.WorkerReportsProgress)
				{
					backgroundWorker.ReportProgress(0, "Parsing Loop Conditions ....");
				}
			}
			DataTable dataTable = ParseDelimitedItemColumn(sourceTable, "ScnValue", "_._", "_ _", "__", "LOOP_", backgroundWorker, e, out loopconditioncolumns, out errorMessage);
			if (dataTable != null && removedelimitedcolumn && dataTable.Columns.Contains("ScnValue"))
			{
				dataTable.Columns.Remove("ScnValue");
			}
			return dataTable;
		}
	}

	public static DataTable ParseLoopConditions(DataTable sourceTable, string loopConditionColName, bool removedelimitedcolumn, out List<string> loopconditioncolumns, out string errorMessage)
	{
		return ParseLoopConditions(sourceTable, loopConditionColName, removedelimitedcolumn, null, null, out loopconditioncolumns, out errorMessage);
	}

	public static DataTable ParseLoopConditions(DataTable sourceTable, string loopConditionColName, bool removedelimitedcolumn, BackgroundWorker backgroundWorker, DoWorkEventArgs e, out List<string> loopconditioncolumns, out string errorMessage)
	{
		lock (objLockParseDelimitedColumn)
		{
			errorMessage = "";
			if (backgroundWorker != null)
			{
				if (backgroundWorker.WorkerSupportsCancellation && backgroundWorker.CancellationPending)
				{
					errorMessage = "Error parsing loop conditions - User Cancelled";
					e.Cancel = true;
					loopconditioncolumns = new List<string>();
					return null;
				}
				if (backgroundWorker.WorkerReportsProgress)
				{
					backgroundWorker.ReportProgress(0, "Parsing Loop Conditions ....");
				}
			}
			DataTable dataTable = ParseDelimitedItemColumn(sourceTable, loopConditionColName, "_._", "_ _", "__", "LOOP_", backgroundWorker, e, out loopconditioncolumns, out errorMessage);
			if (dataTable != null && removedelimitedcolumn && dataTable.Columns.Contains("ScnValue"))
			{
				dataTable.Columns.Remove("ScnValue");
			}
			return dataTable;
		}
	}

	public static DataTable ParseDelimitedItemColumn(DataTable sourcetable, string delimitedcolumn, string scenariondelimiter, string itemdelimiter, string valuedelimiter, string columnPrefix, out List<string> newcolumnsadded, out string errormessage)
	{
		return ParseDelimitedItemColumn(sourcetable, delimitedcolumn, scenariondelimiter, itemdelimiter, valuedelimiter, columnPrefix, null, null, out newcolumnsadded, out errormessage);
	}

	public static DataTable ParseDelimitedItemColumn(DataTable sourcetable, string delimitedcolumn, string scenariondelimiter, string itemdelimiter, string valuedelimiter, string columnPrefix, BackgroundWorker backgroundWorker, DoWorkEventArgs e, out List<string> newcolumnsadded, out string errorMessage)
	{
		lock (objLockParseDelimitedColumn)
		{
			Dictionary<string, Type> dictionary = new Dictionary<string, Type>();
			TypePrecedenceRuleImplementer typePrecedenceRuleImplementer = new TypePrecedenceRuleImplementer();
			errorMessage = "";
			newcolumnsadded = new List<string>();
			DataTable dataTable = null;
			try
			{
				int count = sourcetable.Columns.Count;
				if (!sourcetable.Columns.Contains(delimitedcolumn))
				{
					errorMessage = "Error parsing delimited column - Column " + delimitedcolumn + " not present!";
					return null;
				}
				if (backgroundWorker != null && backgroundWorker.WorkerSupportsCancellation && backgroundWorker.CancellationPending)
				{
					errorMessage = "User cancelled the operation.";
					e.Cancel = true;
					return null;
				}
				new List<string>();
				new List<string>();
				dataTable = sourcetable.Clone();
				int count2 = sourcetable.Rows.Count;
				int num = 0;
				foreach (DataRow row in sourcetable.Rows)
				{
					DataRow dataRow2 = dataTable.NewRow();
					try
					{
						dataRow2.ItemArray = row.ItemArray;
						if (row[delimitedcolumn] == null)
						{
							continue;
						}
						string text = Convert.ToString(row[delimitedcolumn]).Trim();
						string[] array = text.Split(new string[1] { scenariondelimiter }, StringSplitOptions.None);
						string[] array2 = array;
						foreach (string text2 in array2)
						{
							if (text2.Length <= 0)
							{
								continue;
							}
							string[] array3 = text2.Split(new string[1] { itemdelimiter }, StringSplitOptions.None);
							string[] array4 = array3;
							foreach (string text3 in array4)
							{
								if (text3.Length <= 0)
								{
									continue;
								}
								string text4 = text3.Substring(0, text3.LastIndexOf(valuedelimiter));
								string text5 = text3.Substring(text4.Length + valuedelimiter.Length);
								if (!string.IsNullOrEmpty(text4) && !string.IsNullOrEmpty(text5) && !(text4.Trim().ToLower() == "RetryCount".ToLower()))
								{
									string text6 = "";
									Type typeFromHandle = typeof(object);
									text6 = ((!dataTable.Columns.Contains(text4)) ? text4 : ((dataTable.Columns[text4].Ordinal >= count) ? text4 : (columnPrefix + text4)));
									if (!dataTable.Columns.Contains(text6))
									{
										DataColumn column = new DataColumn(text6, typeFromHandle);
										dataTable.Columns.Add(column);
										newcolumnsadded.Add(text6);
									}
									dataRow2[text6] = text5;
									Type delimitedValueType = GetDelimitedValueType(text5);
									if (!dictionary.ContainsKey(text6))
									{
										dictionary.Add(text6, delimitedValueType);
									}
									else
									{
										dictionary[text6] = typePrecedenceRuleImplementer.GetTypeByPrecedence(delimitedValueType, dictionary[text6]);
									}
								}
							}
						}
						goto IL_02cc;
					}
					catch
					{
						goto IL_02cc;
					}
					IL_02cc:
					dataTable.Rows.Add(dataRow2);
					num++;
					if (backgroundWorker == null)
					{
						continue;
					}
					if (backgroundWorker.WorkerSupportsCancellation && backgroundWorker.CancellationPending)
					{
						errorMessage = "User cancelled the operation.";
						e.Cancel = true;
						return null;
					}
					if (backgroundWorker.WorkerReportsProgress)
					{
						int num2 = num * 100 / count2;
						if (num2 > 0 && num2 % 10 == 0)
						{
							backgroundWorker.ReportProgress(num2, null);
						}
					}
				}
				string text7 = "##tmp";
				foreach (KeyValuePair<string, Type> item in dictionary)
				{
					if (dataTable.Columns.Contains(item.Key))
					{
						string text8 = item.Key + text7;
						dataTable.Columns[item.Key].ColumnName = text8;
						dataTable.Columns.Add(item.Key, item.Value);
						CopyColumn(dataTable, text8, item.Key);
						dataTable.Columns.Remove(text8);
					}
				}
			}
			catch (Exception ex)
			{
				errorMessage = "Error parsing delimited column " + delimitedcolumn + " - " + ex.Message;
				dataTable = null;
			}
			return dataTable;
		}
	}

	private static void CopyColumn(DataTable newTable, string sourceColumnName, string destinationColumnName)
	{
		foreach (DataRow row in newTable.Rows)
		{
			row[destinationColumnName] = row[sourceColumnName];
		}
	}

	private static Type GetDelimitedValueType(string itemValue)
	{
		if (int.TryParse(itemValue, out var _))
		{
			return typeof(int);
		}
		if (long.TryParse(itemValue, out var _))
		{
			return typeof(long);
		}
		if (float.TryParse(itemValue, out var _))
		{
			return typeof(float);
		}
		if (double.TryParse(itemValue, out var _))
		{
			return typeof(double);
		}
		return typeof(string);
	}

	private static bool FormatLoopValue(string LoopCondValue, ref DataTable Results, ref DataRow dataRow)
	{
		try
		{
			string text = "";
			LoopCondValue = LoopCondValue.Replace(LOOPSCENARIO_SEP, LOOPS_SEP);
			string[] array = SplitString(LoopCondValue.Trim(), LOOPS_SEP);
			string[] array2 = array;
			foreach (string text2 in array2)
			{
				if (text2 == null || text2.Trim().Length <= 0)
				{
					break;
				}
				string[] array3 = text2.Split(LOOPVALUE_SEP, StringSplitOptions.None);
				try
				{
					if (array3[0] != null && array3[0].Trim() != "")
					{
						text = array3[0].Trim();
					}
					string value = array3[1].Trim();
					if (Results.Columns[text] == null)
					{
						Results.Columns.Add(text, Type.GetType("System.String"));
						DataRow dataRow2 = Results.NewRow();
						dataRow2.ItemArray = dataRow.ItemArray;
						dataRow = Results.NewRow();
						dataRow.ItemArray = dataRow2.ItemArray;
					}
					dataRow[text] = value;
				}
				catch (Exception arg)
				{
					Console.WriteLine("Something bad happened : {0}", arg);
				}
			}
		}
		catch (Exception arg2)
		{
			Console.WriteLine("Something bad happened : {0}", arg2);
			return false;
		}
		return true;
	}

	private static string ParseRunTitleString(string runTitle)
	{
		if (runTitle.StartsWith("RUNTITLE__"))
		{
			runTitle = runTitle.Remove(0, 9);
		}
		return runTitle;
	}

	public static string[] SplitString(string theString, string Separator)
	{
		string[] array = new string[20]
		{
			theString, null, null, null, null, null, null, null, null, null,
			null, null, null, null, null, null, null, null, null, null
		};
		if (Separator.Length == 0)
		{
			return array;
		}
		if (Separator.Length == 1)
		{
			return theString.Split(Separator.ToCharArray());
		}
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int length = theString.Length;
		while (num <= length && num2 > -1)
		{
			num2 = theString.IndexOf(Separator, num);
			if (num2 == -1)
			{
				break;
			}
			array[num3] = theString.Substring(num, num2 - num);
			num3++;
			num = num2 + Separator.Length;
		}
		array[num3] = theString.Substring(num);
		return array;
	}

	public static DataTable GetDataInLongWideViewWithStatistics(ref FormatArgs fargs, out string errorMessage, ref bool isCancelled)
	{
		DataTable dataInLongWideView = GetDataInLongWideView(ref fargs, out errorMessage, ref isCancelled);
		AddStatistics(dataInLongWideView);
		return dataInLongWideView;
	}

	private static void AddStatistics(DataTable longWideViewDataTbl)
	{
		int firstSerialNumberColumnIndex = 0;
		int lastSerialNumberColumnIndex = 0;
		FindFirstAndLastSerialNumberColumns(longWideViewDataTbl, ref firstSerialNumberColumnIndex, ref lastSerialNumberColumnIndex);
		AddStatisticsColumns(longWideViewDataTbl, firstSerialNumberColumnIndex, lastSerialNumberColumnIndex);
		AddStatisticsData(longWideViewDataTbl, firstSerialNumberColumnIndex, lastSerialNumberColumnIndex);
		RemoveSerialNumberColumns(longWideViewDataTbl, firstSerialNumberColumnIndex, lastSerialNumberColumnIndex);
	}

	private static void AddStatisticsData(DataTable longWideViewDataTbl, int firstSerialNumberColumnIndex, int lastSerialNumberColumnIndex)
	{
		for (int i = 0; i < longWideViewDataTbl.Rows.Count; i++)
		{
			List<double> allNumericValuesForSerialNumberColumns = GetAllNumericValuesForSerialNumberColumns(longWideViewDataTbl, i, firstSerialNumberColumnIndex, lastSerialNumberColumnIndex);
			if (allNumericValuesForSerialNumberColumns.Count > 0)
			{
				longWideViewDataTbl.Rows[i]["Min"] = allNumericValuesForSerialNumberColumns.Min();
				longWideViewDataTbl.Rows[i]["Max"] = allNumericValuesForSerialNumberColumns.Max();
				longWideViewDataTbl.Rows[i]["Mean"] = allNumericValuesForSerialNumberColumns.Average();
				longWideViewDataTbl.Rows[i]["StdDev"] = CalculateStandardDeviation(allNumericValuesForSerialNumberColumns);
			}
			longWideViewDataTbl.Rows[i]["NumberOfUnits"] = allNumericValuesForSerialNumberColumns.Count;
		}
		longWideViewDataTbl.Columns["Mean-LSL"].Expression = "Mean-[LowerLimit]";
		longWideViewDataTbl.Columns["USL-Mean"].Expression = "[UpperLimit]-Mean";
		longWideViewDataTbl.Columns["CPK"].Expression = "(IIF(([USL-Mean] < [Mean-LSL]), [USL-Mean], [Mean-LSL])/(3*StdDev))";
	}

	private static double CalculateStandardDeviation(List<double> doubleList)
	{
		double num = doubleList.Average();
		double num2 = 0.0;
		foreach (double @double in doubleList)
		{
			double num3 = @double;
			num2 += num3 * num3;
		}
		double num4 = num2 / (double)doubleList.Count;
		return Math.Sqrt(num4 - num * num);
	}

	private static List<double> GetAllNumericValuesForSerialNumberColumns(DataTable longWideViewDataTbl, int rowIndex, int firstSerialNumberColumnIndex, int lastSerialNumberColumnIndex)
	{
		List<double> list = new List<double>();
		for (int i = firstSerialNumberColumnIndex; i <= lastSerialNumberColumnIndex; i++)
		{
			if (!Convert.IsDBNull(longWideViewDataTbl.Rows[rowIndex][i]) && double.TryParse(longWideViewDataTbl.Rows[rowIndex][i].ToString(), out var result))
			{
				list.Add(result);
			}
		}
		return list;
	}

	private static void FindFirstAndLastSerialNumberColumns(DataTable longWideViewDataTbl, ref int firstSerialNumberColumnIndex, ref int lastSerialNumberColumnIndex)
	{
		int num = longWideViewDataTbl.Columns.IndexOf("UpperLimit");
		int num2 = longWideViewDataTbl.Columns.IndexOf("DataIdentifier");
		firstSerialNumberColumnIndex = num + 1;
		lastSerialNumberColumnIndex = num2 - 1;
	}

	private static void AddStatisticsColumns(DataTable longWideViewDataTbl, int firstSerialNumberColumnIndex, int lastSerialNumberColumnIndex)
	{
		int num = ++lastSerialNumberColumnIndex;
		longWideViewDataTbl.Columns.Add("Min", Type.GetType("System.Double"));
		longWideViewDataTbl.Columns["Min"].SetOrdinal(num++);
		longWideViewDataTbl.Columns.Add("Max", Type.GetType("System.Double"));
		longWideViewDataTbl.Columns["Max"].SetOrdinal(num++);
		longWideViewDataTbl.Columns.Add("Mean", Type.GetType("System.Double"));
		longWideViewDataTbl.Columns["Mean"].SetOrdinal(num++);
		longWideViewDataTbl.Columns.Add("StdDev", Type.GetType("System.Double"));
		longWideViewDataTbl.Columns["StdDev"].SetOrdinal(num++);
		longWideViewDataTbl.Columns.Add("CPK", Type.GetType("System.Double"));
		longWideViewDataTbl.Columns["CPK"].SetOrdinal(num++);
		longWideViewDataTbl.Columns.Add("NumberOfUnits", Type.GetType("System.Double"));
		longWideViewDataTbl.Columns["NumberOfUnits"].SetOrdinal(num++);
		longWideViewDataTbl.Columns.Add("Mean-LSL", Type.GetType("System.Double"));
		longWideViewDataTbl.Columns["Mean-LSL"].SetOrdinal(num++);
		longWideViewDataTbl.Columns.Add("USL-Mean", Type.GetType("System.Double"));
		longWideViewDataTbl.Columns["USL-Mean"].SetOrdinal(num++);
	}

	private static void RemoveSerialNumberColumns(DataTable longWideViewDataTbl, int firstSerialNumberColumnIndex, int lastSerialNumberColumnIndex)
	{
		List<string> list = new List<string>();
		for (int i = firstSerialNumberColumnIndex; i <= lastSerialNumberColumnIndex; i++)
		{
			list.Add(longWideViewDataTbl.Columns[i].ColumnName);
		}
		foreach (string item in list)
		{
			longWideViewDataTbl.Columns.Remove(item);
		}
	}
}
