﻿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>
	/// Form1 の概要の説明です。
	/// </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>
		/// 必要なデザイナ変数です。
		/// </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]; // サンプリング用バッファ
		public static uint		ReadIndex;								          // リードポインタ
		public static uint		WriteIndex;								          // ライトポインタ
		public static long		PreCount;								          // 前回の転送カウント
		public static long		PreCarry;								          // 前回のキャリーカウント
		public static string	file_name = "infinite.csv";

		Ccnt					cnt			   = new Ccnt();

		GCHandle			    gCh;
		IntPtr				    pSamplingData;

		public Infinite()
		{
			//
			// Windows フォーム デザイナ サポートに必要です。
			//
			InitializeComponent();

			//
			// TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
			//
		}

		/// <summary>
		/// 使用されているリソースに後処理を実行します。
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
		/// コード エディタで変更しないでください。
		/// </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, 209);
			this.txtTransCount.Name = "txtTransCount";
			this.txtTransCount.Size = new System.Drawing.Size(232, 19);
			this.txtTransCount.TabIndex = 39;
			this.txtTransCount.Text = "";
			// 
			// txtStatus
			// 
			this.txtStatus.Location = new System.Drawing.Point(112, 235);
			this.txtStatus.Name = "txtStatus";
			this.txtStatus.Size = new System.Drawing.Size(232, 19);
			this.txtStatus.TabIndex = 38;
			this.txtStatus.Text = "";
			// 
			// txtError
			// 
			this.txtError.Location = new System.Drawing.Point(112, 261);
			this.txtError.Name = "txtError";
			this.txtError.Size = new System.Drawing.Size(232, 19);
			this.txtError.TabIndex = 37;
			this.txtError.Text = "";
			// 
			// Label5
			// 
			this.Label5.Location = new System.Drawing.Point(16, 209);
			this.Label5.Name = "Label5";
			this.Label5.Size = new System.Drawing.Size(88, 16);
			this.Label5.TabIndex = 36;
			this.Label5.Text = "転送カウント：";
			// 
			// Label4
			// 
			this.Label4.Location = new System.Drawing.Point(16, 235);
			this.Label4.Name = "Label4";
			this.Label4.Size = new System.Drawing.Size(88, 16);
			this.Label4.TabIndex = 35;
			this.Label4.Text = "ステータス：";
			// 
			// Label3
			// 
			this.Label3.Location = new System.Drawing.Point(16, 261);
			this.Label3.Name = "Label3";
			this.Label3.Size = new System.Drawing.Size(88, 16);
			this.Label3.TabIndex = 34;
			this.Label3.Text = "エラー：";
			// 
			// Label2
			// 
			this.Label2.Location = new System.Drawing.Point(16, 287);
			this.Label2.Name = "Label2";
			this.Label2.Size = new System.Drawing.Size(88, 16);
			this.Label2.TabIndex = 33;
			this.Label2.Text = "戻り値：";
			// 
			// btnExit
			// 
			this.btnExit.Location = new System.Drawing.Point(384, 307);
			this.btnExit.Name = "btnExit";
			this.btnExit.Size = new System.Drawing.Size(104, 26);
			this.btnExit.TabIndex = 32;
			this.btnExit.Text = "Exit";
			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
			// 
			// btnCntExit
			// 
			this.btnCntExit.Location = new System.Drawing.Point(384, 275);
			this.btnCntExit.Name = "btnCntExit";
			this.btnCntExit.Size = new System.Drawing.Size(104, 26);
			this.btnCntExit.TabIndex = 31;
			this.btnCntExit.Text = "CntExit";
			this.btnCntExit.Click += new System.EventHandler(this.btnCntExit_Click);
			// 
			// btnStatus
			// 
			this.btnStatus.Location = new System.Drawing.Point(384, 242);
			this.btnStatus.Name = "btnStatus";
			this.btnStatus.Size = new System.Drawing.Size(104, 26);
			this.btnStatus.TabIndex = 30;
			this.btnStatus.Text = "転送ステータス";
			this.btnStatus.Click += new System.EventHandler(this.btnStatus_Click);
			// 
			// btnCount
			// 
			this.btnCount.Location = new System.Drawing.Point(384, 209);
			this.btnCount.Name = "btnCount";
			this.btnCount.Size = new System.Drawing.Size(104, 26);
			this.btnCount.TabIndex = 29;
			this.btnCount.Text = "転送カウント";
			this.btnCount.Click += new System.EventHandler(this.btnCount_Click);
			// 
			// btnData
			// 
			this.btnData.Location = new System.Drawing.Point(384, 174);
			this.btnData.Name = "btnData";
			this.btnData.Size = new System.Drawing.Size(104, 28);
			this.btnData.TabIndex = 28;
			this.btnData.Text = "取得データ...";
			this.btnData.Click += new System.EventHandler(this.btnData_Click);
			// 
			// btnStop
			// 
			this.btnStop.Location = new System.Drawing.Point(384, 141);
			this.btnStop.Name = "btnStop";
			this.btnStop.Size = new System.Drawing.Size(104, 26);
			this.btnStop.TabIndex = 27;
			this.btnStop.Text = "転送ストップ";
			this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
			// 
			// btnStart
			// 
			this.btnStart.Location = new System.Drawing.Point(384, 107);
			this.btnStart.Name = "btnStart";
			this.btnStart.Size = new System.Drawing.Size(104, 26);
			this.btnStart.TabIndex = 26;
			this.btnStart.Text = "転送スタート";
			this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
			// 
			// btnCondition
			// 
			this.btnCondition.Location = new System.Drawing.Point(384, 74);
			this.btnCondition.Name = "btnCondition";
			this.btnCondition.Size = new System.Drawing.Size(104, 26);
			this.btnCondition.TabIndex = 25;
			this.btnCondition.Text = "条件設定...";
			this.btnCondition.Click += new System.EventHandler(this.btnCondition_Click);
			// 
			// btnMode
			// 
			this.btnMode.Location = new System.Drawing.Point(384, 41);
			this.btnMode.Name = "btnMode";
			this.btnMode.Size = new System.Drawing.Size(104, 26);
			this.btnMode.TabIndex = 24;
			this.btnMode.Text = "カウンタモード";
			this.btnMode.Click += new System.EventHandler(this.btnMode_Click);
			// 
			// btnCntInit
			// 
			this.btnCntInit.Location = new System.Drawing.Point(384, 9);
			this.btnCntInit.Name = "btnCntInit";
			this.btnCntInit.Size = new System.Drawing.Size(104, 26);
			this.btnCntInit.TabIndex = 23;
			this.btnCntInit.Text = "CntInit";
			this.btnCntInit.Click += new System.EventHandler(this.btnCntInit_Click);
			// 
			// txtReturn
			// 
			this.txtReturn.Location = new System.Drawing.Point(112, 287);
			this.txtReturn.Name = "txtReturn";
			this.txtReturn.Size = new System.Drawing.Size(232, 19);
			this.txtReturn.TabIndex = 22;
			this.txtReturn.Text = "";
			// 
			// Label1
			// 
			this.Label1.Location = new System.Drawing.Point(16, 17);
			this.Label1.Name = "Label1";
			this.Label1.Size = new System.Drawing.Size(64, 16);
			this.Label1.TabIndex = 21;
			this.Label1.Text = "デバイス名：";
			// 
			// txtDeviceName
			// 
			this.txtDeviceName.Location = new System.Drawing.Point(112, 17);
			this.txtDeviceName.Name = "txtDeviceName";
			this.txtDeviceName.Size = new System.Drawing.Size(128, 19);
			this.txtDeviceName.TabIndex = 20;
			this.txtDeviceName.Text = "TextBox1";
			// 
			// Infinite
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
			this.ClientSize = new System.Drawing.Size(504, 342);
			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 = "無限サンプリング";
			this.Load += new System.EventHandler(this.Infinite_Load);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// アプリケーションのメイン エントリ ポイントです。
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Infinite());
		}

		//===================================================
		//	ダイアログ初期化
		//===================================================
		private void Infinite_Load(object sender, System.EventArgs e)
		{
			//-----------------------------------
			//	画面表示の初期化
			//-----------------------------------
			txtDeviceName.Text="CNT000";

			//-----------------------------------
			// Pinnedハンドルを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;
	
			//-----------------------------------
			//	デバイス名取得
			//-----------------------------------
			buf=txtDeviceName.Text;
			//-----------------------------------
			//	初期化処理
			//-----------------------------------
			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;

		}

		//---------------------------------------------
		// カウンタモード設定画面表示
		//---------------------------------------------
		private void btnMode_Click(object sender, System.EventArgs e)
		{
			//------------------------------
			// カウンタモード設定画面表示
			//------------------------------
			frmMode	dlg = new frmMode();
			dlg.ShowDialog();
			dlg.Dispose();
		}

		//===================================================
		//	条件設定
		//===================================================
		private void btnCondition_Click(object sender, System.EventArgs e)
		{
			//-----------------------------------
			//	条件設定ダイアログを開く
			//-----------------------------------
			frmCondition dlg = new frmCondition();
			dlg.ShowDialog();
			dlg.Dispose();

		}

		//===================================================
		//	転送スタート
		//===================================================
		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;


			//-----------------------------------
			// メッセージ通知設定
			//-----------------------------------
			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;
			}
			//-----------------------------------
			//	FIFOのリセット(入力)
			//-----------------------------------
			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;
			}
			//-----------------------------------
			//	データバッファを設定
			//-----------------------------------
			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;
			}
			//------------------------------
			// パラメータのセット
			//------------------------------
			for (i=0; i<CHANNEL_NUM; i++) 
			{
				ChNo[i] = i;
			}
			//------------------------------
			// カウント開始処理
			//------------------------------
			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;
			}
			//-----------------------------------
			//	カウント初期化
			//-----------------------------------
			ReadIndex	= 0;		// リードポインタ
			WriteIndex	= 0;		// ライトポインタ
			PreCount	= 0;		// 前回の転送カウント
			PreCarry	= 0;		// 前回のキャリーカウント
			//-----------------------------------
			//	データファイル削除
			//-----------------------------------
			File.Delete(file_name);
			//-----------------------------------
			//	転送スタート
			//-----------------------------------
			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;
		}

		//===================================================
		//	転送ストップ
		//===================================================
		private void btnStop_Click(object sender, System.EventArgs e)
		{
			string	error_string = new string(' ', 256);
			string	str;
			int	ret;

			//-----------------------------------
			//	転送ストップ
			//-----------------------------------
			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;

		}

		//===================================================
		//	データファイル表示
		//===================================================
		private void btnData_Click(object sender, System.EventArgs e)
		{
			//-----------------------------------
			// notepad
			//-----------------------------------
			Process Pro = Process.Start("notepad.exe", file_name);
			return;

		}

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

			//-----------------------------------
			// 転送カウント取得
			//-----------------------------------
			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;

		}

		//===================================================
		//	転送ステータス
		//===================================================
		private void btnStatus_Click(object sender, System.EventArgs e)
		{
			uint	status, err;
			string	error_string = new string(' ', 256);
			string	str;
			int  	ret;

			//-----------------------------------
			// 転送ステータス取得
			//-----------------------------------
			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)
		{

			//-----------------------------------
			// GCHandleのフリー
			//-----------------------------------
			if (gCh.IsAllocated == true)
			{
				gCh.Free();
			}	

			this.Close();
		}

		//===================================================
		// カウンタ イベント通知処理
		//===================================================
		protected override void WndProc(ref Message m)
		{
			long	    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:	// 指定個数転送完了
					//-----------------------------------
					// データバッファ上における転送位置を取得
					//-----------------------------------
					ret = cnt.GetSamplingWritePointer(Id, out WriteIndex, out count, out carry);
					//-----------------------------------
					// オーバーランエラーをチェック
					//-----------------------------------
					if (carry == PreCarry)
					{
						if (count > (PreCount + DATA_NUM)) 
						{
							str = string.Format("Overrun Error!(count = {0:d})", count);
							txtError.Text = str;
							return;
						}
					}
					//-----------------------------------
					// 前回と同じカウント値であれば終了
					//	(転送完了メッセージから呼ばれた場合のため)
					//-----------------------------------
					if ((count == PreCount) && (carry == PreCarry))
					{
						return;
					}
					//-----------------------------------
					// ファイルに転送されたデータを書き込みます
					//-----------------------------------
					//-----------------------------------
					// ファイルを開く
					//-----------------------------------
					try
					{
						fp = File.AppendText(file_name);
					}
					catch (System.IO.IOException)
					{
						txtReturn.Text = "fopen : file open error.";
						return;
					}
					//-----------------------------------
					// データ書き込み
					//-----------------------------------
					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++;
						}
					}
					//-----------------------------------
					// ファイルを閉じる
					//-----------------------------------
					fp.Close();
					//-----------------------------------
					// リードポインタを設定
					//-----------------------------------
					ReadIndex	= WriteIndex;
					PreCount	= count;
					PreCarry	= carry;
					//-----------------------------------
					// 転送カウント値を表示
					//-----------------------------------
					str = string.Format("{0:d}", count);
					txtTransCount.Text = str;
					break;

				case (short)CcntConst.CNTM_SAMPLING_STOP:	// 転送完了
					txtStatus.Text = "Stopped!";
					//-----------------------------------
					// データバッファ上における転送位置を取得
					//-----------------------------------
					ret = cnt.GetSamplingWritePointer(Id, out WriteIndex, out count, out carry);
					//-----------------------------------
					// オーバーランエラーをチェック
					//-----------------------------------
					if (carry == PreCarry)
					{
						if (count > (PreCount + DATA_NUM)) 
						{
							str = string.Format("Overrun Error!(count = {0:d})", count);
							txtError.Text = str;
							return;
						}
					}
					//-----------------------------------
					// 前回と同じカウント値であれば終了
					//	(転送完了メッセージから呼ばれた場合のため)
					//-----------------------------------
					if ((count == PreCount) && (carry == PreCarry))
					{
						return;
					}
					//-----------------------------------
					// ファイルに転送されたデータを書き込みます
					//-----------------------------------
					//-----------------------------------
					// ファイルを開く
					//-----------------------------------
					try
					{
						fp = File.AppendText(file_name);
					}
					catch (System.IO.IOException)
					{
						txtReturn.Text = "fopen : file open error.";
						return;
					}
					//-----------------------------------
					// データ書き込み
					//-----------------------------------
					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++;
						}
					}
					//-----------------------------------
					// ファイルを閉じる
					//-----------------------------------
					fp.Close();
					//-----------------------------------
					// リードポインタを設定
					//-----------------------------------
					ReadIndex	= WriteIndex;
					PreCount	= count;
					PreCarry	= carry;
					//-----------------------------------
					// 転送カウント値を表示
					//-----------------------------------
					str = string.Format("{0:d}", count);
					txtTransCount.Text = str;
					break;
			}
			base.WndProc(ref m);
		}
	}
}
