﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
// Counter Header
using CcntCs;

namespace Infinite
{
	/// <summary>
	/// Summary description for Infinite.
	/// </summary>
	public class Infinite : System.Windows.Forms.Form
	{
		internal System.Windows.Forms.TextBox txtTransCount;
		internal System.Windows.Forms.TextBox txtStatus;
		internal System.Windows.Forms.TextBox txtError;
		internal System.Windows.Forms.Label Label5;
		internal System.Windows.Forms.Label Label4;
		internal System.Windows.Forms.Label Label3;
		internal System.Windows.Forms.Label Label2;
		internal System.Windows.Forms.Button btnExit;
		internal System.Windows.Forms.Button btnCntExit;
		internal System.Windows.Forms.Button btnStatus;
		internal System.Windows.Forms.Button btnCount;
		internal System.Windows.Forms.Button btnData;
		internal System.Windows.Forms.Button btnStop;
		internal System.Windows.Forms.Button btnStart;
		internal System.Windows.Forms.Button btnCondition;
		internal System.Windows.Forms.Button btnMode;
		internal System.Windows.Forms.Button btnCntInit;
		internal System.Windows.Forms.TextBox txtReturn;
		internal System.Windows.Forms.Label Label1;
		internal System.Windows.Forms.TextBox txtDeviceName;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public static short		Id;												  // Device ID
		uint[]					CountMatch	   = new uint[CHANNEL_NUM];	          // Count match number
		public const int		CHANNEL_NUM	   = 4;
		public const int		DATA_NUM	   = 1000;
		int	                    NumberOfData	= 500;
		uint[,]				    SamplingData   = new uint[DATA_NUM, CHANNEL_NUM]; // Buffer for sampling
		public static uint		ReadIndex;								          // Read pointer
		public static uint		WriteIndex;								          // Write pointer
		public static uint		PreCount;								          // Previous transfer count
		public static uint		PreCarry;								          // Previous carry count
		public static string	file_name = "infinite.csv";

		Ccnt					cnt			   = new Ccnt();

		GCHandle			    gCh;
		IntPtr				    pSamplingData;

		public Infinite()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <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.txtTransCount = new System.Windows.Forms.TextBox();
			this.txtStatus = new System.Windows.Forms.TextBox();
			this.txtError = new System.Windows.Forms.TextBox();
			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.btnExit = new System.Windows.Forms.Button();
			this.btnCntExit = new System.Windows.Forms.Button();
			this.btnStatus = new System.Windows.Forms.Button();
			this.btnCount = new System.Windows.Forms.Button();
			this.btnData = new System.Windows.Forms.Button();
			this.btnStop = new System.Windows.Forms.Button();
			this.btnStart = new System.Windows.Forms.Button();
			this.btnCondition = new System.Windows.Forms.Button();
			this.btnMode = new System.Windows.Forms.Button();
			this.btnCntInit = new System.Windows.Forms.Button();
			this.txtReturn = new System.Windows.Forms.TextBox();
			this.Label1 = new System.Windows.Forms.Label();
			this.txtDeviceName = new System.Windows.Forms.TextBox();
			this.SuspendLayout();
			// 
			// txtTransCount
			// 
			this.txtTransCount.Location = new System.Drawing.Point(112, 243);
			this.txtTransCount.Name = "txtTransCount";
			this.txtTransCount.Size = new System.Drawing.Size(232, 20);
			this.txtTransCount.TabIndex = 59;
			this.txtTransCount.Text = "";
			// 
			// txtStatus
			// 
			this.txtStatus.Location = new System.Drawing.Point(112, 273);
			this.txtStatus.Name = "txtStatus";
			this.txtStatus.Size = new System.Drawing.Size(232, 20);
			this.txtStatus.TabIndex = 58;
			this.txtStatus.Text = "";
			// 
			// txtError
			// 
			this.txtError.Location = new System.Drawing.Point(112, 304);
			this.txtError.Name = "txtError";
			this.txtError.Size = new System.Drawing.Size(232, 20);
			this.txtError.TabIndex = 57;
			this.txtError.Text = "";
			// 
			// Label5
			// 
			this.Label5.Location = new System.Drawing.Point(16, 243);
			this.Label5.Name = "Label5";
			this.Label5.Size = new System.Drawing.Size(88, 19);
			this.Label5.TabIndex = 56;
			this.Label5.Text = "Transfer Count:";
			// 
			// Label4
			// 
			this.Label4.Location = new System.Drawing.Point(16, 273);
			this.Label4.Name = "Label4";
			this.Label4.Size = new System.Drawing.Size(88, 19);
			this.Label4.TabIndex = 55;
			this.Label4.Text = "Status:";
			// 
			// Label3
			// 
			this.Label3.Location = new System.Drawing.Point(16, 304);
			this.Label3.Name = "Label3";
			this.Label3.Size = new System.Drawing.Size(88, 18);
			this.Label3.TabIndex = 54;
			this.Label3.Text = "Error:";
			// 
			// Label2
			// 
			this.Label2.Location = new System.Drawing.Point(16, 334);
			this.Label2.Name = "Label2";
			this.Label2.Size = new System.Drawing.Size(88, 18);
			this.Label2.TabIndex = 53;
			this.Label2.Text = "Return Value:";
			// 
			// btnExit
			// 
			this.btnExit.Location = new System.Drawing.Point(384, 357);
			this.btnExit.Name = "btnExit";
			this.btnExit.Size = new System.Drawing.Size(104, 30);
			this.btnExit.TabIndex = 52;
			this.btnExit.Text = "Exit";
			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
			// 
			// btnCntExit
			// 
			this.btnCntExit.Location = new System.Drawing.Point(384, 320);
			this.btnCntExit.Name = "btnCntExit";
			this.btnCntExit.Size = new System.Drawing.Size(104, 30);
			this.btnCntExit.TabIndex = 51;
			this.btnCntExit.Text = "CntExit";
			this.btnCntExit.Click += new System.EventHandler(this.btnCntExit_Click);
			// 
			// btnStatus
			// 
			this.btnStatus.Location = new System.Drawing.Point(384, 282);
			this.btnStatus.Name = "btnStatus";
			this.btnStatus.Size = new System.Drawing.Size(104, 30);
			this.btnStatus.TabIndex = 50;
			this.btnStatus.Text = "Status";
			this.btnStatus.Click += new System.EventHandler(this.btnStatus_Click);
			// 
			// btnCount
			// 
			this.btnCount.Location = new System.Drawing.Point(384, 243);
			this.btnCount.Name = "btnCount";
			this.btnCount.Size = new System.Drawing.Size(104, 30);
			this.btnCount.TabIndex = 49;
			this.btnCount.Text = "Count";
			this.btnCount.Click += new System.EventHandler(this.btnCount_Click);
			// 
			// btnData
			// 
			this.btnData.Location = new System.Drawing.Point(384, 202);
			this.btnData.Name = "btnData";
			this.btnData.Size = new System.Drawing.Size(104, 33);
			this.btnData.TabIndex = 48;
			this.btnData.Text = "Data...";
			this.btnData.Click += new System.EventHandler(this.btnData_Click);
			// 
			// btnStop
			// 
			this.btnStop.Location = new System.Drawing.Point(384, 164);
			this.btnStop.Name = "btnStop";
			this.btnStop.Size = new System.Drawing.Size(104, 30);
			this.btnStop.TabIndex = 47;
			this.btnStop.Text = "Stop";
			this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
			// 
			// btnStart
			// 
			this.btnStart.Location = new System.Drawing.Point(384, 124);
			this.btnStart.Name = "btnStart";
			this.btnStart.Size = new System.Drawing.Size(104, 31);
			this.btnStart.TabIndex = 46;
			this.btnStart.Text = "Start";
			this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
			// 
			// btnCondition
			// 
			this.btnCondition.Location = new System.Drawing.Point(384, 86);
			this.btnCondition.Name = "btnCondition";
			this.btnCondition.Size = new System.Drawing.Size(104, 30);
			this.btnCondition.TabIndex = 45;
			this.btnCondition.Text = "Condition...";
			this.btnCondition.Click += new System.EventHandler(this.btnCondition_Click);
			// 
			// btnMode
			// 
			this.btnMode.Location = new System.Drawing.Point(384, 48);
			this.btnMode.Name = "btnMode";
			this.btnMode.Size = new System.Drawing.Size(104, 30);
			this.btnMode.TabIndex = 44;
			this.btnMode.Text = "Counter Mode...";
			this.btnMode.Click += new System.EventHandler(this.btnMode_Click);
			// 
			// btnCntInit
			// 
			this.btnCntInit.Location = new System.Drawing.Point(384, 10);
			this.btnCntInit.Name = "btnCntInit";
			this.btnCntInit.Size = new System.Drawing.Size(104, 31);
			this.btnCntInit.TabIndex = 43;
			this.btnCntInit.Text = "CntInit";
			this.btnCntInit.Click += new System.EventHandler(this.btnCntInit_Click);
			// 
			// txtReturn
			// 
			this.txtReturn.Location = new System.Drawing.Point(112, 334);
			this.txtReturn.Name = "txtReturn";
			this.txtReturn.Size = new System.Drawing.Size(232, 20);
			this.txtReturn.TabIndex = 42;
			this.txtReturn.Text = "";
			// 
			// Label1
			// 
			this.Label1.Location = new System.Drawing.Point(16, 20);
			this.Label1.Name = "Label1";
			this.Label1.Size = new System.Drawing.Size(88, 18);
			this.Label1.TabIndex = 41;
			this.Label1.Text = "Device Name:";
			// 
			// txtDeviceName
			// 
			this.txtDeviceName.Location = new System.Drawing.Point(112, 20);
			this.txtDeviceName.Name = "txtDeviceName";
			this.txtDeviceName.Size = new System.Drawing.Size(128, 20);
			this.txtDeviceName.TabIndex = 40;
			this.txtDeviceName.Text = "TextBox1";
			// 
			// Infinite
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(504, 397);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.txtTransCount,
																		  this.txtStatus,
																		  this.txtError,
																		  this.Label5,
																		  this.Label4,
																		  this.Label3,
																		  this.Label2,
																		  this.btnExit,
																		  this.btnCntExit,
																		  this.btnStatus,
																		  this.btnCount,
																		  this.btnData,
																		  this.btnStop,
																		  this.btnStart,
																		  this.btnCondition,
																		  this.btnMode,
																		  this.btnCntInit,
																		  this.txtReturn,
																		  this.Label1,
																		  this.txtDeviceName});
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "Infinite";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Infinite Sampling";
			this.Load += new System.EventHandler(this.Infinite_Load);
			this.ResumeLayout(false);

		}
		#endregion

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

		//===================================================
		//	Dialog initialization
		//===================================================
		private void Infinite_Load(object sender, System.EventArgs e)
		{
		
			//-----------------------------------
			//	Initialize dialog display
			//-----------------------------------
			txtDeviceName.Text="CNT000";

			//-----------------------------------
            // Specify Pinned handle to SamplingData
            //-----------------------------------
			if (gCh.IsAllocated == false)
			{
				gCh = GCHandle.Alloc(SamplingData, GCHandleType.Pinned);
			}
		}

		//===================================================
		//	CntInit()
		//===================================================
		private void btnCntInit_Click(object sender, System.EventArgs e)
		{
			string	str;
			string	buf= new string (' ',100);
			string  error_string=new string (' ',256);
			int  	ret;
	
			//-----------------------------------
			//	Get device name
			//-----------------------------------
			buf=txtDeviceName.Text;
			//-----------------------------------
			//	Initialization
			//-----------------------------------
			ret	= cnt.Init(buf,  out Id);
			cnt.GetErrorString(ret, out error_string);
			str = string.Format("CntInit ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
		}

		//---------------------------------------------
		// Display Counter Mode Setting dialog
		//---------------------------------------------
		private void btnMode_Click(object sender, System.EventArgs e)
		{
			//------------------------------
			// Display Counter Mode Setting dialog
			//------------------------------
			frmMode	dlg = new frmMode();
			dlg.ShowDialog();
			dlg.Dispose();
		}

		//===================================================
		//	Condition Setting
		//===================================================
		private void btnCondition_Click(object sender, System.EventArgs e)
		{
			//-----------------------------------
			//	Display Condition Setting dialog
			//-----------------------------------
			frmCondition dlg = new frmCondition();
			dlg.ShowDialog();
			dlg.Dispose();
		}

		//===================================================
		//	Start transfer
		//===================================================
		private void btnStart_Click(object sender, System.EventArgs e)
		{
			short[]	ChNo = new short[CHANNEL_NUM];
			short	i;
			string	str;
			string	error_string = new string(' ', 256);
			int		ret;


			//-----------------------------------
			// Set message notification
			//-----------------------------------
			ret = cnt.NotifySamplingStop(Id, this.Handle);
			if (ret != (uint)CcntConst.CNT_ERR_SUCCESS) 
			{
				cnt.GetErrorString(ret, out error_string);
				str = string.Format("CntNotifySamplingStop ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			ret = cnt.NotifySamplingCount(Id, NumberOfData, this.Handle);
			if (ret != (uint)CcntConst.CNT_ERR_SUCCESS) 
			{
				cnt.GetErrorString(ret, out error_string);
				str = string.Format("CntNotifySamplingCount ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//-----------------------------------
			//	Reset FIFO (Input)
			//-----------------------------------
			ret	= cnt.SamplingFifoReset(Id);
			if(ret != (uint)CcntConst.CNT_ERR_SUCCESS)
			{
				cnt.GetErrorString(ret, out error_string);
				str=string.Format("CntSamplingFifoReset ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//-----------------------------------
			//	Set data buffer
			//-----------------------------------
			Array.Clear(SamplingData, 0, SamplingData.Length);
			pSamplingData = gCh.AddrOfPinnedObject();
			ret = cnt.SamplingSetBuffer(Id, pSamplingData, CHANNEL_NUM, DATA_NUM, (short)CcntConst.CNTS_WRITE_RING);
			if(ret != (uint)CcntConst.CNT_ERR_SUCCESS)
			{
				cnt.GetErrorString(ret, out error_string);
				str = string.Format("CntSamplingSetBuffer ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//------------------------------
			// Set parameter
			//------------------------------
			for (i=0; i<CHANNEL_NUM; i++) 
			{
				ChNo[i] = i;
			}
			//------------------------------
			// Start count
			//------------------------------
			ret = cnt.StartCount(Id, ChNo, CHANNEL_NUM);
			if(ret != (uint)CcntConst.CNT_ERR_SUCCESS)
			{
				cnt.GetErrorString(ret, out error_string);
				str = string.Format("CntStartCount ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//-----------------------------------
			//	Initialize count
			//-----------------------------------
			ReadIndex	= 0;		// Read pointer
			WriteIndex	= 0;		// Write pointer
			PreCount	= 0;		// Previous transfer count
			PreCarry	= 0;		// Previous carry count
			//-----------------------------------
			//	Delete data file
			//-----------------------------------
			File.Delete(file_name);
			//-----------------------------------
			//	Start transfer
			//-----------------------------------
			ret = cnt.SamplingStart(Id);
			if(ret != (uint)CcntConst.CNT_ERR_SUCCESS)
			{
				cnt.GetErrorString(ret, out error_string);
				str = string.Format("CntSamplingStart ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			txtTransCount.Text = "";
			txtStatus.Text = "";
			txtError.Text = "";
			return;
		}

		//===================================================
		//	Stop transfer
		//===================================================
		private void btnStop_Click(object sender, System.EventArgs e)
		{
			string	error_string = new string(' ', 256);
			string	str;
			int	ret;

			//-----------------------------------
			//	Stop transfer
			//-----------------------------------
			ret = cnt.SamplingStop(Id);
			cnt.GetErrorString(ret, out error_string);
			str = string.Format("CntSamplingStop ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			return;
		}

		//===================================================
		//	Display data file
		//===================================================
		private void btnData_Click(object sender, System.EventArgs e)
		{
			//-----------------------------------
			// notepad
			//-----------------------------------
			Process Pro = Process.Start("notepad.exe", file_name);
			return;
		}

		//===================================================
		//	Transfer count
		//===================================================
		private void btnCount_Click(object sender, System.EventArgs e)
		{
			uint	count = 0, carry = 0;
			string	error_string = new string(' ', 256);
			string	str;
			int	ret;

			//-----------------------------------
			// Get transfer count
			//-----------------------------------
			ret = cnt.GetSamplingCount(Id, out count, out carry);
			cnt.GetErrorString(ret, out error_string);
			str = string.Format("CntGetSamplingCount ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			if( ret == (uint)CcntConst.CNT_ERR_SUCCESS)
			{
				str = string.Format("{0:d}", count);
				txtTransCount.Text = str;
			}
			return;
		}

		//===================================================
		//	Transfer status
		//===================================================
		private void btnStatus_Click(object sender, System.EventArgs e)
		{
			uint	status, err;
			string	error_string = new string(' ', 256);
			string	str;
			int  	ret;

			//-----------------------------------
			// Get transfer status
			//-----------------------------------
			ret = cnt.GetSamplingStatus(Id, out status, out err);
			cnt.GetErrorString(ret, out error_string);
			str = string.Format("CntGetSamplingStatus ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			if(ret != (uint)CcntConst.CNT_ERR_SUCCESS)
			{
				return;
			}
	
			// Status
			str = "";
			if ((status & (short)CcntConst.CNTS_STATUS_BMSTOP) !=0)
			{
				str += "BmStop,";
			}
			if ((status & (short)CcntConst.CNTS_STATUS_CNTSTART) != 0)
			{
				str += "CntStart,";
			}
			if ((status & (short)CcntConst.CNTS_STATUS_CNTSTOP) != 0)
			{
				str += "CntStop,";
			}
			if ((status & (short)CcntConst.CNTS_STATUS_TRGIN) != 0)
			{
				str += "TrgIn,";
			}
			if ((status & (short)CcntConst.CNTS_STATUS_OVERRUN) != 0)
			{
				str += "Overrun";
			}
			txtStatus.Text = str;
			// Error
			str = "";
			if ((err & (short)CcntConst.CNTS_STATUS_FIFOFULL) != 0)
			{
				str += "FifoFull,";
			}
			if ((err & (short)CcntConst.CNTS_STATUS_SGOVERIN) != 0)
			{
				str += "S/GOverIn,";
			}
			if ((err & (short)CcntConst.CNTS_STATUS_TRGERR) != 0)
			{
				str += "TrgErr,";
			}
			if ((err & (short)CcntConst.CNTS_STATUS_CLKERR) != 0)
			{
				str += "ClkErr,";
			}
			if ((err & (short)CcntConst.CNTS_STATUS_SLAVEHALT) != 0)
			{
				str += "SlaveHalt,";
			}
			if ((err & (short)CcntConst.CNTS_STATUS_MASTERHALT) != 0)
			{
				str += "MasterHalt";
			}

			txtError.Text = str;		
		}

		//===================================================
		//	CntExit
		//===================================================
		private void btnCntExit_Click(object sender, System.EventArgs e)
		{
			string	error_string = new string(' ', 256);
			string	str;
			int  	ret;
	
			//-----------------------------------
			// CntExit
			//-----------------------------------
			ret = cnt.Exit(Id);
			cnt.GetErrorString(ret, out error_string);
			str = string.Format("CntExit ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
		}

		//===================================================
		//	Exit
		//===================================================
		private void btnExit_Click(object sender, System.EventArgs e)
		{

			//-----------------------------------
            // Free GCHandle
            //-----------------------------------
			if (gCh.IsAllocated == true)
			{
				gCh.Free();
			}	
			this.Close();
		}

		//===================================================
		// Counter Event notification processing
		//===================================================
		protected override void WndProc(ref Message m)
		{
			int	        ret;
			uint	    count, carry;
			uint	    data_count, ch_no, Cnt;
			TextWriter  fp;
			string	    buf = new string(' ', 100);
			string	    str;

			switch( m.Msg ) 
			{
				case (short)CcntConst.CNTM_SAMPLING_COUNT:	// Specified number transfer completion
					//-----------------------------------
					// Retrieve transfer position on data buffer
					//-----------------------------------
					ret = cnt.GetSamplingWritePointer(Id, out WriteIndex, out count, out carry);
					//-----------------------------------
					// Check overflow error
					//-----------------------------------
					if (carry == PreCarry)
					{
						if (count > (PreCount + DATA_NUM)) 
						{
							str = string.Format("Overrun Error!(count = {0:d})", count);
							txtError.Text = str;
							return;
						}
					}
					//-----------------------------------
					// If count value is same as previous, exit current operation
					//	(When it was called from the transfer completion message)
					//-----------------------------------
					if ((count == PreCount) && (carry == PreCarry))
					{
						return;
					}
					//-----------------------------------
					// Write transferred data to file
					//-----------------------------------
					//-----------------------------------
					// Open file
					//-----------------------------------
					try
					{
						fp = File.AppendText(file_name);
					}
					catch (System.IO.IOException)
					{
						txtReturn.Text = "fopen : file open error.";
						return;
					}
					//-----------------------------------
					// Write data
					//-----------------------------------
					if (WriteIndex > ReadIndex)
					{
						Cnt = count - (WriteIndex - ReadIndex);
						for (data_count = ReadIndex; data_count < WriteIndex; data_count++)
						{
							buf = string.Format("{0:d8}: , ", Cnt);
							for( ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++ )
							{
								buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count,ch_no]);
							}
							buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count,ch_no]);
							fp.WriteLine(buf); 

							Cnt++;
						}
					}
					else
					{
						Cnt = count - (DATA_NUM - ReadIndex + WriteIndex);
						for (data_count = ReadIndex; data_count < DATA_NUM; data_count++)
						{
							buf = string.Format("{0:d8} , ", Cnt);
							for( ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++ )
							{
								buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count,ch_no]);

							}
							buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count,ch_no]);
							fp.WriteLine(buf); 

							Cnt++;
						}
						for (data_count = 0; data_count < WriteIndex; data_count++)
						{
							buf = string.Format("{0:d8} , ", Cnt);
							for( ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++ )
							{
								buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count,ch_no]);
							}
							buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count,ch_no]);
							fp.WriteLine(buf);

							Cnt++;
						}
					}
					//-----------------------------------
					// Close file
					//-----------------------------------
					fp.Close();
					//-----------------------------------
					// Set read pointer
					//-----------------------------------
					ReadIndex	= WriteIndex;
					PreCount	= count;
					PreCarry	= carry;
					//-----------------------------------
					// Display transfer count value
					//-----------------------------------
					str = string.Format("{0:d}", count);
					txtTransCount.Text = str;
					break;

				case (short)CcntConst.CNTM_SAMPLING_STOP:	// Transfer completion
					txtStatus.Text = "Stopped!";
					//-----------------------------------
					// Retrieve transfer position on data buffer
					//-----------------------------------
					ret = cnt.GetSamplingWritePointer(Id, out WriteIndex, out count, out carry);
					//-----------------------------------
					// Check overflow error
					//-----------------------------------
					if (carry == PreCarry)
					{
						if (count > (PreCount + DATA_NUM)) 
						{
							str = string.Format("Overrun Error!(count = {0:d})", count);
							txtError.Text = str;
							return;
						}
					}
					//-----------------------------------
					// If count value is same as previous, exit current operation
					//  (In case of called from transfer completion message)
					//-----------------------------------
					if ((count == PreCount) && (carry == PreCarry))
					{
						return;
					}
					//-----------------------------------
					// Write transferred data to file
					//-----------------------------------
					//-----------------------------------
					// Open file
					//-----------------------------------
					try
					{
						fp = File.AppendText(file_name);
					}
					catch (System.IO.IOException)
					{
						txtReturn.Text = "fopen : file open error.";
						return;
					}
					//-----------------------------------
					// Write data
					//-----------------------------------
					if (WriteIndex > ReadIndex)
					{
						Cnt = count - (WriteIndex - ReadIndex);
						for (data_count = ReadIndex; data_count < WriteIndex; data_count++)
						{
							buf = string.Format("{0:d8}: , ", Cnt);
							for( ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++ )
							{
								buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count,ch_no]);
							}
							buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count,ch_no]);
							fp.WriteLine(buf); 

							Cnt++;
						}
					}
					else
					{
						Cnt = count - (DATA_NUM - ReadIndex + WriteIndex);
						for (data_count = ReadIndex; data_count < DATA_NUM; data_count++)
						{
							buf = string.Format("{0:d8} , ", Cnt);
							for( ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++ )
							{
								buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count,ch_no]);
							}
							buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count,ch_no]);
							fp.WriteLine(buf); 

							Cnt++;
						}
						for (data_count = 0; data_count < WriteIndex; data_count++)
						{
							buf = string.Format("{0:d8} , ", Cnt);
							for( ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++ )
							{
								buf = string.Format("{0}{1:X8}, ", buf, SamplingData[data_count,ch_no]);
							}
							buf = string.Format("{0}{1:X8}", buf, SamplingData[data_count,ch_no]);
							fp.WriteLine(buf);

							Cnt++;
						}
					}
					//-----------------------------------
					// Close file
					//-----------------------------------
					fp.Close();
					//-----------------------------------
					// Set read pointer
					//-----------------------------------
					ReadIndex	= WriteIndex;
					PreCount	= count;
					PreCarry	= carry;
					//-----------------------------------
					// Display transf counter value
					//-----------------------------------
					str = string.Format("{0:d}", count);
					txtTransCount.Text = str;
					break;
			}
			base.WndProc(ref m);
		}
	}
}
