using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Timers;
using System.Runtime.InteropServices;	//for Dll Imports
using WaveLib;

namespace HearingAidLab
{
	
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		

		public string strVersion = "BART V3.0.5 ";
		public string Manual = string.Empty;
#if DBUG
		// These are for dumping data to an external file
		public static FileStream fsDbug;
		public static StreamWriter swDbug;
#endif
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.Label label7;
		public System.Windows.Forms.TextBox txtResultFile;
		private System.Windows.Forms.TextBox txtInitFile;
		private System.Windows.Forms.Button btnBrowseInit;
		private System.Windows.Forms.Button btnBrowseResult;
		
		
		public ChirpCal cal = null;								//if only a single has been done
		public ChirpCal LeftCal = null;							//For the left ear, if using two
		public ChirpCal RightCal = null;						//For the right ear, if using two
		
		public Definitions def = null;
		private System.ComponentModel.IContainer components;
		private StreamWriter output;

		public double CalDb = 110;
        public int MaxAmplitude = Calibrate.MaxAmplitude;
		private System.Windows.Forms.MainMenu mainMenu1;
		private System.Windows.Forms.ToolBar toolBar1;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.StatusBar statusBar1;
		private System.Windows.Forms.MenuItem CalSimple;
		private System.Windows.Forms.MenuItem CalChirp;
		private System.Windows.Forms.MenuItem menuItem4;
		private System.Windows.Forms.MenuItem RunAudiogram;
		private System.Windows.Forms.MenuItem RunSTAR;
		private System.Windows.Forms.MenuItem menuItem7;
		public System.Windows.Forms.MenuItem OptSingleScreen;
		private System.Windows.Forms.MenuItem OptTestGame;
		private System.Windows.Forms.Button btnEditDef;
		private System.Windows.Forms.GroupBox groupBox1;
		public System.Windows.Forms.TextBox txtId;
		public System.Windows.Forms.TextBox txtGroup;
		public System.Windows.Forms.TextBox txtBirth;
		public System.Windows.Forms.TextBox txtName;
		public System.Windows.Forms.ComboBox cmbGender;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.ToolBarButton tbSimpleCal;
		private System.Windows.Forms.ImageList ToolBarImages;
		private System.Windows.Forms.ToolBarButton tbChirpCal;
		private System.Windows.Forms.ToolBarButton toolBarButton3;
		private System.Windows.Forms.ToolBarButton tbAudiogram;
		private System.Windows.Forms.ToolBarButton tbStar;
		private System.Windows.Forms.Label lblVer;
		private System.Windows.Forms.StatusBarPanel sbCalibration;
		public System.Windows.Forms.CheckBox chkAppend;
		private System.Windows.Forms.GroupBox groupBox2;
		public System.Windows.Forms.TextBox txtFreqShape;
		private System.Windows.Forms.Button btnEditFreqShape;
		private System.Windows.Forms.Button btnBrowseFreqShape;
		private System.Windows.Forms.Label label8;
		private System.Windows.Forms.StatusBarPanel sbCalibrationR;
		private System.Windows.Forms.Label lbl;//2^23 / 2
		public FileInfo InitFile = null;
		private System.Timers.Timer timerLabel = new System.Timers.Timer(753);
		private ArrayList Colors = new ArrayList();
		private System.Windows.Forms.ToolBarButton toolBarButton1;
		private System.Windows.Forms.ToolBarButton toolBarButton2;
		private System.Windows.Forms.ToolBarButton tbLoudness;
		private System.Windows.Forms.MenuItem RunCategoricalLoudness;
		private System.Windows.Forms.MenuItem RunPairedComparison;
		private System.Windows.Forms.ToolBarButton tbPaired;
		private Random rand;

		

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			rand = new Random(DateTime.Now.Millisecond);
			Colors.Add(Color.Blue);
			Colors.Add(Color.Purple);
			Colors.Add(Color.Red);
			Colors.Add(Color.Yellow);
			Colors.Add(Color.DeepSkyBlue);
			Colors.Add(Color.Gold);
			Colors.Add(Color.Green);
			Colors.Add(Color.DeepPink);
			Colors.Add(Color.Magenta);
			Colors.Add(Color.Cyan);
			Colors.Add(Color.PowderBlue);
			Colors.Add(Color.SeaShell);

			InitializeComponent();
			this.Text = strVersion;
			lblVer.Text = strVersion;
			lbl.Text = "DID YOU CALIBRATE?";
			timerLabel.AutoReset = true;
			timerLabel.Elapsed += new ElapsedEventHandler(timerLabel_Elapsed);
			timerLabel.Start();
			
#if DEBUG
			txtName.Text = "Prasanna Aryal";
			txtBirth.Text = "1/1/1990";
			cmbGender.Text = "Male";
            txtInitFile.Text = @"M:\CLS\Data\New Subject Files\cls_new.def";
			//txtInitFile.Text = @"K:\Legacy\HearingAidLab_ARSC\CL.def";
			//txtInitFile.Text = @"R:\HARL\Common\Loudness\Test.def";
            txtResultFile.Text = @"M:\CLS\Data\New Subject Files\try me.txt";
			//txtFreqShape.Text = @"C:\FreqShapeQuiet.txt";


#endif
          //  this.OptSingleScreen.Checked = true;
			ReadRegistry();
			this.Closing += new CancelEventHandler(Form1_Closing);
			System.Threading.Thread t = System.Threading.Thread.CurrentThread;
			t.Priority = System.Threading.ThreadPriority.Highest;
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.label6 = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.txtInitFile = new System.Windows.Forms.TextBox();
            this.txtResultFile = new System.Windows.Forms.TextBox();
            this.btnBrowseInit = new System.Windows.Forms.Button();
            this.btnBrowseResult = new System.Windows.Forms.Button();
            this.btnEditDef = new System.Windows.Forms.Button();
            this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.CalSimple = new System.Windows.Forms.MenuItem();
            this.CalChirp = new System.Windows.Forms.MenuItem();
            this.menuItem4 = new System.Windows.Forms.MenuItem();
            this.RunAudiogram = new System.Windows.Forms.MenuItem();
            this.RunSTAR = new System.Windows.Forms.MenuItem();
            this.RunCategoricalLoudness = new System.Windows.Forms.MenuItem();
            this.RunPairedComparison = new System.Windows.Forms.MenuItem();
            this.menuItem7 = new System.Windows.Forms.MenuItem();
            this.OptSingleScreen = new System.Windows.Forms.MenuItem();
            this.OptTestGame = new System.Windows.Forms.MenuItem();
            this.toolBar1 = new System.Windows.Forms.ToolBar();
            this.tbSimpleCal = new System.Windows.Forms.ToolBarButton();
            this.tbChirpCal = new System.Windows.Forms.ToolBarButton();
            this.toolBarButton3 = new System.Windows.Forms.ToolBarButton();
            this.tbAudiogram = new System.Windows.Forms.ToolBarButton();
            this.tbStar = new System.Windows.Forms.ToolBarButton();
            this.tbLoudness = new System.Windows.Forms.ToolBarButton();
            this.tbPaired = new System.Windows.Forms.ToolBarButton();
            this.toolBarButton1 = new System.Windows.Forms.ToolBarButton();
            this.toolBarButton2 = new System.Windows.Forms.ToolBarButton();
            this.ToolBarImages = new System.Windows.Forms.ImageList(this.components);
            this.statusBar1 = new System.Windows.Forms.StatusBar();
            this.sbCalibration = new System.Windows.Forms.StatusBarPanel();
            this.sbCalibrationR = new System.Windows.Forms.StatusBarPanel();
            this.lblVer = new System.Windows.Forms.Label();
            this.lbl = new System.Windows.Forms.Label();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.txtId = new System.Windows.Forms.TextBox();
            this.txtGroup = new System.Windows.Forms.TextBox();
            this.txtBirth = new System.Windows.Forms.TextBox();
            this.txtName = new System.Windows.Forms.TextBox();
            this.cmbGender = new System.Windows.Forms.ComboBox();
            this.label5 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.chkAppend = new System.Windows.Forms.CheckBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.txtFreqShape = new System.Windows.Forms.TextBox();
            this.btnEditFreqShape = new System.Windows.Forms.Button();
            this.btnBrowseFreqShape = new System.Windows.Forms.Button();
            this.label8 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.sbCalibration)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.sbCalibrationR)).BeginInit();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.SuspendLayout();
            // 
            // label6
            // 
            this.label6.Location = new System.Drawing.Point(8, 224);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(80, 23);
            this.label6.TabIndex = 15;
            this.label6.Text = "Definitions file:";
            this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label7
            // 
            this.label7.Location = new System.Drawing.Point(16, 256);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(72, 23);
            this.label7.TabIndex = 16;
            this.label7.Text = "Result File:";
            this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // txtInitFile
            // 
            this.txtInitFile.Location = new System.Drawing.Point(96, 224);
            this.txtInitFile.Name = "txtInitFile";
            this.txtInitFile.Size = new System.Drawing.Size(272, 20);
            this.txtInitFile.TabIndex = 6;
            // 
            // txtResultFile
            // 
            this.txtResultFile.Location = new System.Drawing.Point(96, 256);
            this.txtResultFile.Name = "txtResultFile";
            this.txtResultFile.Size = new System.Drawing.Size(272, 20);
            this.txtResultFile.TabIndex = 7;
            // 
            // btnBrowseInit
            // 
            this.btnBrowseInit.Image = ((System.Drawing.Image)(resources.GetObject("btnBrowseInit.Image")));
            this.btnBrowseInit.Location = new System.Drawing.Point(456, 224);
            this.btnBrowseInit.Name = "btnBrowseInit";
            this.btnBrowseInit.Size = new System.Drawing.Size(32, 23);
            this.btnBrowseInit.TabIndex = 19;
            this.btnBrowseInit.Click += new System.EventHandler(this.btnBrowseInit_Click);
            // 
            // btnBrowseResult
            // 
            this.btnBrowseResult.Image = ((System.Drawing.Image)(resources.GetObject("btnBrowseResult.Image")));
            this.btnBrowseResult.Location = new System.Drawing.Point(456, 256);
            this.btnBrowseResult.Name = "btnBrowseResult";
            this.btnBrowseResult.Size = new System.Drawing.Size(32, 23);
            this.btnBrowseResult.TabIndex = 20;
            this.btnBrowseResult.Click += new System.EventHandler(this.btnBrowseResult_Click);
            // 
            // btnEditDef
            // 
            this.btnEditDef.BackColor = System.Drawing.SystemColors.Control;
            this.btnEditDef.Image = ((System.Drawing.Image)(resources.GetObject("btnEditDef.Image")));
            this.btnEditDef.Location = new System.Drawing.Point(376, 224);
            this.btnEditDef.Name = "btnEditDef";
            this.btnEditDef.Size = new System.Drawing.Size(32, 23);
            this.btnEditDef.TabIndex = 23;
            this.btnEditDef.UseVisualStyleBackColor = false;
            this.btnEditDef.Click += new System.EventHandler(this.btnEditDef_Click);
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem1,
            this.menuItem4,
            this.menuItem7});
            // 
            // menuItem1
            // 
            this.menuItem1.Index = 0;
            this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.CalSimple,
            this.CalChirp});
            this.menuItem1.Text = "Calibration";
            // 
            // CalSimple
            // 
            this.CalSimple.Index = 0;
            this.CalSimple.Text = "Simple Calibration";
            this.CalSimple.Click += new System.EventHandler(this.CalSimple_Click);
            // 
            // CalChirp
            // 
            this.CalChirp.Index = 1;
            this.CalChirp.Text = "Chirp Calibration";
            this.CalChirp.Click += new System.EventHandler(this.CalChirp_Click);
            // 
            // menuItem4
            // 
            this.menuItem4.Index = 1;
            this.menuItem4.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.RunAudiogram,
            this.RunSTAR,
            this.RunCategoricalLoudness,
            this.RunPairedComparison});
            this.menuItem4.Text = "Run Programs";
            // 
            // RunAudiogram
            // 
            this.RunAudiogram.Index = 0;
            this.RunAudiogram.Text = "Audiogram";
            this.RunAudiogram.Click += new System.EventHandler(this.RunAudiogram_Click);
            // 
            // RunSTAR
            // 
            this.RunSTAR.Index = 1;
            this.RunSTAR.Text = "STAR";
            this.RunSTAR.Click += new System.EventHandler(this.RunSTAR_Click);
            // 
            // RunCategoricalLoudness
            // 
            this.RunCategoricalLoudness.Index = 2;
            this.RunCategoricalLoudness.Text = "Categorical Loudness";
            this.RunCategoricalLoudness.Click += new System.EventHandler(this.RunCategoricalLoudness_Click);
            // 
            // RunPairedComparison
            // 
            this.RunPairedComparison.Index = 3;
            this.RunPairedComparison.Text = "Paired Comparison";
            this.RunPairedComparison.Click += new System.EventHandler(this.RunPairedComparison_Click);
            // 
            // menuItem7
            // 
            this.menuItem7.Index = 2;
            this.menuItem7.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.OptSingleScreen,
            this.OptTestGame});
            this.menuItem7.Text = "Options";
            // 
            // OptSingleScreen
            // 
            this.OptSingleScreen.Index = 0;
            this.OptSingleScreen.Text = "Single Screen";
            this.OptSingleScreen.Click += new System.EventHandler(this.OptSingleScreen_Click);
            // 
            // OptTestGame
            // 
            this.OptTestGame.Index = 1;
            this.OptTestGame.Text = "Test Game";
            this.OptTestGame.Click += new System.EventHandler(this.OptTestGame_Click);
            // 
            // toolBar1
            // 
            this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
            this.tbSimpleCal,
            this.tbChirpCal,
            this.toolBarButton3,
            this.tbAudiogram,
            this.tbStar,
            this.tbLoudness,
            this.tbPaired,
            this.toolBarButton1,
            this.toolBarButton2});
            this.toolBar1.DropDownArrows = true;
            this.toolBar1.ImageList = this.ToolBarImages;
            this.toolBar1.Location = new System.Drawing.Point(0, 0);
            this.toolBar1.Name = "toolBar1";
            this.toolBar1.ShowToolTips = true;
            this.toolBar1.Size = new System.Drawing.Size(560, 28);
            this.toolBar1.TabIndex = 30;
            this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
            // 
            // tbSimpleCal
            // 
            this.tbSimpleCal.ImageIndex = 0;
            this.tbSimpleCal.Name = "tbSimpleCal";
            this.tbSimpleCal.ToolTipText = "Simple Calibration";
            // 
            // tbChirpCal
            // 
            this.tbChirpCal.ImageIndex = 1;
            this.tbChirpCal.Name = "tbChirpCal";
            this.tbChirpCal.ToolTipText = "Chirp Calibration";
            // 
            // toolBarButton3
            // 
            this.toolBarButton3.Name = "toolBarButton3";
            this.toolBarButton3.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
            // 
            // tbAudiogram
            // 
            this.tbAudiogram.ImageIndex = 2;
            this.tbAudiogram.Name = "tbAudiogram";
            this.tbAudiogram.ToolTipText = "Run Audiogram";
            // 
            // tbStar
            // 
            this.tbStar.ImageIndex = 3;
            this.tbStar.Name = "tbStar";
            this.tbStar.ToolTipText = "Run EXPERIMENT";
            // 
            // tbLoudness
            // 
            this.tbLoudness.ImageIndex = 5;
            this.tbLoudness.Name = "tbLoudness";
            this.tbLoudness.ToolTipText = "Categorical Loudness";
            // 
            // tbPaired
            // 
            this.tbPaired.ImageIndex = 6;
            this.tbPaired.Name = "tbPaired";
            this.tbPaired.ToolTipText = "Paired Comparison";
            // 
            // toolBarButton1
            // 
            this.toolBarButton1.Name = "toolBarButton1";
            this.toolBarButton1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
            // 
            // toolBarButton2
            // 
            this.toolBarButton2.ImageIndex = 4;
            this.toolBarButton2.Name = "toolBarButton2";
            this.toolBarButton2.ToolTipText = "Reset to Simple Calibration";
            // 
            // ToolBarImages
            // 
            this.ToolBarImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ToolBarImages.ImageStream")));
            this.ToolBarImages.TransparentColor = System.Drawing.Color.Transparent;
            this.ToolBarImages.Images.SetKeyName(0, "");
            this.ToolBarImages.Images.SetKeyName(1, "");
            this.ToolBarImages.Images.SetKeyName(2, "");
            this.ToolBarImages.Images.SetKeyName(3, "");
            this.ToolBarImages.Images.SetKeyName(4, "");
            this.ToolBarImages.Images.SetKeyName(5, "");
            this.ToolBarImages.Images.SetKeyName(6, "");
            // 
            // statusBar1
            // 
            this.statusBar1.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.statusBar1.Location = new System.Drawing.Point(0, 355);
            this.statusBar1.Name = "statusBar1";
            this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
            this.sbCalibration,
            this.sbCalibrationR});
            this.statusBar1.ShowPanels = true;
            this.statusBar1.Size = new System.Drawing.Size(560, 22);
            this.statusBar1.TabIndex = 31;
            this.statusBar1.Text = "Calibration:";
            // 
            // sbCalibration
            // 
            this.sbCalibration.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
            this.sbCalibration.Name = "sbCalibration";
            this.sbCalibration.Text = "Calibration (L):";
            this.sbCalibration.Width = 123;
            // 
            // sbCalibrationR
            // 
            this.sbCalibrationR.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
            this.sbCalibrationR.Name = "sbCalibrationR";
            this.sbCalibrationR.Text = "Calibration (R):";
            this.sbCalibrationR.Width = 123;
            // 
            // lblVer
            // 
            this.lblVer.Font = new System.Drawing.Font("Times New Roman", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblVer.ForeColor = System.Drawing.Color.MidnightBlue;
            this.lblVer.Location = new System.Drawing.Point(8, 56);
            this.lblVer.Name = "lblVer";
            this.lblVer.Size = new System.Drawing.Size(544, 24);
            this.lblVer.TabIndex = 32;
            this.lblVer.Text = "BART V2.0.1.3 (pre-release beta)";
            this.lblVer.TextAlign = System.Drawing.ContentAlignment.TopCenter;
            // 
            // lbl
            // 
            this.lbl.Font = new System.Drawing.Font("Times New Roman", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lbl.ForeColor = System.Drawing.Color.MidnightBlue;
            this.lbl.Location = new System.Drawing.Point(8, 32);
            this.lbl.Name = "lbl";
            this.lbl.Size = new System.Drawing.Size(544, 24);
            this.lbl.TabIndex = 33;
            this.lbl.Text = "Boys Town National Research Hospital";
            this.lbl.TextAlign = System.Drawing.ContentAlignment.TopCenter;
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.txtId);
            this.groupBox1.Controls.Add(this.txtGroup);
            this.groupBox1.Controls.Add(this.txtBirth);
            this.groupBox1.Controls.Add(this.txtName);
            this.groupBox1.Controls.Add(this.cmbGender);
            this.groupBox1.Controls.Add(this.label5);
            this.groupBox1.Controls.Add(this.label4);
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Location = new System.Drawing.Point(8, 88);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(544, 96);
            this.groupBox1.TabIndex = 34;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Subject Data";
            // 
            // txtId
            // 
            this.txtId.Location = new System.Drawing.Point(348, 45);
            this.txtId.Name = "txtId";
            this.txtId.Size = new System.Drawing.Size(192, 20);
            this.txtId.TabIndex = 15;
            // 
            // txtGroup
            // 
            this.txtGroup.Location = new System.Drawing.Point(348, 21);
            this.txtGroup.Name = "txtGroup";
            this.txtGroup.Size = new System.Drawing.Size(192, 20);
            this.txtGroup.TabIndex = 13;
            // 
            // txtBirth
            // 
            this.txtBirth.Location = new System.Drawing.Point(76, 45);
            this.txtBirth.Name = "txtBirth";
            this.txtBirth.Size = new System.Drawing.Size(192, 20);
            this.txtBirth.TabIndex = 10;
            // 
            // txtName
            // 
            this.txtName.Location = new System.Drawing.Point(76, 21);
            this.txtName.Name = "txtName";
            this.txtName.Size = new System.Drawing.Size(192, 20);
            this.txtName.TabIndex = 7;
            // 
            // cmbGender
            // 
            this.cmbGender.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbGender.Items.AddRange(new object[] {
            "Female",
            "Male"});
            this.cmbGender.Location = new System.Drawing.Point(76, 69);
            this.cmbGender.Name = "cmbGender";
            this.cmbGender.Size = new System.Drawing.Size(192, 21);
            this.cmbGender.TabIndex = 12;
            // 
            // label5
            // 
            this.label5.Location = new System.Drawing.Point(276, 21);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(72, 23);
            this.label5.TabIndex = 14;
            this.label5.Text = "Group:";
            this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label4
            // 
            this.label4.Location = new System.Drawing.Point(276, 45);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(72, 23);
            this.label4.TabIndex = 11;
            this.label4.Text = "Id Number:";
            this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(4, 69);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(72, 23);
            this.label3.TabIndex = 9;
            this.label3.Text = "Gender:";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(4, 45);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(72, 23);
            this.label2.TabIndex = 8;
            this.label2.Text = "Date of Birth:";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(4, 21);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(72, 23);
            this.label1.TabIndex = 6;
            this.label1.Text = "Name:";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // chkAppend
            // 
            this.chkAppend.Location = new System.Drawing.Point(376, 256);
            this.chkAppend.Name = "chkAppend";
            this.chkAppend.Size = new System.Drawing.Size(72, 24);
            this.chkAppend.TabIndex = 35;
            this.chkAppend.Text = "Append?";
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.txtFreqShape);
            this.groupBox2.Controls.Add(this.btnEditFreqShape);
            this.groupBox2.Controls.Add(this.btnBrowseFreqShape);
            this.groupBox2.Controls.Add(this.label8);
            this.groupBox2.Location = new System.Drawing.Point(8, 288);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(544, 64);
            this.groupBox2.TabIndex = 36;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Frequency Shaping (Experiment only)";
            // 
            // txtFreqShape
            // 
            this.txtFreqShape.Location = new System.Drawing.Point(144, 24);
            this.txtFreqShape.Name = "txtFreqShape";
            this.txtFreqShape.Size = new System.Drawing.Size(272, 20);
            this.txtFreqShape.TabIndex = 24;
            // 
            // btnEditFreqShape
            // 
            this.btnEditFreqShape.Image = ((System.Drawing.Image)(resources.GetObject("btnEditFreqShape.Image")));
            this.btnEditFreqShape.Location = new System.Drawing.Point(424, 24);
            this.btnEditFreqShape.Name = "btnEditFreqShape";
            this.btnEditFreqShape.Size = new System.Drawing.Size(32, 23);
            this.btnEditFreqShape.TabIndex = 27;
            this.btnEditFreqShape.Click += new System.EventHandler(this.btnEditFreqShape_Click);
            // 
            // btnBrowseFreqShape
            // 
            this.btnBrowseFreqShape.Image = ((System.Drawing.Image)(resources.GetObject("btnBrowseFreqShape.Image")));
            this.btnBrowseFreqShape.Location = new System.Drawing.Point(472, 24);
            this.btnBrowseFreqShape.Name = "btnBrowseFreqShape";
            this.btnBrowseFreqShape.Size = new System.Drawing.Size(32, 23);
            this.btnBrowseFreqShape.TabIndex = 26;
            this.btnBrowseFreqShape.Click += new System.EventHandler(this.btnBrowseFreqShape_Click);
            // 
            // label8
            // 
            this.label8.Location = new System.Drawing.Point(8, 24);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(128, 23);
            this.label8.TabIndex = 25;
            this.label8.Text = "Frequency Shaping File:";
            this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(560, 377);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.chkAppend);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.lbl);
            this.Controls.Add(this.lblVer);
            this.Controls.Add(this.statusBar1);
            this.Controls.Add(this.txtResultFile);
            this.Controls.Add(this.txtInitFile);
            this.Controls.Add(this.toolBar1);
            this.Controls.Add(this.btnBrowseResult);
            this.Controls.Add(this.btnEditDef);
            this.Controls.Add(this.btnBrowseInit);
            this.Controls.Add(this.label7);
            this.Controls.Add(this.label6);
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Menu = this.mainMenu1;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Behavioral Auditory Research Tests (B.A.R.T.)";
            ((System.ComponentModel.ISupportInitialize)(this.sbCalibration)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.sbCalibrationR)).EndInit();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		private void ReadRegistry()
		{
			try
			{
				Microsoft.Win32.RegistryKey upper = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("HAL");
				if(upper != null)
				{
					Microsoft.Win32.RegistryKey key = upper.OpenSubKey("Calibration");
					if(key != null)
					{
						CalDb = float.Parse((string) key.GetValue("CalDb"));
						this.SetLeftCalibration("Calibration (L):  Simple:  " + CalDb.ToString());
						this.SetRightCalibration("Calibration (R):  Simple:  " + CalDb.ToString());
					}
					key = upper.OpenSubKey("Manual");
					if(key != null)
					{
						Manual = (string) key.GetValue("Manual");
					}
				}
			}
			catch(Exception)
			{
				return;
			}
		}

		private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
		{
			

			timerLabel.Stop();
			EventArgs ev = new EventArgs();
			switch(toolBar1.Buttons.IndexOf(e.Button))
			{
				case 0:
					CalSimple_Click(sender,ev);
					break;
				case 1:
					CalChirp_Click(sender,ev);
					break;
				case 3:
					RunAudiogram_Click(sender, ev);
					break;
				case 4:
					RunSTAR_Click(sender,ev);
					break;
				case 5:
					RunCategoricalLoudness_Click(sender,ev);
					break;
				case 6:
					RunPairedComparison_Click(sender,ev);
					break;
				case 8:
					ResetCal();
					break;
			}
		}
		private void ResetCal()
		{
			if(cal!=null)
                cal.Cal.Clear();
			cal = null;
			if(LeftCal!=null)
				LeftCal.Cal.Clear();
			LeftCal = null;
			if(RightCal!=null)
				RightCal.Cal.Clear();
			RightCal = null;
			ReadRegistry();

		}
		private void CalSimple_Click(object sender, System.EventArgs e)
		{
			timerLabel.Stop();
			GC.Collect();
			GC.WaitForPendingFinalizers();
			GC.Collect();
			GC.WaitForPendingFinalizers();
			try
			{
				Calibrate dlg = new Calibrate();
				dlg.mainmenu = this;
				dlg.CalDb = CalDb;
				dlg.SetDb();
				dlg.ShowDialog();
				CalDb = dlg.CalDb;
				try
				{
					Microsoft.Win32.RegistryKey upper = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("HAL");
					Microsoft.Win32.RegistryKey key = upper.CreateSubKey("Calibration");
					key.SetValue("CalDb",CalDb.ToString());
					SetLeftCalibration("Calibration (L):  Simple: " + CalDb.ToString());
					SetRightCalibration("Calibration (R):  Simple: " + CalDb.ToString());
				}
				catch(Exception)
				{
					return;
				}
				GC.Collect();
			}
			catch(Exception err)
			{
				MessageBox.Show("Calibration Start Error: "+err.Message);
			}
			
		}

		private void CalChirp_Click(object sender, System.EventArgs e)
		{
			timerLabel.Stop();
			GC.Collect();
			GC.WaitForPendingFinalizers();
			GC.Collect();
			GC.WaitForPendingFinalizers();
			try
			{
				cal = new ChirpCal();
				Chirp dlg = new Chirp();
				dlg.mainmenu = this;
				dlg.cal = cal;
				this.Hide();
				dlg.Show();
				dlg.Init();
				dlg.Draw();
			}
			catch(Exception)
			{
				return;
			}
		}
		private void RunAudiogram_Click(object sender, System.EventArgs e)
		{
			if(this.txtInitFile.Text.Length<=0)
			{
				ErrorMsg("Invalid .def file!");
				return;
			}
			FileInfo fResult = new FileInfo(txtResultFile.Text);
			if(fResult.Exists)
				if(MessageBox.Show("File "+fResult.FullName + " already exists. Overwrite ?","Confirm Overwrite",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)== DialogResult.No)
					return;

			def = new Definitions();
			timerLabel.Stop();
			InitFile = new FileInfo(txtInitFile.Text);
			//DialogResult r = MessageBox.Show("Are you sure you want to start AUDIOGRAM?","???",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
			//if(r==DialogResult.No)
			//	return;
			try
			{
				//this actually starts the audiogram, which was initially star
				if(ValidateStar()==false)
					return;
				Progress progress = new Progress();
				progress.Init("Starting Audiogram",100,0,1);
				progress.Show();
				StarAudio s = new StarAudio(def.bSingleScreen);
				progress.Increment();
				this.Hide();
				progress.SetLabel("Reading Init File");
				progress.Increment();
				if(ReadInitFile(progress)==false)
				{
					MessageBox.Show("Error reading Definitions File!","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
					this.ShowDialog();
					progress.Close();
					return;
				}
				//remove any pauses
				for(int x=0;x<this.def.PrimaryStims.Count;x++)
				{
					Stim stim = (Stim) def.PrimaryStims[x];
					if(stim.strType=="PAUSE")
					{
						def.PrimaryStims.RemoveAt(x);
						x--;
					}
				}
				progress.SetLabel("Starting Audiogram");
				progress.Increment();
				
				s.outfile = new FileInfo(txtResultFile.Text);
				s.strInitFile = this.txtInitFile.Text;
				progress.Increment();
				s.mainmenu = this;
				progress.Increment();
				progress.Close();
				s.Init();
			}
			catch(Exception err)
			{
				MessageBox.Show("Error: " + err.Message);
				this.Show();
			}
			
		}

		private void RunSTAR_Click(object sender, System.EventArgs e)
		{
			if(this.txtInitFile.Text.Length<=0)
			{
				ErrorMsg("Invalid .def file!");
				return;
			}
			FileInfo fResult = new FileInfo(txtResultFile.Text);
			if(fResult.Exists)
				if(MessageBox.Show("File "+fResult.FullName + " already exists. Overwrite ?","Confirm Overwrite",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)== DialogResult.No)
					return;

			def = new Definitions();
			timerLabel.Stop();
			//InitFile = new FileInfo(txtInitFile.Text);
			//DialogResult r = MessageBox.Show("Are you sure you want to start STAR?","???",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
			//if(r==DialogResult.No)
			//	return;
			try
			{
				/*if(this.chkAppend.Checked==true)
				{
					MessageBox.Show("Please do not try to append to a Star result file!","Append",MessageBoxButtons.OK,MessageBoxIcon.Hand);
					return;
				}*/
				if(ValidateStar()==false)
					return;
				Progress progress = new Progress();
				progress.Init("Starting Star",100,0,1);
				progress.Show();
				Star s = new Star(def.bSingleScreen);
				progress.Increment();
				this.Hide();
            
				progress.SetLabel("Reading Init File");
				progress.Increment();
				if(ReadInitFile(progress)==false)
				{
					MessageBox.Show("Error reading Definitions File!","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
					this.ShowDialog();
					progress.Close();
					return;
				}
				try
				{
					output = new StreamWriter(txtResultFile.Text,this.chkAppend.Checked);
					if(output==null)
					{
						Exception err = new Exception("Unable to create output File.");
					}
					output.Close();
				}
				catch(Exception)
				{
					MessageBox.Show("Unable to create result file.","File Error");
					return;
				}
				if(ReadFreqShapeFile()==false)
				{
					MessageBox.Show("Unable to read/parse Frequency Shaping File.","File Error");
					return;
				}
				progress.SetLabel("Starting Star");
				progress.Increment();
				s.outfile = new FileInfo(txtResultFile.Text);
				progress.Increment();
				s.mainmenu = this;
				progress.Increment();
				progress.Close();
				s.Init();
			}
			catch(Exception err)
			{
				MessageBox.Show("Error: " + err.Message);
				this.Show();
			}
		}
		private void RunCategoricalLoudness_Click(object sender, System.EventArgs e)
		{
			if(this.txtInitFile.Text.Length<=0)
			{
				ErrorMsg("Invalid .def file!");
				return;
			}
			FileInfo fResult = new FileInfo(txtResultFile.Text);
			if(fResult.Exists)
				if(MessageBox.Show("File "+fResult.FullName + " already exists. Overwrite ?","Confirm Overwrite",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)== DialogResult.No)
					return;

			timerLabel.Stop();
			InitFile = new FileInfo(txtInitFile.Text);
			//DialogResult r = MessageBox.Show("Are you sure you want to start Categorical Loudness?","???",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
			//if(r==DialogResult.No)
			//	return;
			try
			{
				def = new Definitions();
				if(ValidateStar()==false)
					return;
				Progress progress = new Progress();
				progress.Init("Starting Categorical Loudness",100,0,1);
				progress.Show();
				CategoricalLoudness cl = new CategoricalLoudness();
				//CatLoud2 cl = new CatLoud2();
				progress.Increment();
				this.Hide();
				progress.SetLabel("Reading Init File");
				progress.Increment();
				if(ReadInitFile(progress)==false)
				{
					MessageBox.Show("Error reading Definitions File!","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
					this.ShowDialog();
					progress.Close();
					return;
				}
				try
				{
					output = new StreamWriter(txtResultFile.Text,false);
					if(output==null)
					{
						Exception err = new Exception("Unable to create output File.");
					}
					output.Close();
				}
				catch(Exception)
				{
					MessageBox.Show("Unable to create result file.","File Error");
					return;
				}
				if(ReadFreqShapeFile()==false)
				{
					MessageBox.Show("Unable to read/parse Frequency Shaping File.","File Error");
					return;
				}
				progress.SetLabel("Starting Categorical Loudness");
				progress.Increment();
				cl.outfile = new FileInfo(txtResultFile.Text);
				progress.Increment();
				cl.mainmenu = this;
				cl.def = this.def;
				progress.Increment();
				cl.Init();
				progress.Close();
				//cl.Show();
			}
			catch(Exception err)
			{
				MessageBox.Show("Error: " + err.Message);
				this.Show();
			}
		
		}
		private bool ReadFreqShapeFile()
		{
			//txtFreqShape.Text = @"C:\Visual Studio Projects\HearingAidLab_ARSC\FreqShape.txt";;
			if(txtFreqShape.Text.Length<=0)//no file
				return true;
			string strLine = string.Empty;
			try
			{
				def.bFrequencyShaping = true;
				StreamReader sr = new StreamReader(txtFreqShape.Text);
				strLine = sr.ReadLine();
				char[] szSep = {' ',',',':','%','[',']','\t','='};
				string[] str;
				while(strLine!=null)
				{
					strLine = strLine.Trim();
					if(strLine[0]!='%')//if it is not a comment
					{
						int n = strLine.IndexOf("%",0);
						if(n>0)
							strLine = strLine.Substring(0,n-1);
						str = strLine.Split(szSep,50);
						switch(str[0].ToLower())
						{
							case "lattenfreqs":
								def.LFreqs = SetArray(str);
								break;
							case "lattendb":
								def.LAtten = SetArray(str);
								break;
							case "rattenfreqs":
								def.RFreqs = SetArray(str);
								break;
							case "rattendb":
								def.RAtten = SetArray(str);
								break;
						}
					}
					strLine = sr.ReadLine();
				}
			}
			catch(Exception err)
			{
				ErrorMsg("Error reading Freq Shape File {0} {1}",
					err.Message, strLine);
				return false;
			}
			return true;
		}
		public bool ReadFreqShapeFile(string file)
		{
			string strLine = string.Empty;
			try
			{
				def.bFrequencyShaping = true;
				StreamReader sr = new StreamReader(file);
				strLine = sr.ReadLine();
				char[] szSep = {' ',',',':','%','[',']','\t'};
				string[] str;
				while(strLine!=null)
				{
					strLine = strLine.Trim();
					if(strLine[0]!='%')//if it is not a comment
					{
						int n = strLine.IndexOf("%",0);
						if(n>0)
							strLine = strLine.Substring(0,n-1);
						str = strLine.Split(szSep,50);
						switch(str[0].ToLower())
						{
							case "lattenfreqs":
								def.LFreqs = SetArray(str);
								break;
							case "lattendb":
								def.LAtten = SetArray(str);
								break;
							case "rattenfreqs":
								def.RFreqs = SetArray(str);
								break;
							case "rattendb":
								def.RAtten = SetArray(str);
								break;
						}
					}
					strLine = sr.ReadLine();
				}
			}
			catch(Exception err)
			{
				ErrorMsg("Error Reading Freq Shape File: {0} {1}",
					strLine, err.Message);
				return false;
			}
			return true;
		}
		private float[] SetArray(string[] str)
		{
			float[] f = new float[str.Length];
			int fCount=0;
			for(int x=0;x<str.Length;x++)
			{
				try
				{
					float flt = float.Parse(str[x]);
					f[fCount++] = flt;
				}
				catch(Exception){}
			}
			float[] goodf = new float[fCount];
			for(int i=0;i<fCount;i++)
			{
				goodf[i] = f[i];
			}
			return goodf;
		}

		private int SetInt(string[] str)
		{
			for(int x=0;x<str.Length;x++)
			{
				try
				{
					int i = int.Parse(str[x]);
					return i;
				}
				catch(Exception){}
			}
			return 0;
		}
		private void OptSingleScreen_Click(object sender, System.EventArgs e)
		{
			this.OptSingleScreen.Checked = !OptSingleScreen.Checked;
		}

		private void OptTestGame_Click(object sender, System.EventArgs e)
		{
			if(txtInitFile.Text.Length<=0)
			{
				ErrorMsg("Please select the .def file you want to test!");
				return;
			}
			InitFile = new FileInfo(txtInitFile.Text);
			if(InitFile.Exists==false)
			{
				ErrorMsg("Could not find file {0} or it does not exist!",txtInitFile.Text);
				return;
			}
			TestGame dlg = new TestGame();
			if(ReadInitFile(null)==false)
			{
				MessageBox.Show("Error reading Definitions File!","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
				return;
			}
			dlg.mainmenu = this;
			dlg.Init();
			this.Hide();
			dlg.Show();
		}
		private void btnBrowseInit_Click(object sender, System.EventArgs e)
		{
			OpenFileDialog dlg = new OpenFileDialog();
			dlg.Filter = "Init file (*.def)|*.def";
			dlg.Filter += "|All files|*.*";
			dlg.Multiselect = false;
			if(dlg.ShowDialog()==DialogResult.OK)
			{
				txtInitFile.Text = dlg.FileName;
				InitFile = new FileInfo(txtInitFile.Text);

			}
		
		}

		private void btnBrowseResult_Click(object sender, System.EventArgs e)
		{
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.Filter = "Text file (*.txt)|*.txt";
			dlg.Filter += "|All files|*.*";
			
			if(dlg.ShowDialog()==DialogResult.OK)
			{
				txtResultFile.Text = dlg.FileName;
			}
		
		}

		private void btnEditDef_Click(object sender, System.EventArgs e)
		{
//#if DEBUG
			DefEditor d = new DefEditor();
			this.Hide();
			d.main = this;
			Progress progress = new Progress();
			progress.Init("Loading .def file",100,0,1);
			progress.Show();
			if(txtInitFile.Text.Length>0)
			{
				d.SaveFile = new FileInfo(this.txtInitFile.Text);
				InitFile = new FileInfo(txtInitFile.Text);
				if(InitFile.Exists==true)
					this.ReadInitFile(progress);
				else
				{
					MessageBox.Show("Unable to find file " + InitFile.Name);
					this.Show();
					return;
				}
				progress.Increment();
			}
			else
				this.def = new Definitions();
			
            d.FillFields();
			d.ShowDialog();
/*#else
			System.Diagnostics.Process p = new System.Diagnostics.Process();
			System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo("notepad.exe",this.txtInitFile.Text);
			p.StartInfo = si;
			p.Start();
#endif*/
			progress.Close();
			progress.Dispose();
				
		}

		private void btnEditFreqShape_Click(object sender, System.EventArgs e)
		{
			System.Diagnostics.Process p = new System.Diagnostics.Process();
			System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo("notepad.exe",this.txtFreqShape.Text);
			p.StartInfo = si;
			p.Start();
		}

		private void btnBrowseFreqShape_Click(object sender, System.EventArgs e)
		{
			OpenFileDialog dlg = new OpenFileDialog();
			dlg.Filter = "Frequency Shaping file (*.txt)|*.txt";
			dlg.Filter += "|All files|*.*";
			dlg.Multiselect = false;
			if(dlg.ShowDialog()==DialogResult.OK)
			{
				this.txtFreqShape.Text = dlg.FileName;
			}
		}
		public void SetLeftCalibration(string s)
		{
			this.statusBar1.Panels[0].Text = s;
			if(this.cal!=null)
			{
				if(cal.strFile.Length<=0)
					sbCalibration.Text = "Calibration (L): Chirp";
				else
					sbCalibration.Text = "Calibration (L): "+cal.strFile;
			}
			if(this.LeftCal!=null)
			{
				if(LeftCal.strFile.Length<=0)
					sbCalibration.Text = "Calibration (L): Chirp";
				else
					sbCalibration.Text = "Calibration (L): "+LeftCal.strFile;
			}
			
		}
		public void SetRightCalibration(string s)
		{
			sbCalibrationR.Text = s;
			if(this.cal!=null)
			{
				if(cal.strFile.Length<=0)
					sbCalibrationR.Text = "Calibration (R): Chirp";
				else
					sbCalibrationR.Text = "Calibration (R): "+cal.strFile;
			}
			if(this.RightCal!=null)
			{
				if(RightCal.strFile.Length<=0)
					sbCalibrationR.Text = "Calibration (R): Chirp";
				else
					sbCalibrationR.Text = "Calibration (R): "+RightCal.strFile;
			}
		}
		
		public string GetCal()
		{
			string str = sbCalibration.Text + "  " + sbCalibrationR.Text;
			return str;
		}
		public string GetLCal()
		{
			return sbCalibration.Text;
		}
		public string GetRCal()
		{
			return sbCalibrationR.Text;
		}
		private void Form1_Closing(object sender, CancelEventArgs e)
		{
			
		}

		

		private bool ValidateStar()
		{
			def.bSingleScreen = this.OptSingleScreen.Checked;
			string strError = string.Empty;
			if(this.txtInitFile.Text.Length<=0)
				strError = "Please select a Definitions file!";
			else if(this.txtResultFile.Text.Length<=0)
				strError = "Please select a results file!";
			else if(this.txtName.Text.Length<=0)
				strError = "Please enter a subject name!";
			else
			{
				try
				{
					FileInfo f = new FileInfo(txtInitFile.Text.ToString());
					if(f.Exists == false)
						strError = "Unable to find Definitions File!";
				}
				catch(Exception)
				{
					strError = "Unable to open Definitions File!";
				}
			}
			if(strError.Length>0)
			{
				MessageBox.Show(strError,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
				return false;
			}
			FileInfo fi = new FileInfo(this.txtResultFile.Text);
			if(fi.Exists==true)
				fi.CopyTo(fi.FullName+".old",true);
			return true;
		}

		private bool ValidateGames()
		{
			foreach(string game in def.Feedback)
			{
				string strTxt = string.Empty;
				if(game.IndexOf(".txt")<=0)
					strTxt = def.strFeedbackDir + game + ".txt";
				else
					strTxt = def.strFeedbackDir + game;
				FileInfo f = new FileInfo(strTxt);
				if(f.Exists==false)
				{
					MessageBox.Show("Feedback file " + strTxt + " does not exist!","Feedback Error",MessageBoxButtons.OK,MessageBoxIcon.Stop);
					return false;
				}
				StreamReader read = new StreamReader(f.FullName);
				string strType = GameParse(read.ReadLine());
				if(strType=="DOT_TO_DOT")
				{
					f = new FileInfo(def.strGameDir + GameParse(read.ReadLine()));
					if(f.Exists==false)
					{
						MessageBox.Show("Error in game" + strTxt + " picture file " + f.FullName +" does not exsist.","Feedback Error",
							MessageBoxButtons.OK,MessageBoxIcon.Stop);
						read.Close();
						return false;
					}
					f = new FileInfo(def.strGameDir + GameParse(read.ReadLine()));
					if(f.Exists==false)
					{
						MessageBox.Show("Error in game" + strTxt + " picture file " + f.FullName +" does not exsist.","Feedback Error",
							MessageBoxButtons.OK,MessageBoxIcon.Stop);
						read.Close();
						return false;
					}
				}
				else if(strType=="ZAP" || strType=="REVEAL")
				{
					f = new FileInfo(def.strGameDir + GameParse(read.ReadLine()));
					if(f.Exists==false)
					{
						MessageBox.Show("Error in game" + strTxt + " picture file " + f.FullName +" does not exsist.","Feedback Error",
							MessageBoxButtons.OK,MessageBoxIcon.Stop);
						read.Close();
						return false;
					}
				}
				else if(strType=="SLIDESHOW")
				{
					string strLine = GameParse(read.ReadLine());
					while(strLine!=null&&strLine!=string.Empty)
					{
						f = new FileInfo(def.strGameDir + strLine);
						if(f.Exists==false)
						{
							MessageBox.Show("Error in game" + strTxt + " picture file " + f.FullName +" does not exsist.","Feedback Error",
								MessageBoxButtons.OK,MessageBoxIcon.Stop);
							read.Close();
							return false;
						}
						strLine = GameParse(read.ReadLine());
					}
				}
				else
				{
					MessageBox.Show("Unrecognized game type: " + strType + " in game " + strTxt + ".","Feedback Error",
						MessageBoxButtons.OK,MessageBoxIcon.Stop);
					read.Close();
					return false;
				}
				read.Close();
			}
		
			return true;
		}

		
		public bool ReadInitFile(Progress progress)
		{
			GC.Collect();
			GC.WaitForPendingFinalizers();
			GC.Collect();
			GC.WaitForPendingFinalizers();

			System.Text.RegularExpressions.Regex reg;
			reg = new System.Text.RegularExpressions.Regex(@"[A-Za-z]");
			System.Text.RegularExpressions.Match mat;
			InitFile = new FileInfo(txtInitFile.Text);
			string strLine = string.Empty;
			try
			{
				if(InitFile.Exists==false)
				{
					ErrorMsg("Definition File: {0} does not exist!",txtInitFile.Text);
					return false;
				}
				StreamReader input = null;
				try{input = new StreamReader(InitFile.FullName);}
				catch(Exception)
				{
					ErrorMsg("Unable to open {0}!",InitFile.FullName);
					return false;
				}
				if(def == null)
					def = new Definitions();
				else
					def.Clear();
				def.Buttons.Clear();
				def.listRes.Clear();
				def.Feedback.Clear();
				def.Methods.Clear();
				def.PrimaryStims.Clear();
				def.SecondaryStims.Clear();
				def.PairedStims.Clear();
				def.strInitFile = InitFile.FullName;
				strLine = input.ReadLine();
				string strVar,strValue;
				int nValue;
				int n;
				while(strLine != null)
				{
					strLine = strLine.Trim(); //remove whitespace
					if(progress!=null)
					{
						progress.Increment();
						progress.lblProgress.Text = strLine;
					}
					if(strLine.Length>0)
					{
						if(strLine[0]=='%')
						{
							strLine = input.ReadLine();
							continue;
						}
						n = strLine.IndexOf(':');
						if(n>0)
						{
							strVar = strLine.Substring(0,n);
							if(strVar.Trim().ToUpper() == "BUTTON")
								ParseButton(strLine);
							else if(strLine.Trim().ToUpper().IndexOf("STIMULI.PRIMARY:COMPLEX")>=0)
								ParseComplexPrimary(input,strLine);
							else if(strLine.Trim().ToUpper().IndexOf("STIMULI.SECONDARY:COMPLEX")>=0)
								ParseComplexSecondary(input,strLine);
							else
							{
								//Standard error is only double/float value
								if(strVar.ToLower()=="standarderror"||strVar.ToLower()=="stop.standarderror")
								{
									try{def.dwStdErrVal = double.Parse(strLine.Substring(n+1));}
									catch(Exception)
									{
										ErrorMsg("Error on parse of {0} value {1}",strVar, strLine);
										return false;
									}
								}
								else
								{
									try
									{
										mat = reg.Match(strLine.Substring(n+1));
										if(mat.Length<=0)
										{
											nValue = int.Parse(strLine.Substring(n+1));
											SetInitialValue(strVar.ToLower(),nValue);
										}
										else
										{
											//same as catch block below, but 
											//runs faster by not triggering the exception
											strValue = strLine.Substring(n+1);
											SetInitialValue(strVar.ToLower(),strValue.Trim().ToLower());
										}
									}
									catch(Exception)
									{
										strValue = strLine.Substring(n+1);
										SetInitialValue(strVar.ToLower(),strValue.Trim().ToLower());
									}
								}
							}
						}
					}
					strLine = input.ReadLine();
				}
				//set default buttons
				if(def.Buttons.Count<=0&&def.bCL==false)
				{
					Button b = new Button();
					b.Text = "Yes";
					ButtonTag bt = new ButtonTag();
					bt.strCat = "0"; // Category 0 = yes
					b.Tag = bt;
					def.Buttons.Add(b);
					b = new Button();
					bt = new ButtonTag();
					bt.strCat = "1"; // category 1 = no
					b.Tag = bt;
					b.Text = "No";
					def.Buttons.Add(b);
				}
				bool bb = ValidateGames();
				input.Close();
				if(progress!=null)
				{
					progress.SetLevel(95);
				}
				return bb;
			}
			catch(Exception err)
			{
				ErrorMsg("Error reading definition file:  {0} on line {1}",
					err.Message,strLine);
				return false;
			}

			//Check Result file
			if(this.txtResultFile.Text.Length<=0)
			{
				ErrorMsg("Invalid Result File!");
				return false;
			}
		}
		public void SetInitialValue(string Variable, int Value)
		{
			switch(Variable.Trim())
			{
				case "cl":
					if(Value==1)
					{
						def.bCL = true;
						def.Buttons.Clear();
					}
					break;
				case "clbuttons":
					def.nCLButtons = Value;
					break;
				case "clanchor":
				case "clanchored":
					if(Value==1)
						def.bAnchoredTrials = true;
					break;
				case "stop.mode":
					def.nStopMode = Value;
					break;
				case "stop.secondaryreversals":
					def.nStopReversals = Value;
					break;
				case "stop.primaryreversals":
					def.nChangeReversals = Value;
					break;
				case "stimuli.secondarycontinuous":
					if(Value==1)
						def.bSecondaryContinuous = true;
					else
						def.bSecondaryContinuous = false;
					break;
				case "waitfornextbutton":
					if(Value==1)
						def.bWaitForNextButton = true;
					else
						def.bWaitForNextButton = false;
					break;
				case "maxlevel":
					def.nMaxLevel = Value;
					break;
				case "interval.cue":
					if(Value==1)
						def.bCue = true;
					else
						def.bCue = false;
					break;
				case "intervalbuttons":
				case "interval.buttons":
					if(Value==1)
						def.bInterval = true;
					break;
				case "intervalon":
				case "interval.timeon":
					def.nIntervalLen = Value;
					break;
				case "intervalspace":
				case "interval.interval":
					def.nIntervalSpace = Value;
					break;
				case "numberoftrials":
					def.nNumberOfTrials = Value;
					break;
				case "method":
					def.Methods.Add(Value);
					break;
				case "random":
				case "order.primary":
					if(Value==1)
						def.bRandom = true;
					else 
						def.bRandom = false;
					break;
				case "primarystepsize":
				case "stepsize.primary":
					def.nPrimaryStep = Value;
					break;
				case "secondarystepsize":
				case "stepsize.secondary":
					def.nSecondaryStep = Value;
					break;
				case "catchtrial":
				case "catchtrial.enabled":
					if(Value==1)
						def.bCatchTrial = true;
					else 
						def.bCatchTrial = false;
					break;
				case "catchtrial.backtoback":
					if(Value==1)
						def.bBackToBackCatch = true;
					else
						def.bBackToBackCatch = false;
					break;
				case "catchlength":
				case "catchtrial.length":
					def.nCatchLength = Value;
					break;
				case "catchfrequency":
				case "catchtrial.frequency":
					def.nCatchFreq = Value;
					break;
				case "repetitions":
					def.nReps = Value;
					break;
				case "timer":
					def.nTimer = Value;
					if(Value==0)
						def.nTimer = 600000;//10 minutes
					break;
				case "delay":
				case "isi":
				case "isi.length":
					def.nDelay = Value;
					break;
				case "jitter":
				case "isi.jitter":
					def.nJitter = Value;
					break;
				case "stepsize":
				case "range.stepsize":
					def.nStepSize = Value;
					break;
				case "range":
				case "range.width":
					def.nRange = Value;
					break;
				case "gamedelay":
					def.nGameDelay = Value;
					break;
				case "gamedelaytype":
					def.nGameDelayType = Value;
					break;
				case "freqshapesecondary":
					def.nFreqShapeSecondary = Value;
					break;
				case "specialnextbutton":
					def.nSpecialPatNextButton = Value;
					break;
				case "changefeedback":
					def.nChangeFeedback = (Value>0)? Value:1;//avoid division by zero
					break;
				case "feedbackx":
					def.FeedbackLoc.X = Value;
					break;
				case "feedbacky":
					def.FeedbackLoc.Y=Value;
					break;
				case "feedbackwid":;
					def.FeedbackSize.X = Value;
					break;
				case "feedbackhgt":
					def.FeedbackSize.Y = Value;
					break;
				case "playlrstereo":
					def.bPlayLRStereo = (Value > 0)?true:false;
					break;
				case "clbuttonslayout":
					def.CLButtonsLayout=Value;
					break;
				case "cluseadaptive":
					if(Value == 1) def.CLUseAdaptive = true;
					else def.CLUseAdaptive= false;
                    break;
				default:
					string str = string.Format("Unable to find Parameter {0}!",Variable);
                    MessageBox.Show(str,"Init Error",MessageBoxButtons.OK,MessageBoxIcon.Warning);
					break;
			}
		}

		public void SetInitialValue(string Variable, string Value)
		{
			switch(Variable.Trim())
			{	case "mixsecondary":
				case "mix.secondary":
					string str = Value.Trim().ToLower();
					if (str=="mix")	def.bMixSecondary = true;
					else if (str == "do not mix") def.bMixSecondary = false;
					break;
				case "secondaryorder":
				case "order.secondary":
					def.strSecondaryOrder = Value;
					break;
				case "results":
					ParseResults(Value);
					break;
				case "feedbackfile":
				case "feedback.file":
					def.Feedback.Add(Value);
					break;
				case "feedbackdirectory":
				case "feedback.directory":
					def.strFeedbackDir = Value;
					break;
				case "primarystimuli":
				case "stimuli.primary":
					ParsePrimaryStimLine(Value);
					break;
				case "secondarystimuli":
				case "stimuli.secondary":
					ParseSecondaryStimLine(Value);
					break;
				case "pairedstimuli":
				case "stimuli.paired":
					ParsePairedStimLine(Value);
					break;
				case "masker":
				case "stimuli.masker":
					ParseMasker(Value);
					break;
				case "adapt":
					str = Value.Trim().ToLower();
					if(str=="primary")
						def.nAdaptType = 1;
					else if(str=="secondary")
						def.nAdaptType = 2;
					else if(str=="across primary")
						def.nAdaptType = 3;
					else
						def.nAdaptType = 0;
					break;
				case "primaryadapt":
					if(Value.Trim().ToLower()=="level")
					{
						def.nAdaptType = 1;
						def.PrimaryAdapt = AdaptiveTypes.Level;
					}
					else if(Value.IndexOf(";")>0)
					{
						ParsePrimaryFilterLine(Value);
					}
					break;
				case "dirofchange":
					if(Value.Trim()=="+")
						def.bBandwidth=true;
					break;
				case "stimulidirectory":
				case "stimuli.directory":
					def.strStimDirectory = Value;
					if(def.strStimDirectory.LastIndexOf(@"\")!=def.strStimDirectory.Length-1)
						def.strStimDirectory+=@"\";
					break;
				case "playlrstereo":
					def.bPlayLRStereo = bool.Parse(Value);
					break;
				default:
					str = string.Format("Unable to find Parameter {0}!",Variable);
					MessageBox.Show(str,"Init Error",MessageBoxButtons.OK,MessageBoxIcon.Warning);
					break;
			}
		}
		
		public void ParseButton(string strLine)
		{
			//Full line should be :
			//button: XSize : YSize : XLoc: YLoc: ; fontsize ; category ; Text ; file
			string[] arrIn;
			string[] arr = new string[9];

			char[] szSeps = {':',';',','};
			arrIn = strLine.Split(szSeps,9);
			int k=0;
			for(int j=0;j<9;j++)
			{
				if(j>=arrIn.Length)
					break;
				//if(arrIn[j].Trim().Length>0)
					arr[k++] = arrIn[j].Trim();
			}
			Button b = new Button();
			try
			{
				b.Size = new Size(int.Parse(arr[1]),int.Parse(arr[2]));
				b.Location = new Point(int.Parse(arr[3]),int.Parse(arr[4]));
				Font f = new Font("Arial",float.Parse(arr[5]));
				b.Font = f;
				ButtonTag bt = new ButtonTag();
				bt.strCat = arr[6];
				b.Text = arr[7];
				//There may be a picture file associated.  If so, it's enclosed in quotes;
				if(arr[8]!="\"\"")
				{
					k = strLine.IndexOf("\"");
					if(k>0)
					{
						int l = strLine.LastIndexOf("\"");
						string strImage = strLine.Substring(k+1,l-k-1);
						Bitmap bm = new Bitmap(strImage);
						b.Image = bm;
						bt.strPic = strImage;
					}
				}
				b.Tag = bt;
				def.Buttons.Add(b);
			}
			catch(Exception err)
			{
				ErrorMsg("Error Parsing Button Definition {0} {1}",
					strLine, err.Message);
				return;
			}
		}
		public void ParsePrimaryStimLine(string strLine)
		{
			Stim s = new Stim();
			if(strLine=="pause")
			{
				
				s.strText = strLine;
				s.strType = "PAUSE";
				s.strDesiredResponse = "PAUSE";
				def.PrimaryStims.Add(s);
				return;
			}
			//%PrimaryStimuli: type;file;category;initial cutoff/(center frequency);intial level;ear(s);amplification type
			//%PrimaryStimuli: type ; freq ; length ms ; rise ms ; fall ms ; ear
			//%PrimaryStimuli: type ; freq  ; length ; interval ; rise ; fall ; left
			try
			{
				string[] arrIn;
				char[] szSeps = {';'};
				arrIn = strLine.Split(szSeps, StringSplitOptions.None);
		
				//s = new Stim();
				s.strText = strLine;
				s.strType = arrIn[0].ToLower().Trim();
				s.strDesiredResponse = "1";
		
				if(s.strType == "wave")
				{
					//wav
					FileInfo f = new FileInfo(arrIn[1].Trim());
                    s.strFile =f.Name;// arrIn[1].Trim();
					s.strStimDirectory= f.DirectoryName;
					s.strDesiredResponse = arrIn[2].Trim();
					s.strInfo = arrIn[3].Trim();
					s.nOrigin = int.Parse(arrIn[4]);
					s.strEar = arrIn[5].ToLower().Trim();
					if(arrIn[6].ToLower().Trim()=="rms")
						s.AmpType = AmplificationTypes.RMS;
					else if(arrIn[6].ToLower().Trim()=="none")
						s.AmpType = AmplificationTypes.None;
					s.nFreq = 0;
				}
				else if(s.strType == "tone")
				{
					//tone
					////%PrimaryStimuli: type ; freq ; length ms ; rise ms ; fall ms ; ear; initial level ; phase
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nLength = int.Parse(arrIn[2].Trim());
					s.nRise = int.Parse(arrIn[3].Trim());
					s.nFall = int.Parse(arrIn[4].Trim());
					s.strEar = arrIn[5].ToLower().Trim();
                    if (arrIn[8].ToLower().Trim() == "rms")
                        s.AmpType = AmplificationTypes.RMS;
                    else if (arrIn[8].ToLower().Trim() == "peak")
                        s.AmpType = AmplificationTypes.Peak;
                    else s.AmpType = AmplificationTypes.None;
                    s.attenuation = Convert.ToInt32(arrIn[9].Trim());
                    
					if(arrIn.Length>6)
						s.nOrigin = int.Parse(arrIn[6]);
					else
						s.nOrigin = 40;
					if(arrIn.Length>7)
						s.nInitialPhase = int.Parse(arrIn[7]);
					else
						s.nInitialPhase = 0;
					if(arrIn.Length>8)
						s.strInfo = arrIn[8];
					s.strDesiredResponse = "1";
					
				}
				else if(s.strType == "pulse")
				{
					//%PrimaryStimuli: type ; freq  ; length ; interval ; rise ; fall ; ear ; initial level ; phase
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nLength = int.Parse(arrIn[2].Trim());
					s.nInterval = int.Parse(arrIn[3].Trim());
					s.nRise = int.Parse(arrIn[4].Trim());
					s.nFall = int.Parse(arrIn[5].Trim());
					s.strEar = arrIn[6].ToLower().Trim();
					if(arrIn.Length>7)
						s.nOrigin = int.Parse(arrIn[7]);
					else
						s.nOrigin = 40;
					if(arrIn.Length>8)
						s.nInitialPhase = int.Parse(arrIn[8]);
					else
						s.nInitialPhase = 0;
					if(arrIn.Length>9)
						s.strInfo = arrIn[9];
					
				}
				else if(s.strType == "nbn")
				{
					//nbn ; center freq ; bw(in fraction of octave) ; length ms ; rise ms ; fall ms ; ear
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nOctave = int.Parse(arrIn[2].Trim());
					s.nLength = int.Parse(arrIn[3].Trim());
					s.nRise = int.Parse(arrIn[4].Trim());
					s.nFall = int.Parse(arrIn[5].Trim());
					s.strEar = arrIn[6].ToLower().Trim();
					if(arrIn.Length>7)
						s.nOrigin = int.Parse(arrIn[7]);
					else
						s.nOrigin = 40;
					if(arrIn.Length>8)
						s.strInfo = arrIn[8];
					s.AmpType = AmplificationTypes.RMS;//always do rms for noise
					
				
				}
				else if(s.strType == "nbp")
				{
					//npb ; center freq ; bw(in fraction of octave) ; length of each pulse; interval ; rise ; fall ; ear
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nOctave = int.Parse(arrIn[2].Trim());
					s.nLength = int.Parse(arrIn[3].Trim());
					s.nInterval = int.Parse(arrIn[4].Trim());
					s.nRise = int.Parse(arrIn[5].Trim());
					s.nFall = int.Parse(arrIn[6].Trim());
					s.strEar = arrIn[7].ToLower().Trim();
					if(arrIn.Length>8)
						s.nOrigin = int.Parse(arrIn[8]);
					else
						s.nOrigin = 40;
					if(arrIn.Length>9)
						s.strInfo = arrIn[9];
					s.AmpType = AmplificationTypes.RMS; //always do rms for noise
					
				}
				def.PrimaryStims.Add(s);
			}
			catch(Exception err)
			{
				ErrorMsg("Error Parsing Primary Stim Definition: {0} {1}",
					strLine, err.Message);
			}
			return; 
			
		}
		public void ParseSecondaryStimLine(string strLine)
		{
			//%PrimaryStimuli: type;file;category;initial cutoff/(center frequency);intial level;ear(s);amplification type
			//%PrimaryStimuli: type ; freq ; length ms ; rise ms ; fall ms ; ear
			//%PrimaryStimuli: type ; freq  ; length ; interval ; rise ; fall ; left

			try
			{
				string[] arrIn;
				string[] arr = new string[9];
				char[] szSeps = {';'};
				arrIn = strLine.Split(szSeps,9);
				Stim s = new Stim();
				s.strText = strLine;
				s.strType = arrIn[0].ToLower().Trim();
						
				if(s.strType == "wave")
				{
					//wav
					FileInfo f = new FileInfo(arrIn[1].Trim());
					s.strFile =f.Name;//s.strFile = arrIn[1].Trim();
					s.strStimDirectory=f.DirectoryName;
					s.strDesiredResponse = arrIn[2].Trim();
					s.strInfo = arrIn[3];
					s.nOrigin = int.Parse(arrIn[4]);
					s.strEar = arrIn[5].ToLower().Trim();
					if(arrIn[6].ToLower().Trim()=="rms")
						s.AmpType = AmplificationTypes.RMS;
					else if(arrIn[6].ToLower().Trim()=="none")
						s.AmpType = AmplificationTypes.None;
					s.nFreq = 0;

				}
				else if(s.strType == "tone")
				{
					//tone
					////%PrimaryStimuli: type ; freq ; length ms ; rise ms ; fall ms ; ear; initial level ; phase
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nLength = int.Parse(arrIn[2].Trim());
					s.nRise = int.Parse(arrIn[3].Trim());
					s.nFall = int.Parse(arrIn[4].Trim());
					s.strEar = arrIn[5].ToLower().Trim();
					if(arrIn.Length>6)
						s.nOrigin = int.Parse(arrIn[6]);
					else
						s.nOrigin = 40;
					if(arrIn.Length>7)
						s.nInitialPhase = int.Parse(arrIn[7]);
					else
						s.nInitialPhase = 0;
					if(arrIn.Length>8)
						s.strInfo = arrIn[8];
					s.strDesiredResponse = "1";
					
				}
				else if(s.strType == "pulse")
				{
					//%PrimaryStimuli: type ; freq  ; length ; interval ; rise ; fall ; ear ; initial level ; phase
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nLength = int.Parse(arrIn[2].Trim());
					s.nInterval = int.Parse(arrIn[3].Trim());
					s.nRise = int.Parse(arrIn[4].Trim());
					s.nFall = int.Parse(arrIn[5].Trim());
					s.strEar = arrIn[6].ToLower().Trim();
					if(arrIn.Length>7)
						s.nOrigin = int.Parse(arrIn[7]);
					else
						s.nOrigin = 40;
					if(arrIn.Length>8)
						s.nInitialPhase = int.Parse(arrIn[8]);
					else
						s.nInitialPhase = 0;
					if(arrIn.Length>9)
						s.strInfo = arrIn[9];
					
				}
				else if(s.strType == "nbn")
				{
					//nbn ; center freq ; bw(in fraction of octave) ; length ms ; rise ms ; fall ms ; ear
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nOctave = int.Parse(arrIn[2].Trim());
					s.nLength = int.Parse(arrIn[3].Trim());
					s.nRise = int.Parse(arrIn[4].Trim());
					s.nFall = int.Parse(arrIn[5].Trim());
					s.strEar = arrIn[6].ToLower().Trim();
					if(arrIn.Length>7)
						s.nOrigin = int.Parse(arrIn[7]);
					else
						s.nOrigin = 40;
					if(arrIn.Length>8)
						s.strInfo = arrIn[8];
					s.AmpType = AmplificationTypes.RMS;//always do rms for noise
				}
				else if(s.strType == "nbp"|| s.strType == "pnbn")
				{
					//npb ; center freq ; bw(in fraction of octave) ; length of each pulse; interval ; rise ; fall ; ear
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nOctave = int.Parse(arrIn[2].Trim());
					s.nLength = int.Parse(arrIn[3].Trim());
					s.nInterval = int.Parse(arrIn[4].Trim());
					s.nRise = int.Parse(arrIn[5].Trim());
					s.nFall = int.Parse(arrIn[6].Trim());
					s.strEar = arrIn[7].ToLower().Trim();
					if(arrIn.Length>8)
						s.nOrigin = int.Parse(arrIn[8]);
					else
						s.nOrigin = 40;
					if(arrIn.Length>9)
						s.strInfo = arrIn[9];
					s.AmpType = AmplificationTypes.RMS; //always do rms for noise
					
				}
				def.SecondaryStims.Add(s);
			}
			catch(Exception err)
			{
				ErrorMsg("Error Parsing Secondary Stim Definition: {0} {1}",
					strLine, err.Message);
			}
			
		}
		public void ParsePairedStimLine(string strLine)
		{
			try
			{
				string[] arrIn;
				string[] arr = new string[9];
				char[] szSeps = {';'};
				arrIn = strLine.Split(szSeps,9);
				Stim s = new Stim();
				s.strText = strLine;
				s.strType = arrIn[0].ToLower().Trim(); //type=wave or tone
				switch(s.strType)
				{
					case "wave":
					case "Wave":
						s.strStimDirectory= arrIn[1].Trim();
						//def.strStimDirectory = arrIn[1].Trim();
						s.strDesiredResponse = arrIn[2].Trim();
						s.strInfo = arrIn[3];
						s.nOrigin = int.Parse(arrIn[4]);
						s.strEar = arrIn[5].ToLower().Trim();
						if(arrIn[6].ToLower().Trim()=="rms")
							s.AmpType = AmplificationTypes.RMS;
						else if(arrIn[6].ToLower().Trim()=="none")
							s.AmpType = AmplificationTypes.None;
						s.nFreq = 0;
						def.PairedStims.Add(s);
						break;
					case "tone":
					////%PairedStimuli: type ; freq ; length ms ; rise ms ; fall ms ; ear; initial level ; phase
						s.nFreq = int.Parse(arrIn[1].Trim());
						s.nLength = int.Parse(arrIn[2].Trim());
						s.nRise = int.Parse(arrIn[3].Trim());
						s.nFall = int.Parse(arrIn[4].Trim());
						s.strEar = arrIn[5].ToLower().Trim();
						if(arrIn.Length>6)
							s.nOrigin = int.Parse(arrIn[6]);
						else
							s.nOrigin = 40;
						if(arrIn.Length>7)
							s.nInitialPhase = int.Parse(arrIn[7]);
						else
							s.nInitialPhase = 0;
						if(arrIn.Length>8)
							s.strInfo = arrIn[8];
						def.PairedStims.Add(s);
						break;
										
					case "pulse":
					//%PairedStimuli: type ; freq  ; length ; interval ; rise ; fall ; ear ; initial level ; phase
						s.nFreq = int.Parse(arrIn[1].Trim());
						s.nLength = int.Parse(arrIn[2].Trim());
						s.nInterval = int.Parse(arrIn[3].Trim());
						s.nRise = int.Parse(arrIn[4].Trim());
						s.nFall = int.Parse(arrIn[5].Trim());
						s.strEar = arrIn[6].ToLower().Trim();
						if(arrIn.Length>7)
							s.nOrigin = int.Parse(arrIn[7]);
						else
							s.nOrigin = 40;
						if(arrIn.Length>8)
							s.nInitialPhase = int.Parse(arrIn[8]);
						else
							s.nInitialPhase = 0;
						if(arrIn.Length>9)
							s.strInfo = arrIn[9];
						def.PairedStims.Add(s);
						break;	
				}	
			}
			catch(Exception err)
			{
				ErrorMsg("Error Parsing Paired Stim Definition: {0} {1}",
					strLine, err.Message);
			}

		}
		public void ParseComplexPrimary(StreamReader input, string strLine)
		{
			/***********************
			 * Complex line should look like:
			 * Stimuli.Primary:complex;TotalLength;NumberOfSignals
			 * Subsequent stimuli have total NumberOfSignals
			 * Each should be the same as the ParseStimlines above,
			 * with these changes
			 * Length is ignored
			 * Start time is added
			 * Stop time is added
			 * boolean adapt field on end
			 * So, a tone would look like:
			 * Stimuli.Primary:tone; freq; length ms (ignored); rise ms; fall ms; ear; initial level; phase; start; stop; bAdapt
			 * Stimuli.Primary: pulse ; freq  ; length (of pulse); interval ; rise ; fall ; ear ; initial level ; phase; start; stop; bAdapt
			 * Stimuli.Primary: nbn ; center freq ; bw(in fraction of octave) ; length ms (ignored) ; rise ms ; fall ms ; ear ; initial level; start; stop; bAdapt
			*/
			string[] arrIn;
			string[] arr = new string[3];
			char[] szSeps = {';'};
			arrIn = strLine.Split(szSeps,3);
			ComplexStim cs = new ComplexStim();
			cs.nTotalLength = int.Parse(arrIn[1].Trim());
			cs.nNumberOfStims = int.Parse(arrIn[2].Trim());
			for(int i=0;i<cs.nNumberOfStims;i++)
			{
				strLine = input.ReadLine();
				int n = strLine.IndexOf(':');
				string strVar = string.Empty;
				if(n>0)
					strVar = strLine.Substring(0,n);
				else
				{
					MessageBox.Show("Error parsing complex stim!");
					return;
				}
				Stim s = NewParseStimLine(strLine.Substring(n+1));
				/**Set the phase
				 * I'm modifying the phase here, so that when it is generated
				 * it will generate with the proper phase
				 * the specified phase is in relation to t0 - the start of signal
				 * the phase that I am calculating is what the phase would be 
				 * at t(nStart), or when the signal actually starts
				 * if 'theta' is the phase in degrees, then the basic equation for a sine wave would be
				 * sin (  2*pi*Freq*time + (theta*pi/180)  )
				 * time will be nStart, which gives us a new phase of :
				 * 2*pi*Freq*nStart + (theta*pi/180 ) in radian
				 * rad * 180 / pi to convert back to degrees
				 * or, 360*Freq*time + theta (degrees) = new phase, degrees  
				 * */
				s.nPhase = (int) (360*s.nFreq/1000.0*s.nStart+s.nInitialPhase);
				s.bIsComplexMember = true;
				cs.listStims.Add(s);
			}
			cs.nOrigin = 0;
			def.PrimaryStims.Add(cs);

		}
		public void ParseComplexSecondary(StreamReader input,string strLine)
		{
			string[] arrIn;
			string[] arr = new string[3];
			char[] szSeps = {';'};
			arrIn = strLine.Split(szSeps,3);
			ComplexStim cs = new ComplexStim();
			cs.nTotalLength = int.Parse(arrIn[1].Trim());
			cs.nNumberOfStims = int.Parse(arrIn[2].Trim());
			for(int i=0;i<cs.nNumberOfStims;i++)
			{
				strLine = input.ReadLine();
				int n = strLine.IndexOf(':');
				string strVar = string.Empty;
				if(n>0)
					strVar = strLine.Substring(0,n);
				else
				{
					MessageBox.Show("Error parsing complex stim!");
					return;
				}
				Stim s = NewParseStimLine(strLine.Substring(n+1));
				s.bIsComplexMember = true;
				cs.listStims.Add(s);
			}
			cs.nOrigin = 0;
			def.SecondaryStims.Add(cs);
		}
		public Stim NewParseStimLine(string strLine)
		{
			try
			{
				string[] arrIn;
				string[] arr = new string[12];
				char[] szSeps = {';'};
				arrIn = strLine.Split(szSeps,12);
				Stim s = new Stim();
				s.strText = strLine;
				s.strType = arrIn[0].ToLower().Trim();
				s.strDesiredResponse = "1";
						
				if(s.strType == "wave")
				{
					//wav
					s.strFile = arrIn[1].Trim();
					s.strDesiredResponse = arrIn[2].Trim();
					s.strInfo = arrIn[3];
					s.nOrigin = int.Parse(arrIn[4]);
					s.strEar = arrIn[5].ToLower().Trim();
					if(arrIn[6].ToLower().Trim()=="rms")
						s.AmpType = AmplificationTypes.RMS;
					else if(arrIn[6].ToLower().Trim()=="none")
						s.AmpType = AmplificationTypes.None;
					s.nFreq = 0;
				}
				else if(s.strType == "tone")
				{
					//tone
					////%PrimaryStimuli: type ; freq ; length ms ; rise ms ; fall ms ; ear; initial level ; phase
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nLength = int.Parse(arrIn[2].Trim());
					s.nRise = int.Parse(arrIn[3].Trim());
					s.nFall = int.Parse(arrIn[4].Trim());
					s.strEar = arrIn[5].ToLower().Trim();
					s.nOrigin = int.Parse(arrIn[6]);
					s.nInitialPhase = int.Parse(arrIn[7]);
					s.nStart = int.Parse(arrIn[8]);
					s.nStop = int.Parse(arrIn[9]);
					s.nLength = s.nStop-s.nStart;
					if(arrIn[10]=="1")
						s.bAdapt = true;
					//s.strInfo = arrIn[11];
					s.strDesiredResponse = "1";
				}
				else if(s.strType == "pulse")
				{
					//%PrimaryStimuli: type ; freq  ; length ; interval ; rise ; fall ; ear ; initial level ; phase
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nLength = int.Parse(arrIn[2].Trim());
					s.nInterval = int.Parse(arrIn[3].Trim());
					s.nRise = int.Parse(arrIn[4].Trim());
					s.nFall = int.Parse(arrIn[5].Trim());
					s.strEar = arrIn[6].ToLower().Trim();
					s.nOrigin = int.Parse(arrIn[7]);
					s.nInitialPhase = int.Parse(arrIn[8]);
					s.nStart = int.Parse(arrIn[9]);
					s.nStop = int.Parse(arrIn[10]);
					s.nLength = s.nStop-s.nStart;
					if(arrIn[11]=="1")
						s.bAdapt = true;
					//s.strInfo = arrIn[12];
					s.strDesiredResponse = "1";
				}
				else if(s.strType == "nbn")
				{
					//nbn ; center freq ; bw(in fraction of octave) ; length ms ; rise ms ; fall ms ; ear
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nOctave = int.Parse(arrIn[2].Trim());
					s.nLength = int.Parse(arrIn[3].Trim());
					s.nRise = int.Parse(arrIn[4].Trim());
					s.nFall = int.Parse(arrIn[5].Trim());
					s.strEar = arrIn[6].ToLower().Trim();
					s.nOrigin = int.Parse(arrIn[7]);
					s.nStart = int.Parse(arrIn[8]);
					s.nStop = int.Parse(arrIn[9]);
					s.nLength = s.nStop-s.nStart;
					if(arrIn[10]=="1")
						s.bAdapt = true;
					//s.strInfo = arrIn[11];
					s.AmpType = AmplificationTypes.RMS;//always do rms for noise
				}
				else if(s.strType == "nbp")
				{
					//npb ; center freq ; bw(in fraction of octave) ; length of each pulse; interval ; rise ; fall ; ear
					s.nFreq = int.Parse(arrIn[1].Trim());
					s.nOctave = int.Parse(arrIn[2].Trim());
					s.nLength = int.Parse(arrIn[3].Trim());
					s.nInterval = int.Parse(arrIn[4].Trim());
					s.nRise = int.Parse(arrIn[5].Trim());
					s.nFall = int.Parse(arrIn[6].Trim());
					s.strEar = arrIn[7].ToLower().Trim();
					s.nOrigin = int.Parse(arrIn[8]);
					s.nStart = int.Parse(arrIn[9]);
					s.nStop = int.Parse(arrIn[10]);
					s.nLength = s.nStop-s.nStart;
					if(arrIn[11]=="1")
						s.bAdapt = true;
					//s.strInfo = arrIn[12];
					s.AmpType = AmplificationTypes.RMS; //always do rms for noise
					
				}
				return s;
			}
			catch(Exception err)
			{
				ErrorMsg("Error parsing stim def: {0} {1}",
					strLine, err.Message);
			}
			return null;
		}
		public void ParseMasker(string strLine)
		{
			try
			{
				string[] arrIn;
				string[] arr = new string[5];
				char[] szSeps = {';'};
				arrIn = strLine.Split(szSeps,5);
				Stim s = new Stim();
				try
				{
					int nFreq = int.Parse(arrIn[0]);
					s.nFreq = nFreq;
				}
				catch(Exception)
				{
				
					s.strFile = arrIn[0].Trim();
				}
				s.fThreshold = int.Parse(arrIn[1]);	
				s.strEar = arrIn[2].ToLower().Trim();
				if(arrIn[3].ToLower().Trim()=="rms")
					s.AmpType = AmplificationTypes.RMS;
				else if(arrIn[3].ToLower().Trim()=="none")
					s.AmpType = AmplificationTypes.None;
				s.buffer = new WaveBuffer();
				s.bLoop = true;
				def.Masker = s;
			}
			catch(Exception err)
			{
				ErrorMsg("Error Parsing Masker Declaration: {0} {1}",
					strLine, err.Message);
			}
			
		}
		/*public void ParseStimuli(string strLine)
		{
			try
			{
				string[] arrIn;
				string[] arr = new string[8];

				//%stimuli:	file	;	category	;	info
				char[] szSeps = {'=',':',';',','};
				arrIn = strLine.Split(szSeps,5);
				Stim s = new Stim();
				s.strFile = arrIn[0].Trim();			
				s.strDesiredResponse = arrIn[1].Trim();
				s.strInfo = arrIn[2].Trim();
				s.bWav = true;
				s.Responses = new ArrayList();
				def.PrimaryStims.Add(s);
			}
			catch(Exception /*err)
			{
				MessageBox.Show("Error parsing " +strLine,"Parse Error",
					MessageBoxButtons.OK,MessageBoxIcon.Stop);
			}
		}
 */
		private void ParsePrimaryFilterLine(string strLine)
		{
			try
			{
				string[] arrIn;
				string[] arr = new string[4];

			
				char[] szSeps = {'=',':',';',','};
				arrIn = strLine.Split(szSeps,4);
				string strFilter = arrIn[0].Trim().ToLower();
				if(strFilter=="lowpass")
					def.PrimaryAdapt = AdaptiveTypes.LowPass;
				else if(strFilter == "hipass")
					def.PrimaryAdapt = AdaptiveTypes.HiPass;
				else if(strFilter == "bandpass")
					def.PrimaryAdapt = AdaptiveTypes.BandPass;
				else if(strFilter == "bandstop")
					def.PrimaryAdapt = AdaptiveTypes.BandStop;

				def.nPrimaryFilterOrder = int.Parse(arrIn[1]);
			}
			catch(Exception /*err*/)
			{
				MessageBox.Show("Error parsing " +strLine,"Parse Error",
					MessageBoxButtons.OK,MessageBoxIcon.Stop);
			}
		}
		private void ParseResults(string strLine)
		{
			try
			{
				def.listRes.Clear();
				string[] arrIn;
				char[] szSeps = {'=',':',';',','};
				arrIn = strLine.Split(szSeps,20);
				int n=0;
				for(n=0;n<arrIn.Length;n++)
				{
					string str = arrIn[n].Trim();
					if(str.Length>0)
						def.listRes.Add(str);
				}
			}
			catch(Exception /*err*/)
			{
				MessageBox.Show("Error parsing " +strLine,"Parse Error",
					MessageBoxButtons.OK,MessageBoxIcon.Stop);
			}
		}
		
		private string GameParse(string str)
		{
			if(str==null)
				return string.Empty;
			int n;
			n = str.IndexOf(';');
			if(n>0)
				str = str.Substring(0,n);
			str = str.Replace(';',' ');
			str = str.Trim();
			return str;
		}


		public bool CreateStim(ref Stim s)
		{
			try
			{
				if(s.strType=="pulse")
				{
					s.buffer.Pulse(MaxAmplitude,s.nFreq,s.nPhase,s.nLength,
						s.nRise,s.nFall,s.nInterval,s.strEar,false);
				}
				else if(s.strType == "tone")
				{
					s.buffer.Tone(MaxAmplitude,s.nFreq,s.nPhase,s.nLength,
						s.nRise,s.nFall,s.strEar,false);
				}
				else if(s.strType == "nbn")
				{
					s.buffer.NarrowBandNoise(MaxAmplitude,s.nFreq,s.nOctave,
						s.nLength,s.nRise,s.nFall,s.strEar);
					s.AmpType = AmplificationTypes.RMS;
				}
				else if(s.strType == "nbp" || s.strType == "pnbn")
				{
					s.buffer.NarrowBandPulse(MaxAmplitude,s.nFreq,s.nOctave,
						s.nLength,s.nInterval,s.nRise,s.nFall,s.strEar);
				}
				else if(s.strType == "wave")
				{ 
					FileInfo f = new FileInfo(s.strStimDirectory+"\\" +s.strFile);
					s.buffer.WaveFile(f,MaxAmplitude,s.strEar,false,s.AmpType);
				}
				s.buffer.Status = WaveBuffer.WaveStatus.Done;
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
				return false;
			}
			return true;
		}

		public int GetV2(float V1, int nFreq, string Ear)
		{
			//try left/right
			int V2 = 0;
			if(Ear.ToLower()=="left")
			{
				if(LeftCal!=null)
				{
					//if(this.chkER10C.Checked==true)
					//	V1+=6;
					return(LeftCal.CalcInt(V1,nFreq));
				}
			}
			else if(Ear.ToLower()=="right")
			{
				if(RightCal!=null)
				{
					//if(this.chkER10C.Checked==true)
					//	V1+=6;
					return(RightCal.CalcInt(V1,nFreq));
				}
			}
			else if(Ear.ToLower()=="both")
			{
				if(RightCal!=null&&LeftCal!=null)
				{
					int r = RightCal.CalcInt(V1,nFreq);
					int l = LeftCal.CalcInt(V1,nFreq);
					double d = (r+l)/2.0;
					return((int)d);
				}
			}
			//use cal
			if(cal!=null)
			{
				//if(this.chkER10C.Checked==true&&Ear.ToLower()!="both")
				if(Ear.ToLower() !="both")
					V1+=6;
				return cal.CalcInt(V1,nFreq);
			}

			//if none of the above, then do simple cal
			//manual cal
			if(V1>CalDb)
				V1 = (int) CalDb;
			double fLevel = V1 - CalDb;
			V2 = (int) (MaxAmplitude*(Math.Pow(10,fLevel/20)));
			return V2;
		}
		/*public static EngMATLib.Matrix GetMatrix(WaveBuffer buf,bool bLeft)
		{
			buf.ms.Seek(0,SeekOrigin.Begin);
			int r = 0;
			int l = 0;
			double[,] d = new double[(int)(buf.ms.Length/8),2];
			for(int i = 0;i<(buf.ms.Length/8);i++)
			{
				r = buf.reader.ReadInt32();
				l = buf.reader.ReadInt32();
				if(bLeft==true)
					d[i,0] = r>>8;
				else
					d[i,0] = r;
				if(bLeft==true)
					d[i,1] = l>>8;
				else
					d[i,1] = l/2;
			}
			Matrix m = new Matrix(d);
			return m;

		}
*/
		public static void DebugWrite ( string astrFormat, params object[] aobj_ ) 
		{
			// This function allows passing of multiple arguments so that I can
			// emulate the String.Format() functionality.
			//
			// By having this as a separate function, I can turn it off with a
			// compiler directive.
#if DBUG
			swDbug.WriteLine ( astrFormat, aobj_ );
#endif
		}

		public static void ErrorMsg(string astrFormat, params object[] aobj)
		{
			string str = string.Format(astrFormat,aobj);
			MessageBox.Show(str,"Error",MessageBoxButtons.OK,MessageBoxIcon.Warning);
		}
		private void timerLabel_Elapsed(object sender, ElapsedEventArgs e)
		{
            //string str = lbl.Text.Trim();
            //int i = rand.Next(Colors.Count);
            //if(str.Length<40)
            //    lbl.Text = "*" +str +"*";
            //else
            //    lbl.Text = "DID YOU CALIBRATE?";
            //lbl.ForeColor = (Color)Colors[i];
            //lbl.Update();
		}

		private void RunPairedComparison_Click(object sender, System.EventArgs e)
		{
			
			try
			{
				FileInfo fResult = new FileInfo(txtResultFile.Text);
				if(fResult.Exists)
					if(MessageBox.Show("File "+fResult.FullName + " already exists. Overwrite ?","Confirm Overwrite",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)== DialogResult.No)
						return;
				def = new Definitions();
				timerLabel.Stop();		

				Progress progress = new Progress();
				progress.Init("Starting Paired Comparison",100,0,1);
				progress.Show();
				PairedComparison pc = new PairedComparison();
				pc.mainmenu = this;
				progress.Increment();
				this.Hide();
				progress.SetLabel("Reading Init File");
				progress.Increment();
				if(ReadInitFile(progress)==false)
				{
					MessageBox.Show("Error reading Definitions File!","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
					pc.Dispose();
					this.Show();
					progress.Close();
					return;
				}
				try
				{
					output = new StreamWriter(txtResultFile.Text,this.chkAppend.Checked);
					if(output==null)
					{
						Exception err = new Exception("Unable to create output File.");
					}
					output.Close();
				}
				catch(Exception)
				{
					MessageBox.Show("Unable to create result file.","File Error");
					return;
				}
				
				progress.SetLabel("Starting Paired Comparison");
				progress.Increment();
				pc.outfile = new FileInfo(txtResultFile.Text);
				progress.Increment();
				
				progress.Increment();
				progress.Close();
				pc.Show();
				pc.Init();
				
			}
			catch(Exception err)
			{
				MessageBox.Show("Error: " + err.Message);
				this.Show();
			}
		}
	}
	/// <summary>
	/// Enum of available adaptive types
	/// </summary>
	public enum AdaptiveTypes
	{
		Level,
		LowPass,
		HiPass,
		BandPass,
		BandStop,
		MFile,
		None
	}
}
