using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectDraw;
using Microsoft.DirectX.DirectSound;
using Audiogram;

namespace HearingAidLab
{
	/// <summary>
	/// Summary description for StarResults.
	/// </summary>
	public class StarResults : System.Windows.Forms.Form
	{
		/// <summary>
		/// Required designer variable.
		/// </summary> 
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label3;
		public System.Windows.Forms.ListView list1;
		private System.ComponentModel.Container components = null;
	
		private Audiogram.AudPt CurrentPt = new Audiogram.AudPt();
		private Microsoft.DirectX.DirectDraw.Device draw2 = null; // Holds the DrawDevice object.
		private Surface primary2 = null; // Holds the primary destination surface.
		private Surface offscreen2 = null; // Holds the offscreen surface that the bitmap will be loaded on.
		private Clipper clip2 = null; // Holds the clipper object.
		private Rectangle destination2 = new Rectangle();
		private System.Windows.Forms.Panel panel1;
		private System.Windows.Forms.Panel panel2;
		private ArrayList listPanel1 = new ArrayList();
		private ArrayList listPanel2 = new ArrayList();
		public System.Windows.Forms.ListView listLeft;
		public System.Windows.Forms.ListView listRight;
		private AudiogramClass audio;
		private bool Paused = false;
		private bool bCatch = false;
		private bool bDone = false;
				
		private Font font = null;//screen text font;
		private Font font2 = null;//screen text font;
		private Font font3 = null;
		private System.Windows.Forms.Button btnPause;//screen text font;
		private DateTime dtStart;
		private System.Windows.Forms.Button btnSkip;
		private System.Windows.Forms.Button btnReset;
		private System.Windows.Forms.Button btnPrint;
		private System.Drawing.Printing.PrintDocument m_printDocument1 = new System.Drawing.Printing.PrintDocument();
		private ListViewColumnSorter lvwColumnSorter;
		private System.Windows.Forms.Button TestMasking;
		private System.Windows.Forms.StatusBar statusBar1;
		private System.Windows.Forms.StatusBarPanel sbTime;
		private System.Windows.Forms.StatusBarPanel sbCurrent;
		private System.Windows.Forms.StatusBarPanel sbStdErr;
		private System.Windows.Forms.StatusBarPanel sbReversals;
		private System.Windows.Forms.StatusBarPanel sbStatus;
		private System.Windows.Forms.Label lblKey;
		private System.Windows.Forms.Label lblCal;

		public StarAudio Star;
		
		public StarResults()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			panel1 = new Panel();
			panel2 = new Panel();
			dtStart = DateTime.Now;
			this.Controls.Add(panel1);
			this.Controls.Add(panel2);

			draw2 = new Microsoft.DirectX.DirectDraw.Device(); // Create a new DrawDevice, using the default device.
			draw2.SetCooperativeLevel(this.panel2, CooperativeLevelFlags.Normal); // Set the coop level to normal windowed mode.
			font = new Font("Arial",8);
			font2 = new Font("Arial",12);
			font3 = new Font("Arial",18);

			m_printDocument1.PrintPage += new PrintPageEventHandler(pd_PrintPage);
			this.Closing += new CancelEventHandler(StarResults_Closing);

			lvwColumnSorter = new ListViewColumnSorter();
			lvwColumnSorter.bInteger = true;
			listRight.ListViewItemSorter = lvwColumnSorter;
			listLeft.ListViewItemSorter = lvwColumnSorter;
			listRight.ColumnClick += new ColumnClickEventHandler(listRight_ColumnClick);
			listLeft.ColumnClick += new ColumnClickEventHandler(listLeft_ColumnClick);


			ColumnHeader c = new ColumnHeader();
			ColumnHeader d;
			c = new ColumnHeader();
			c.Text = "Method";
			c.Width = -2;
			listLeft.Columns.Add(c);
			d = (ColumnHeader) c.Clone();
			listRight.Columns.Add(d);
			c = new ColumnHeader();
			c.Text = "Frequency";
			c.Width = -2;
			listLeft.Columns.Add(c);
			d = (ColumnHeader) c.Clone();
			listRight.Columns.Add(d);
			c = new ColumnHeader();
			c.Text = "Threshold";
			c.Width = -2;
			listLeft.Columns.Add(c);
			d = (ColumnHeader) c.Clone();
			listRight.Columns.Add(d);
			c = new ColumnHeader();
			c.Text = "Standard Error";
			c.Width = -2;
			listLeft.Columns.Add(c);
			d = (ColumnHeader) c.Clone();
			listRight.Columns.Add(d);
			c = new ColumnHeader();
			c.Text = "Reversals";
			c.Width = -2;
			listLeft.Columns.Add(c);
			d = (ColumnHeader) c.Clone();
			listRight.Columns.Add(d);
			ShowStatus("Ready");

			
		}

		/// <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()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(StarResults));
			this.label1 = new System.Windows.Forms.Label();
			this.list1 = new System.Windows.Forms.ListView();
			this.label3 = new System.Windows.Forms.Label();
			this.listLeft = new System.Windows.Forms.ListView();
			this.listRight = new System.Windows.Forms.ListView();
			this.btnPause = new System.Windows.Forms.Button();
			this.btnSkip = new System.Windows.Forms.Button();
			this.btnReset = new System.Windows.Forms.Button();
			this.btnPrint = new System.Windows.Forms.Button();
			this.TestMasking = new System.Windows.Forms.Button();
			this.statusBar1 = new System.Windows.Forms.StatusBar();
			this.sbTime = new System.Windows.Forms.StatusBarPanel();
			this.sbCurrent = new System.Windows.Forms.StatusBarPanel();
			this.sbStdErr = new System.Windows.Forms.StatusBarPanel();
			this.sbReversals = new System.Windows.Forms.StatusBarPanel();
			this.sbStatus = new System.Windows.Forms.StatusBarPanel();
			this.lblKey = new System.Windows.Forms.Label();
			this.lblCal = new System.Windows.Forms.Label();
			((System.ComponentModel.ISupportInitialize)(this.sbTime)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.sbCurrent)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.sbStdErr)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.sbReversals)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.sbStatus)).BeginInit();
			this.SuspendLayout();
			// 
			// label1
			// 
			this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.label1.Location = new System.Drawing.Point(420, 8);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(128, 23);
			this.label1.TabIndex = 0;
			this.label1.Text = "Left Ear";
			this.label1.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
			// 
			// list1
			// 
			this.list1.Anchor = System.Windows.Forms.AnchorStyles.Right;
			this.list1.Location = new System.Drawing.Point(424, 272);
			this.list1.Name = "list1";
			this.list1.Size = new System.Drawing.Size(296, 128);
			this.list1.TabIndex = 4;
			this.list1.View = System.Windows.Forms.View.Details;
			// 
			// label3
			// 
			this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.label3.Location = new System.Drawing.Point(420, 128);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(128, 23);
			this.label3.TabIndex = 7;
			this.label3.Text = "Right Ear";
			this.label3.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
			// 
			// listLeft
			// 
			this.listLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.listLeft.Location = new System.Drawing.Point(420, 32);
			this.listLeft.Name = "listLeft";
			this.listLeft.Size = new System.Drawing.Size(300, 96);
			this.listLeft.TabIndex = 8;
			this.listLeft.View = System.Windows.Forms.View.Details;
			// 
			// listRight
			// 
			this.listRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.listRight.Location = new System.Drawing.Point(420, 152);
			this.listRight.Name = "listRight";
			this.listRight.Size = new System.Drawing.Size(296, 96);
			this.listRight.TabIndex = 9;
			this.listRight.View = System.Windows.Forms.View.Details;
			// 
			// btnPause
			// 
			this.btnPause.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.btnPause.Location = new System.Drawing.Point(400, 440);
			this.btnPause.Name = "btnPause";
			this.btnPause.TabIndex = 10;
			this.btnPause.Text = "Pause";
			this.btnPause.Visible = false;
			this.btnPause.Click += new System.EventHandler(this.btnPause_Click);
			// 
			// btnSkip
			// 
			this.btnSkip.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.btnSkip.Location = new System.Drawing.Point(432, 440);
			this.btnSkip.Name = "btnSkip";
			this.btnSkip.TabIndex = 14;
			this.btnSkip.Text = "Skip";
			this.btnSkip.Visible = false;
			this.btnSkip.Click += new System.EventHandler(this.btnSkip_Click);
			// 
			// btnReset
			// 
			this.btnReset.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.btnReset.Location = new System.Drawing.Point(496, 440);
			this.btnReset.Name = "btnReset";
			this.btnReset.TabIndex = 15;
			this.btnReset.Text = "Reset";
			this.btnReset.Visible = false;
			this.btnReset.Click += new System.EventHandler(this.btnReset_Click);
			// 
			// btnPrint
			// 
			this.btnPrint.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
			this.btnPrint.Location = new System.Drawing.Point(640, 440);
			this.btnPrint.Name = "btnPrint";
			this.btnPrint.TabIndex = 16;
			this.btnPrint.Text = "Print";
			this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
			// 
			// TestMasking
			// 
			this.TestMasking.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.TestMasking.Location = new System.Drawing.Point(552, 440);
			this.TestMasking.Name = "TestMasking";
			this.TestMasking.Size = new System.Drawing.Size(88, 23);
			this.TestMasking.TabIndex = 17;
			this.TestMasking.Text = "Test Masking";
			this.TestMasking.Visible = false;
			this.TestMasking.Click += new System.EventHandler(this.TestMasking_Click);
			// 
			// statusBar1
			// 
			this.statusBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.statusBar1.Dock = System.Windows.Forms.DockStyle.None;
			this.statusBar1.Location = new System.Drawing.Point(0, 472);
			this.statusBar1.Name = "statusBar1";
			this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
																						  this.sbTime,
																						  this.sbCurrent,
																						  this.sbStdErr,
																						  this.sbReversals,
																						  this.sbStatus});
			this.statusBar1.ShowPanels = true;
			this.statusBar1.Size = new System.Drawing.Size(728, 24);
			this.statusBar1.TabIndex = 18;
			this.statusBar1.Text = "statusBar1";
			// 
			// sbTime
			// 
			this.sbTime.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
			this.sbTime.Text = "Elapsed Time:";
			this.sbTime.Width = 142;
			// 
			// sbCurrent
			// 
			this.sbCurrent.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
			this.sbCurrent.Text = "Current Stim:";
			this.sbCurrent.Width = 142;
			// 
			// sbStdErr
			// 
			this.sbStdErr.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
			this.sbStdErr.Text = "Standard Error:";
			this.sbStdErr.Width = 142;
			// 
			// sbReversals
			// 
			this.sbReversals.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
			this.sbReversals.Text = "Reversals:";
			this.sbReversals.Width = 142;
			// 
			// sbStatus
			// 
			this.sbStatus.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
			this.sbStatus.Text = "Status:";
			this.sbStatus.Width = 142;
			// 
			// lblKey
			// 
			this.lblKey.Location = new System.Drawing.Point(424, 392);
			this.lblKey.Name = "lblKey";
			this.lblKey.Size = new System.Drawing.Size(100, 72);
			this.lblKey.TabIndex = 19;
			this.lblKey.Text = "label2";
			// 
			// lblCal
			// 
			this.lblCal.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.lblCal.Location = new System.Drawing.Point(8, 448);
			this.lblCal.Name = "lblCal";
			this.lblCal.Size = new System.Drawing.Size(384, 23);
			this.lblCal.TabIndex = 20;
			this.lblCal.Text = "label2";
			// 
			// StarResults
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(728, 494);
			this.Controls.Add(this.lblCal);
			this.Controls.Add(this.lblKey);
			this.Controls.Add(this.statusBar1);
			this.Controls.Add(this.TestMasking);
			this.Controls.Add(this.btnPrint);
			this.Controls.Add(this.btnReset);
			this.Controls.Add(this.btnSkip);
			this.Controls.Add(this.btnPause);
			this.Controls.Add(this.listRight);
			this.Controls.Add(this.listLeft);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.list1);
			this.Controls.Add(this.label1);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Name = "StarResults";
			this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
			this.Text = "STAR Results";
			this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
			((System.ComponentModel.ISupportInitialize)(this.sbTime)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.sbCurrent)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.sbStdErr)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.sbReversals)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.sbStatus)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		public void CreateSurfaces()
		{
			SurfaceDescription description2 = new SurfaceDescription(); // Create a new SurfaceDescription struct.

			if(primary2!=null)
				primary2.Dispose();
			description2.SurfaceCaps.PrimarySurface = true; // The caps for this surface is simply primary.
			IntPtr ptr;
			ptr = font.ToHfont();
			primary2 = new Surface(description2, draw2); // Create the primary surface.
			clip2 = new Clipper(draw2); // Create a new clipper.
			clip2.Window = this.panel2; // The clipper will use the main window handle.
			primary2.Clipper = clip2; // Assign this clipper to the primary surface.
			description2.Clear(); // Clear the SurfaceDescription struct.
			description2.SurfaceCaps.OffScreenPlain = true;
			// Set the height and width of the text.
			description2.Width = panel2.Width;
			description2.Height = 2*this.Height/5;
			offscreen2 = new Surface(description2,draw2);
			offscreen2.FontHandle = ptr;
			
		}

		private void Draw()
		{
			try
			{
			TimeSpan s = DateTime.Now-dtStart;
			this.sbTime.Text = "Elapsed Time: " + s.Hours.ToString() + ":" + s.Minutes.ToString() + ":" + s.Seconds.ToString();
			
			/*if (null == primary1)
				return;*/
			if (null == primary2)
				return;
			if (FormWindowState.Minimized == WindowState)
				return;
			Height = Height < 50 ? 50 : Height; // Make sure the height is always valid.
			audio.ClearPtList();
			foreach(AudPt p in this.listPanel1)
				audio.AddPoint(p);
			if(bDone==false)
			{
				AudPt a = new AudPt();
				a.Freq = CurrentPt.Freq;
				a.Threshold = CurrentPt.Threshold;
				a.Symbol = CurrentPt.Symbol+2;
				audio.AddPoint(a);
			}
			
			audio.Draw(PointToScreen(panel1.Location));

			//panel2
			destination2 = new Rectangle(panel2.Location, panel2.Size);
			offscreen2.ColorFill(Color.Black);
			IntPtr ptr;
			ptr = font.ToHfont();
			offscreen2.FontHandle = ptr;
			offscreen2.ForeColor = Color.White;
			offscreen2.DrawText(panel2.Width/2,panel2.Height-20,"Trial",false);
			offscreen2.DrawText(8,panel2.Height/2,"SPL (dB)",false);
			//frame lines
			for(int i=1;i<9;i++)
				offscreen2.DrawLine(i*panel2.Width/9,8*panel2.Height/9,i*panel2.Width/9,panel2.Height/9);
			for(int i=1;i<9;i++)
				offscreen2.DrawLine(panel2.Width/9,i*panel2.Height/9,8*panel2.Width/9,i*panel2.Height/9);
			int l = 120;
			for(int i=1;i<9;i++)
			{
				offscreen2.DrawText(panel2.Width/9-18,i*panel2.Height/9-6,l.ToString(),false);
				l-=20;
			}
			//DrawTrials
			ptr = font3.ToHfont();
			offscreen2.FontHandle = ptr;
			if(bCatch==true)
				offscreen2.DrawText(20,40,"Catch Trial!",false);
			foreach(AudPt pt in listPanel2)
			{
				/*if(listPanel2.Count-8>listPanel2.IndexOf(pt))
					continue;*/
				if(pt.Symbol==1)
				{
					offscreen2.ForeColor = Color.Green;
					offscreen2.DrawText(pt.Freq,pt.Threshold,"+",false);
				}
				else if(pt.Symbol==0)
				{
					offscreen2.ForeColor = Color.Red;
					offscreen2.DrawText(pt.Freq,pt.Threshold,"-",false);
				}
				else if(pt.Symbol==3)
				{
					offscreen2.ForeColor = Color.Red;
					offscreen2.DrawText(pt.Freq,pt.Threshold,"C",false);
				}
			}
		
				// Try and Draw the offscreen surface on to the primary surface.
				primary2.Draw(destination2, offscreen2, DrawFlags.Wait);
			}
			catch(SurfaceLostException)
			{
				// The surface can be lost if power saving
				// mode kicks in, or any other number of
				// reasons.
				CreateSurfaces(); // Surface was lost. Recreate them.
			}
			//position the lists
			listLeft.Height = this.Height/4-label3.Height;
			listRight.Height = listLeft.Height;
			Point x = this.listLeft.Location;
			x.Y += listLeft.Height+5;
			label3.Location = x;
			x.Y += label3.Height;
            listRight.Location = x;
			x = this.listRight.Location;
			x.Y += listRight.Height+5;
			list1.Height = listLeft.Height;
			list1.Location = x;
			lblKey.Text = "Keys:\r\n"+
				"P - Pause\r\n"+
				"C - Continue\r\n"+
				"R - Reset\r\n"+
				"S - Skip";
			x = this.list1.Location;
			x.Y += list1.Height+5;
			lblKey.Location = x;
			
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			base.OnPaint (e);
			Draw();
			
		}

		public void Format()
		{
			panel1.Location = new Point(8,10);
			panel1.Size = new Size(listLeft.Location.X-10,this.Height/2-20);
			audio = new AudiogramClass();
			audio.SetPanel(panel1);
			audio.Type = Audiogram.GraphType.SPL;
			audio.BackgroundColor = Color.Black;
			audio.ForeColor = Color.Red;
			audio.SetSize(panel1.Size);
			panel2.Size = new Size(listLeft.Location.X-10,(int)(2*this.Height/5));
			panel2.Location = new Point(8,panel1.Height+30);
			lblCal.Text = Star.GetCal();
			//list1.Location = new Point(list1.Location.X,panel1.Height+30);
		}

		public void FillList(ArrayList stims)
		{
			list1.Items.Clear();
			list1.Clear();
            ColumnHeader c = new ColumnHeader();
			c.Text = "Ear";
			c.Width = 35;
			list1.Columns.Add(c);
			c = new ColumnHeader();
			c.Text = "Method";
			c.Width = 50;
			list1.Columns.Add(c);
			c = new ColumnHeader();
			c.Text = "Freq";
			c.Width = 40;
			list1.Columns.Add(c);
			ListViewItem i;
			foreach(Stim s in stims)
			{
				i = new ListViewItem();
				i.Text = s.strEar;
				if(s.nMethod == 2)
					i.SubItems.Add("70%");
				else if(s.nMethod == 3)
					i.SubItems.Add("30%");
				else
					i.SubItems.Add("50%");
				i.SubItems.Add(s.nFreq.ToString());
				this.list1.Items.Add(i);
			}
		}
		public void ShowCurrentLevel(Stim stim,int nLevel)
		{
			CurrentPt.Freq = stim.nFreq;
			CurrentPt.Threshold = nLevel;
			if(stim.strEar=="left")
				CurrentPt.Symbol = 1;
			else if(stim.strEar=="right")
				CurrentPt.Symbol = 2;
			else
				CurrentPt.Symbol = 1;
			this.sbCurrent.Text = "Current Stim: " + stim.strEar + " " + stim.nFreq.ToString() +" " + nLevel.ToString() + "dB"; 
			this.Redraw();
			this.Update();
		}
		public void ShowCatchTrial()
		{
			bCatch=true;
			sbCurrent.Text = "CurrentStim: Catch Trial";
			Draw();
			bCatch=false;
		}
		public void AddAudPoint(Stim stim,double StdErr, int Reversals)
		{
			AudPt p = new AudPt();
			p.Freq = stim.nFreq;
			p.Threshold = (int) stim.fThreshold;
			if(stim.strEar=="left")
				p.Symbol = 1;
			else if(stim.strEar=="right")
				p.Symbol = 2;
			else
				p.Symbol = 1;
			this.listPanel1.Add(p);

			
			ListViewItem i = new ListViewItem();
			if(stim.nMethod==1)
				i.Text = "50%";
			else if(stim.nMethod==2)
				i.Text = "70%";
			else if(stim.nMethod==3)
				i.Text = "30%";
			i.SubItems.Add(stim.nFreq.ToString());
			i.SubItems.Add(stim.fThreshold.ToString("###"));
			i.SubItems.Add(StdErr.ToString(".00"));
			i.SubItems.Add(Reversals.ToString());
			this.lvwColumnSorter.SortColumn=0;
			this.lvwColumnSorter.Order = SortOrder.Ascending;
			ColumnClickEventArgs e = new ColumnClickEventArgs(1);
			if(stim.strEar=="right")
			{
				listRight.Items.Add(i);
				this.listRight_ColumnClick(listRight,e);
			}
			else
			{
				listLeft.Items.Add(i);
				this.listLeft_ColumnClick(listLeft,e);
			}
		}
		public void ShowResponses(ArrayList response, ArrayList Levels)
		{
			listPanel2.Clear();
			AudPt p;
			int n=0;
			//Get Full X Scale
			int Xorigin = panel2.Width/9;
			int Xscale = 8*panel2.Width/9 - Xorigin;
			double x, y;
			int nCount=0;
			int kk=0;
			if(response.Count>15)
					kk += response.Count-15;
			for(;kk<response.Count;kk++)
			{
				
				bool r = (bool) response[kk];
				if(Levels.Count>n)
				{
					p = new AudPt();
					if(r==true)
						p.Symbol = 1;
					else
						p.Symbol = 0;
					if(kk<Levels.Count)
						y = 120-(int)Levels[kk];
					else
						y = 120-(int)Levels[Levels.Count-1];
					//y full range = panel1.Height/8 -> 7*panel.Height/8
					float maxY = (float)8*panel2.Height/9.0f;
					float minY = (float)panel2.Height/9.0f;
					float YScale = (maxY - minY) / 140.0f;//full range
					y = y*YScale+33.11/2;//+33.11 (panel2.Width/9)  offset of from top, - size of half the symbol
					
					x = Xorigin+((nCount/15.0f)*Xscale);
					p.Freq = (int) x;
					p.Threshold = (int) y;
					listPanel2.Add(p);
					n++;
				}
				else
					break;
				nCount++;
			}

		}
		public void ShowStdErr(double stderr)
		{
			if(stderr==5.0)
				sbStdErr.Text = "Standard Error: NA";
			else
				sbStdErr.Text = "Standard Error: " + stderr.ToString("###.00");
		}
		public void ShowReversals(string Type, int Reversals)
		{
			this.sbReversals.Text = "Reversals: " + Type+": " + Reversals.ToString();
		}
		public void ShowStatus(string status)
		{
			this.sbStatus.Text = "Status: " + status;
		}
		public void Skip(Stim s)
		{
			int Symbol = 0;
			if(s.strEar=="right")
				Symbol = 2;
			else
				Symbol = 1;
			
			for(int i=0;i<listPanel1.Count;i++)
			{
				AudPt p = (AudPt) listPanel1[i];
				if(p.Freq==s.nFreq&&p.Symbol==Symbol)
				{
					listPanel1.Remove(p);
					i--;
				}
			}
		}
		public void Redraw()
		{
			this.Draw();
		}
		public bool IsActive()
		{
			return !bDone;
		}
		public void Done()
		{
			bDone = true;
			audio.Done();
		}
		public bool Start()
		{
			DialogResult r = MessageBox.Show(this,"Click 'OK' when you are ready to begin, or 'Cancel' to abort!","Ready?",MessageBoxButtons.OKCancel,MessageBoxIcon.Information);
			if(r == DialogResult.OK)
			{
				dtStart = DateTime.Now;
				return true;
			}
			else 
				return false;
		}
		private void StarResults_Closing(object sender, CancelEventArgs e)
		{
			Star.Close();

		}

		public void btnPause_Click(object sender, System.EventArgs e)
		{
			if(Paused==false)
			{
				Star.timer.Stop();
				Star.timer2.Stop();
				Star.timer3.Stop();
				Star.timerCatch.Stop();
				Star.player.Stop();
				Star.bButtons = false;
				Paused = true;
				ShowStatus("PAUSED");

			}
			else
			{
				Star.timer2.Start();
				Star.bButtons = true;
				Paused = false;
				ShowStatus("Working");
			}
		}
		public void Continue()
		{
			Star.bButtons = false;
			Star.timer.Stop();
			Star.timer2.Stop();
			Star.timer3.Stop();
			Star.timerCatch.Stop();
			Star.player.Stop();
			Star.timer2.Start();
			Star.bButtons = true;
			Paused = false;
			ShowStatus("Working");
		}

		private void btnReset_Click(object sender, System.EventArgs e)
		{
			Star.Reset();
		}

		private void btnSkip_Click(object sender, System.EventArgs e)
		{
			Star.Skip();
		}

		private void btnPrint_Click(object sender, System.EventArgs e)
		{
			
			PrintDialog dlgPrint = new System.Windows.Forms.PrintDialog();
			dlgPrint.Document = m_printDocument1;
			dlgPrint.Document.DefaultPageSettings.Landscape = false;
			if(dlgPrint.ShowDialog()==DialogResult.OK)
			{
				m_printDocument1.Print();
			}
			
		
		}
		private void pd_PrintPage(object sender, PrintPageEventArgs e)
		{
			System.Drawing.Printing.PrinterResolution res = e.PageSettings.PrinterResolution;
			//float X = res.X;
			//float Y = res.Y/2;
			e.Graphics.PageUnit = GraphicsUnit.Point;
			float X = 72*8;
			float Y = 72*11;
			Y = Y/2;
			float Z = 0;
			System.Drawing.SolidBrush brush = new SolidBrush(Color.Black);
			Pen pen = new Pen(brush,1);
			
			Graphics g = e.Graphics;
			Font fontText = new Font("Arial",10);
			
			g.DrawString(Star.outfile.Name,fontText,brush,0,0);
			g.DrawString(Star.mainmenu.txtName.Text,fontText,brush,0,10);

			//Audiogram
			g.DrawString("Audiogram",fontText,brush,(float) (X/2-40),(float)(Y*.05));
			g.DrawString("Frequency (Hz)",fontText,brush,(float)(X/2-50),(float)(Y*.95));
			g.DrawString("HL",fontText,brush,(float) 0.05*X,(float)(Y/2));
			g.DrawString("(dB SPL)",fontText,brush,(float)0,(float)(Y/2+0.05*Y));
			for(int i=1;i<9;i++)
			{
				g.DrawLine(pen,i*X/9,Z+8*Y/9,i*X/9,Z+Y/9);
			}
			for(int i=1;i<9;i++)
			{
				g.DrawLine(pen,X/9,Z+i*Y/9,8*X/9,Z+i*Y/9);
			}
			int l = 250;
			for(int i=2;i<8;i++)
			{
				g.DrawString(l.ToString(),fontText,brush,(float)(i*X/9-10),(float)(Z+8*Y/9));
				l*=2;
			}
			l = 140;
			for(int i=1;i<9;i++)
			{
				g.DrawString(l.ToString(),fontText,brush,X/9-18,Z+i*Y/9-6);
				l-=20;
			}
			Audiogram.AudPt lastRed = null;
			Audiogram.AudPt lastBlue = null;
			foreach(Audiogram.AudPt pt in audio.listPts)
			{
				
				float nX = 0;
					
				int nFreq = pt.Freq;
				float maxX = (float)8*X/9.0f;
				float minX = (float)X/9.0f;
				double XScale = (maxX - minX)/((Math.Log(16000,2))-(Math.Log(125,2)));
				double d = Math.Log(nFreq,2)-Math.Log(125,2);
				nX += (float) (d*XScale+X/9.0f);
					
				//y range is -20-50
				float nY = pt.Threshold;
				//nY += 10; //move it up ten, for convenience
				float maxY = (float)8*Y/9.0f;
				float minY = (float)Y/9.0f;
				float YScale = (maxY - minY) / 140.0f;//full range
				nY =(float) ((140-nY)*YScale+Y/9.0f);

				if(pt.Symbol==1)
				{
					SolidBrush br = new SolidBrush(Color.Blue);
					Pen pe = new Pen(br,1);
					g.DrawString("X",fontText,br,nX,nY);
					if(lastBlue != null)
					{
						g.DrawLine(pe,lastBlue.xPos,(lastBlue.yPos),(int)nX,(int)(nY));
					}
					lastBlue = new AudPt((int)nX,(int)nY,1);
					lastBlue.xPos = nX;
					lastBlue.yPos = nY;
						
				}
				else if(pt.Symbol==2)
				{
					SolidBrush br = new SolidBrush(Color.Red);
					Pen pe = new Pen(br,1);
					g.FillEllipse(br,(nX),(int)(nY),8,8);
					if(lastRed != null)
					{
						g.DrawLine(pe,lastRed.xPos,(lastRed.yPos),(int)nX,(int)(nY));
					}
					lastRed = new AudPt((int)nX,(int)nY,1);
					lastRed.xPos = nX;
					lastRed.yPos = nY;
				}
				else if(pt.Symbol==3)
				{
					SolidBrush br = new SolidBrush(Color.Blue);
					Pen pe = new Pen(br,1);
					g.DrawString("X",fontText,br,nX,nY);
				}
				else if(pt.Symbol==4)
				{
					SolidBrush br = new SolidBrush(Color.Red);
					Pen pe = new Pen(br,1);
					g.FillEllipse(br,(nX),(int)(nY),8,8);
				}

			}
			
		
		}

		private void listRight_ColumnClick(object sender, ColumnClickEventArgs e)
		{
			// Determine if clicked column is already the column that is being sorted.
			//lvwColumnSorter.bInteger = true;
			
			if ( e.Column == lvwColumnSorter.SortColumn )
			{
				// Reverse the current sort direction for this column.
				if (lvwColumnSorter.Order == SortOrder.Ascending)
				{
					lvwColumnSorter.Order = SortOrder.Descending;
				}
				else
				{
					lvwColumnSorter.Order = SortOrder.Ascending;
				}
			}
			else
			{
				// Set the column number that is to be sorted; default to ascending.
				lvwColumnSorter.SortColumn = e.Column;
				lvwColumnSorter.Order = SortOrder.Ascending;
			}

			// Perform the sort with these new sort options.
			this.listRight.Sort();

		}

		private void listLeft_ColumnClick(object sender, ColumnClickEventArgs e)
		{
			// Determine if clicked column is already the column that is being sorted.
			//lvwColumnSorter.bInteger = true;
			
			if ( e.Column == lvwColumnSorter.SortColumn )
			{
				// Reverse the current sort direction for this column.
				if (lvwColumnSorter.Order == SortOrder.Ascending)
				{
					lvwColumnSorter.Order = SortOrder.Descending;
				}
				else
				{
					lvwColumnSorter.Order = SortOrder.Ascending;
				}
			}
			else
			{
				// Set the column number that is to be sorted; default to ascending.
				lvwColumnSorter.SortColumn = e.Column;
				lvwColumnSorter.Order = SortOrder.Ascending;
			}

			// Perform the sort with these new sort options.
			this.listLeft.Sort();

		}

		private void TestMasking_Click(object sender, System.EventArgs e)
		{
			Star.TestMasking();
		}
	}
}
