﻿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;
using CdioCs;

namespace Infinite
{
	/// <summary>
	/// Summary description for Infinite.
	/// </summary>
	public class Infinite : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button btnData;
		private System.Windows.Forms.Button btnCount;
		private System.Windows.Forms.TextBox txtReturn;
		private System.Windows.Forms.TextBox txtError;
		private System.Windows.Forms.TextBox txtStatus;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.TextBox txtCount;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox txtDeviceName;
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.Button btnExit;
		private System.Windows.Forms.Button btnDioExit;
		private System.Windows.Forms.Button btnStatus;
		private System.Windows.Forms.Button btnStop;
		private System.Windows.Forms.Button btnStart;
		private System.Windows.Forms.Button btnCondition;
		private System.Windows.Forms.Button btnDioInit;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		delegate void SetTextDelegate(string str);

		Cdio				dio = new Cdio();
		const int			DATA_SIZE = 1000;				// Buffer size for busmaster
		public static short	Id;								// Device ID
		static uint[]		BmBuffer = new uint[DATA_SIZE];	// Buffer for busmaster
		static uint			ReadIndex;						// Read pointer
		static uint			WriteIndex;						// Write pointer 
		static uint			PreCount;						// Pre-count 
		static uint			PreCarry;						// Pre-carrycount 
		static string		file_name = "infinite.csv";		// Data file name
		GCHandle			gCh;
		IntPtr				pBmBuf;

		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.btnData = new System.Windows.Forms.Button();
			this.btnCount = new System.Windows.Forms.Button();
			this.txtReturn = new System.Windows.Forms.TextBox();
			this.txtError = new System.Windows.Forms.TextBox();
			this.txtStatus = 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.txtCount = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.txtDeviceName = new System.Windows.Forms.TextBox();
			this.label6 = new System.Windows.Forms.Label();
			this.btnExit = new System.Windows.Forms.Button();
			this.btnDioExit = new System.Windows.Forms.Button();
			this.btnStatus = 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.btnDioInit = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// btnData
			// 
			this.btnData.Location = new System.Drawing.Point(358, 147);
			this.btnData.Name = "btnData";
			this.btnData.Size = new System.Drawing.Size(96, 26);
			this.btnData.TabIndex = 9;
			this.btnData.Text = "Get Data...";
			this.btnData.Click += new System.EventHandler(this.btnData_Click);
			// 
			// btnCount
			// 
			this.btnCount.Location = new System.Drawing.Point(358, 182);
			this.btnCount.Name = "btnCount";
			this.btnCount.Size = new System.Drawing.Size(96, 26);
			this.btnCount.TabIndex = 10;
			this.btnCount.Text = "Transfer Count";
			this.btnCount.Click += new System.EventHandler(this.btnCount_Click);
			// 
			// txtReturn
			// 
			this.txtReturn.Location = new System.Drawing.Point(102, 289);
			this.txtReturn.Name = "txtReturn";
			this.txtReturn.Size = new System.Drawing.Size(232, 20);
			this.txtReturn.TabIndex = 4;
			this.txtReturn.Text = "";
			// 
			// txtError
			// 
			this.txtError.Location = new System.Drawing.Point(102, 254);
			this.txtError.Name = "txtError";
			this.txtError.Size = new System.Drawing.Size(232, 20);
			this.txtError.TabIndex = 3;
			this.txtError.Text = "";
			// 
			// txtStatus
			// 
			this.txtStatus.Location = new System.Drawing.Point(102, 220);
			this.txtStatus.Name = "txtStatus";
			this.txtStatus.Size = new System.Drawing.Size(232, 20);
			this.txtStatus.TabIndex = 2;
			this.txtStatus.Text = "";
			// 
			// label5
			// 
			this.label5.Location = new System.Drawing.Point(14, 290);
			this.label5.Name = "label5";
			this.label5.Size = new System.Drawing.Size(72, 19);
			this.label5.TabIndex = 73;
			this.label5.Text = "Return Code:";
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(14, 256);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(72, 18);
			this.label4.TabIndex = 72;
			this.label4.Text = "Error:";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(14, 221);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(72, 18);
			this.label3.TabIndex = 71;
			this.label3.Text = "Status:";
			// 
			// txtCount
			// 
			this.txtCount.Location = new System.Drawing.Point(102, 185);
			this.txtCount.Name = "txtCount";
			this.txtCount.Size = new System.Drawing.Size(232, 20);
			this.txtCount.TabIndex = 1;
			this.txtCount.Text = "";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(14, 186);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(90, 18);
			this.label2.TabIndex = 70;
			this.label2.Text = "Transfer Count:";
			// 
			// txtDeviceName
			// 
			this.txtDeviceName.Location = new System.Drawing.Point(102, 10);
			this.txtDeviceName.Name = "txtDeviceName";
			this.txtDeviceName.Size = new System.Drawing.Size(96, 20);
			this.txtDeviceName.TabIndex = 0;
			this.txtDeviceName.Text = "";
			// 
			// label6
			// 
			this.label6.Location = new System.Drawing.Point(14, 11);
			this.label6.Name = "label6";
			this.label6.Size = new System.Drawing.Size(82, 19);
			this.label6.TabIndex = 69;
			this.label6.Text = "Device Name:";
			// 
			// btnExit
			// 
			this.btnExit.Location = new System.Drawing.Point(358, 287);
			this.btnExit.Name = "btnExit";
			this.btnExit.Size = new System.Drawing.Size(96, 26);
			this.btnExit.TabIndex = 13;
			this.btnExit.Text = "Exit";
			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
			// 
			// btnDioExit
			// 
			this.btnDioExit.Location = new System.Drawing.Point(358, 252);
			this.btnDioExit.Name = "btnDioExit";
			this.btnDioExit.Size = new System.Drawing.Size(96, 26);
			this.btnDioExit.TabIndex = 12;
			this.btnDioExit.Text = "DioExit";
			this.btnDioExit.Click += new System.EventHandler(this.btnDioExit_Click);
			// 
			// btnStatus
			// 
			this.btnStatus.Location = new System.Drawing.Point(358, 217);
			this.btnStatus.Name = "btnStatus";
			this.btnStatus.Size = new System.Drawing.Size(96, 26);
			this.btnStatus.TabIndex = 11;
			this.btnStatus.Text = "Transfer Status";
			this.btnStatus.Click += new System.EventHandler(this.btnStatus_Click);
			// 
			// btnStop
			// 
			this.btnStop.Location = new System.Drawing.Point(358, 112);
			this.btnStop.Name = "btnStop";
			this.btnStop.Size = new System.Drawing.Size(96, 26);
			this.btnStop.TabIndex = 8;
			this.btnStop.Text = "Stop Transfer";
			this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
			// 
			// btnStart
			// 
			this.btnStart.Location = new System.Drawing.Point(358, 78);
			this.btnStart.Name = "btnStart";
			this.btnStart.Size = new System.Drawing.Size(96, 25);
			this.btnStart.TabIndex = 7;
			this.btnStart.Text = "Start Transfer";
			this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
			// 
			// btnCondition
			// 
			this.btnCondition.Location = new System.Drawing.Point(358, 43);
			this.btnCondition.Name = "btnCondition";
			this.btnCondition.Size = new System.Drawing.Size(96, 25);
			this.btnCondition.TabIndex = 6;
			this.btnCondition.Text = "Set Conditions...";
			this.btnCondition.Click += new System.EventHandler(this.btnCondition_Click);
			// 
			// btnDioInit
			// 
			this.btnDioInit.Location = new System.Drawing.Point(358, 8);
			this.btnDioInit.Name = "btnDioInit";
			this.btnDioInit.Size = new System.Drawing.Size(96, 25);
			this.btnDioInit.TabIndex = 5;
			this.btnDioInit.Text = "DioInit";
			this.btnDioInit.Click += new System.EventHandler(this.btnDioInit_Click);
			// 
			// Infinite
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(464, 321);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.btnData,
																		  this.btnCount,
																		  this.txtReturn,
																		  this.txtError,
																		  this.txtStatus,
																		  this.label5,
																		  this.label4,
																		  this.label3,
																		  this.txtCount,
																		  this.label2,
																		  this.txtDeviceName,
																		  this.label6,
																		  this.btnExit,
																		  this.btnDioExit,
																		  this.btnStatus,
																		  this.btnStop,
																		  this.btnStart,
																		  this.btnCondition,
																		  this.btnDioInit});
			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.Closed += new System.EventHandler(this.Infinite_Closed);
			this.ResumeLayout(false);

		}
		#endregion

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

		//===================================================
		//	Dialog init
		//===================================================
		unsafe private void Infinite_Load(object sender, System.EventArgs e)
		{
			//-----------------------------------
			// Dialog init
			//-----------------------------------
			txtDeviceName.Text = "DIO000";

			//-----------------------------------
			// Pinned type handle is allocated to BmBuffer
			//-----------------------------------
			if (gCh.IsAllocated == false)
			{
				gCh = GCHandle.Alloc(BmBuffer, GCHandleType.Pinned);
			}
		}

		//===================================================
		//	Close handle
		//===================================================
		private void Infinite_Closed(object sender, System.EventArgs e)
		{
			int	ret;

			//-----------------------------------
			// DioExit()
			//-----------------------------------
			ret	= dio.Exit(Id);

			//-----------------------------------
			// GCHandle is freed
			//-----------------------------------
			if (gCh.IsAllocated == true)
			{
				gCh.Free();
			}
		}

		//===================================================
		//	DioInit()
		//===================================================
		private void btnDioInit_Click(object sender, System.EventArgs e)
		{
			string	str;
			string	error_string = new string(' ', 256);
			int		ret;
	
			//-----------------------------------
			// DioInit
			//-----------------------------------
			ret	= dio.Init(txtDeviceName.Text, out Id);
			dio.GetErrorString(ret, out error_string);
			str = string.Format("DioInit ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			return;
		}

		//===================================================
		//	Set condition
		//===================================================
		private void btnCondition_Click(object sender, System.EventArgs e)
		{
			Condition	ConditionDlg = new Condition();
			//-----------------------------------
			// Show set condition dialog
			//-----------------------------------
			ConditionDlg.ShowDialog();
			ConditionDlg.Dispose();
			return;
		}

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

			//-----------------------------------
			// Set notification of message
			//-----------------------------------
			ret = dio.DmSetStopEvent(Id, (short)CdioConst.DIODM_DIR_IN, this.Handle);
			if (ret != (int)CdioConst.DIO_ERR_SUCCESS) 
			{
				dio.GetErrorString(ret, out error_string);
				str = string.Format("DioDmSetStopEvent ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			ret = dio.DmSetCountEvent(Id, (short)CdioConst.DIODM_DIR_IN, Condition.NumberOfData, this.Handle);
			if (ret != (int)CdioConst.DIO_ERR_SUCCESS) 
			{
				dio.GetErrorString(ret, out error_string);
				str = string.Format("DioDmSetCountEvent ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//-----------------------------------
			// Reset FIFO (input)
			//-----------------------------------
			ret	= dio.DmFifoReset(Id, (short)CdioConst.DIODM_RESET_FIFO_IN);
			if(ret != (int)CdioConst.DIO_ERR_SUCCESS)
			{
				dio.GetErrorString(ret, out error_string);
				str = string.Format("DioDmFifoReset ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//-----------------------------------
			// Set data buffer
			//-----------------------------------
			Array.Clear(BmBuffer, 0, BmBuffer.Length);
			pBmBuf	= gCh.AddrOfPinnedObject();
			ret	= dio.DmSetBuffer(Id, (short)CdioConst.DIODM_DIR_IN, pBmBuf, DATA_SIZE, (short)CdioConst.DIODM_WRITE_RING);
			if(ret != (int)CdioConst.DIO_ERR_SUCCESS)
			{
				dio.GetErrorString(ret, out error_string);
				str = string.Format("DioDmSetBuffer ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			//-----------------------------------
			// Count init
			//-----------------------------------
			ReadIndex	= 0;		// Read pointer
			WriteIndex	= 0;		// Write pointer 
			PreCount	= 0;		// Pre-count 
			PreCarry	= 0;		// Pre-carrycount 
			//-----------------------------------
			//Remove data file
			//-----------------------------------
			File.Delete(file_name);
			//-----------------------------------
			// Start transfer
			//-----------------------------------
			ret = dio.DmTransferStart(Id, (short)CdioConst.DIODM_DIR_IN);
			if(ret != (int)CdioConst.DIO_ERR_SUCCESS)
			{
				dio.GetErrorString(ret, out error_string);
				str = string.Format("DioDmTransferStart ret = {0:d}: {1}", ret, error_string);
				txtReturn.Text = str;
				return;
			}
			txtCount.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 = dio.DmTransferStop(Id, (short)CdioConst.DIODM_DIR_IN);
			dio.GetErrorString(ret, out error_string);
			str = string.Format("DioDmTransferStop ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			return;
		}

		//===================================================
		//	Get data
		//===================================================
		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 = dio.DmGetCount(Id, (short)CdioConst.DIODM_DIR_IN, out count, out carry);
			dio.GetErrorString(ret, out error_string);
			str = string.Format("DioDmGetCount ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text  = str;
			if( ret == (int)CdioConst.DIO_ERR_SUCCESS)
			{
				str = string.Format("{0:d}", count);
				txtCount.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 = dio.DmGetStatus(Id, (short)CdioConst.DIODM_DIR_IN, out status, out err);
			dio.GetErrorString(ret, out error_string);
			str = string.Format("DioDmGetStatus ret = {0:d}: {1}", ret, error_string);
			txtReturn.Text = str;
			if(ret != (int)CdioConst.DIO_ERR_SUCCESS)
			{
				return;
			}
			// Status
			str = "";
			if ((status & (uint)CdioConst.DIODM_STATUS_BMSTOP) != 0)	str += "BmStop,";
			if ((status & (uint)CdioConst.DIODM_STATUS_PIOSTART) != 0)	str += "PioStart,";
			if ((status & (uint)CdioConst.DIODM_STATUS_PIOSTOP) != 0)	str += "PioStop,";
			if ((status & (uint)CdioConst.DIODM_STATUS_TRGIN) != 0)		str += "TrgIn,";
			if ((status & (uint)CdioConst.DIODM_STATUS_OVERRUN) != 0)	str += "Overrun";
			txtStatus.Text = str;
			// Error
			str = "";
			if ((err & (uint)CdioConst.DIODM_STATUS_FIFOEMPTY) != 0) 	str += "FifoEmpty,";
			if ((err & (uint)CdioConst.DIODM_STATUS_FIFOFULL) != 0)		str += "FifoFull,";
			if ((err & (uint)CdioConst.DIODM_STATUS_SGOVERIN) != 0)		str += "S/GOverIn,";
			if ((err & (uint)CdioConst.DIODM_STATUS_TRGERR) != 0)		str += "TrgErr,";
			if ((err & (uint)CdioConst.DIODM_STATUS_CLKERR) != 0)		str += "ClkErr,";
			if ((err & (uint)CdioConst.DIODM_STATUS_SLAVEHALT) != 0)	str += "SlaveHalt,";
			if ((err & (uint)CdioConst.DIODM_STATUS_MASTERHALT) != 0)	str += "MasterHalt";
			txtError.Text = str;
			return;
		}

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

		//===================================================
		//	Exit
		//===================================================
		private void btnExit_Click(object sender, System.EventArgs e)
		{
			//-----------------------------------
			// Release GCHandle
			//-----------------------------------
			if(gCh.IsAllocated == false)
			{
				gCh	= GCHandle.Alloc(BmBuffer, GCHandleType.Pinned);
			}
			this.Close();
		}

		//===================================================
		// Synchronization function for control operation
		//===================================================
		void SetCountText(string str)
		{
			txtCount.Text	= str;
		}
		void SetStatusText(string str)
		{
			txtStatus.Text	= str;
		}
		void SetErrText(string str)
		{
			txtError.Text	= str;
		}

		//===================================================
		// Messange handler
		//===================================================
		protected override void WndProc(ref Message m)
		{
			StreamWriter fp;
			string       buf = new string(' ', 100);
			string       str;
			uint         count, carry;
			uint         i, cnt;
			int          ret;

			switch (m.Msg)
			{
				//---------------------------------------------------
				// Transfer specified number of data completion message
				//---------------------------------------------------
				case ((int)CdioConst.DIO_DMM_COUNT):
					//-----------------------------------
					// Get the transfer position on the data buffer
					//-----------------------------------
					ret = dio.DmGetWritePointer(Id, (short)CdioConst.DIODM_DIR_IN, out WriteIndex, out count, out carry);
					//-----------------------------------
					// Check overrun error
					//-----------------------------------
					if (carry == PreCarry)
					{
						if (count > (PreCount + DATA_SIZE))
						{
							str = string.Format("Overrun Error!(count = {0:d})", count);
							txtError.Text = str;
							return;
						}
					}
					//-----------------------------------
					// If count is same as the precount,then return 
					// (In the case of being called from transfer stop message)
					//-----------------------------------
					if ((count == PreCount) && (carry == PreCarry))
					{
						return;
					}
					//-----------------------------------
					// Write transferred data into file
					//-----------------------------------
					//-----------------------------------
					// Open file
					//-----------------------------------
					fp = File.AppendText(file_name);
					//-----------------------------------
					// Write file
					//-----------------------------------
					if (WriteIndex > ReadIndex)
					{
						cnt = count - (WriteIndex - ReadIndex);
						for (i = ReadIndex; i < WriteIndex; i++)
						{
							buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
							fp.WriteLine(buf);
							cnt++;
						}
					}
					else
					{
						cnt = count - (DATA_SIZE - ReadIndex + WriteIndex);
						for (i = ReadIndex; i < DATA_SIZE; i++)
						{
							buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
							fp.WriteLine(buf);
							cnt++;
						}
						for (i = 0; i < WriteIndex; i++)
						{
							buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
							fp.WriteLine(buf);
							cnt++;
						}
					}
					//-----------------------------------
					// Close file
					//-----------------------------------
					fp.Close();
					//-----------------------------------
					// Set read pointer
					//-----------------------------------
					ReadIndex = WriteIndex;
					PreCount  = count;
					PreCarry  = carry;
					//-----------------------------------
					// Display transfer count
					//-----------------------------------
					str = string.Format("{0:d}", count);
					txtCount.Text = str;
					break;
			    //---------------------------------------------------
			    // Transfer stop message
			    //---------------------------------------------------
			    case ((int)CdioConst.DIO_DMM_STOP):
					//-----------------------------------
					// Transfer stop message
					//-----------------------------------
					txtStatus.Text = "Stopped!";
					//-----------------------------------
					// Get write pointer
					//-----------------------------------
					ret = dio.DmGetWritePointer(Id, (short)CdioConst.DIODM_DIR_IN, out WriteIndex, out count, out carry);
					//-----------------------------------
					// Overrun error check
					//-----------------------------------
					if (carry == PreCarry)
					{
						if (count > (PreCount + DATA_SIZE))
						{
							str = string.Format("Overrun Error!(count = {0:d})", count);
							txtError.Text = str;
							return;
						}
					}
					//-----------------------------------
					// If count is same as the precount,then return 
					// (In the case of being called from transfer stop message)
					//-----------------------------------
					if ((count == PreCount) && (carry == PreCarry))
					{
						return;
					}
					//-----------------------------------
					// Write transferred data into file
					//-----------------------------------
					//-----------------------------------
					// Open file
					//-----------------------------------
					fp = File.AppendText(file_name);
					//-----------------------------------
					// Write file
					//-----------------------------------
					if (WriteIndex > ReadIndex)
					{
						cnt = count - (WriteIndex - ReadIndex);
						for (i = ReadIndex; i < WriteIndex; i++)
						{
							buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
							fp.WriteLine(buf);
							cnt++;
						}
					}
					else
					{
						cnt = count - (DATA_SIZE - ReadIndex + WriteIndex);
						for (i = ReadIndex; i < DATA_SIZE; i++)
						{
							buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
							fp.WriteLine(buf);
							cnt++;
						}
						for (i = 0; i < WriteIndex; i++)
						{
							buf = string.Format("{0:d8}:, {1:X8}", cnt, BmBuffer[i]);
							fp.WriteLine(buf);
							cnt++;
						}
					}
					//-----------------------------------
					// Close file
					//-----------------------------------
					fp.Close();
					//-----------------------------------
					// Set read pointer
					//-----------------------------------
					ReadIndex = WriteIndex;
					PreCount  = count;
					PreCarry  = carry;
					//-----------------------------------
					// Display transfer count
					//-----------------------------------
					str = string.Format("{0:d}", count);
					txtCount.Text = str;
					break;
			    default:
					break;
			}
			base.WndProc(ref m);
		}
	}
}