using System;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using CgpibCs;

namespace CSubFuncCs
{
	/// <summary>
	/// SubFunc ̊Tv̐łB
	/// </summary>
	public class CSubFunc
	{
		public CSubFunc()
		{
			// 
			// TODO: RXgN^ WbNɒǉĂB
			//
		}

		Cgpib	gpib = new Cgpib();
		public 	uint[]	Cmd = new uint[30];						// bZ[W(R}h)
		public	IntPtr	pCmd;									// CmdzpIntPtr

		// ************************************************** [`FbN(f)֐] ***
		public int CheckRet(string Func, uint Ret, out string csBuf)
		{
			int	RetCode;
			int	RetTmp;

			csBuf = new String('0', 1);
			RetCode = 0;										// 펞
			RetTmp = (int)Ret & 0xff;							// }XN
			if (RetTmp >= 3)
			{													// Ret3ȏ̏ꍇ̓G[
				RetCode = 1;									// ُ펞
				switch (RetTmp)
				{
					case 80:	csBuf = Func + " : I/OAhXG[łB[Config.exe]ŊmFĂB";	break;	// 0x50
					case 82:	csBuf = Func + " : WXgݒG[łB[Config.exe]ŊmFĂB";	break;	// 0x52
					case 128:	csBuf = Func + " : wf[^M[SRQ]͏オĂ܂"; 				break;	// 0x80
					case 140:	csBuf = Func + " : 񓯊֐̎sł"; 									break;	// 0x8C
					case 141:	csBuf = Func + " : 񓯊֐I܂"; 							break;	// 0x8D
					case 200:	csBuf = Func + " : Xbh쐬ł܂B"; 								break;	// 0xC8
					case 201:	csBuf = Func + " : ̃Cxgsł"; 									break;	// 0xC9
					case 210:	csBuf = Func + " : DMAݒł܂"; 										break;	// 0xD0
					case 240:	csBuf = Func + " : EscL[܂B"; 									break;	// 0xF0
					case 241:	csBuf = Func + " : t@Co̓G[łB"; 								break;	// 0xF1
					case 242:	csBuf = Func + " : AhXw肪ԈĂ܂B"; 							break;	// 0xF2
					case 243:	csBuf = Func + " : obt@wG[łB";									break;	// 0xF3
					case 244:	csBuf = Func + " : zTCYG[łB";										break;	// 0xF4
					case 245:	csBuf = Func + " : obt@܂B"; 									break;	// 0xF5
					case 246:	csBuf = Func + " : sȃIuWFNgłB"; 								break;	// 0xF6
					case 247:	csBuf = Func + " : foCX̉̃`FbNłB"; 						break;	// 0xF7
					case 248:	csBuf = Func + " : sȃf[^^łB"; 										break;	// 0xF8
					case 249:	csBuf = Func + " : ȏfoCXǉł܂B"; 						break;	// 0xF9
					case 250:	csBuf = Func + " : foCX܂B"; 								break;	// 0xFA
					case 251:	csBuf = Func + " : f~^foCXԂňĂ܂B"; 						break;	// 0xFB
					case 252:	csBuf = Func + " : GPIBG[łB"; 											break;	// 0xFC
					case 253:	csBuf = Func + " : f~^݂̂M܂B"; 								break;	// 0xFD
					case 254:	csBuf = Func + " : ^CAEg܂B"; 									break;	// 0xFE
					case 255:	csBuf = Func + " : p[^G[łB"; 									break;	// 0xFF
					default:	break;
				}
			}
			else
			{
				csBuf = Func + " : I܂B";
			}

			// -- [Ifc] [Srq] M̏ -- //
			RetTmp = (int)Ret & 0xff00;							// }XN
			switch (RetTmp)
			{
				case 0x100:		csBuf = csBuf + " -- [SRQ]M<STATUS>";			break;		// 256(10)
				case 0x200:		csBuf = csBuf + " -- [IFC]M<STATUS>";			break;		// 512(10)
				case 0x300:		csBuf = csBuf + " -- [SRQ][IFC]M<STATUS>";	break;		// 768(10)
				default:		break;
			}
			return	RetCode;
		}
		
		//************************************************************ [ׂ֐] ***
		public int Pows(int x, int y)
		{
			int	tmp = 1;

			while (y-- > 0)										// y ̉񐔕JԂ܂B
				tmp *= x;										// tmp  x |Ă܂B
			return(tmp);
		}
		
		//****************************************************** [ -> 16i] ***
		public uint chr2hex(string ch)
		{
			int		length;
			int		Count;
			int		Ret;
			int		RetTmp;

			RetTmp = 0;
			length	= ch.Length;								// 𒲂ׂ܂B
			for (Count = 0; Count < length; Count++)
			{													// JԂ܂B
				if ((ch[Count] >= 0x30) && (ch[Count] <= 0x39))	// ASCIIR[h琔IȒl擾
				{
					Ret = (ch[Count] - 0x30) * Pows(0x10,(length - (Count + 1)));	// 0 - 9
				}
				else if ((ch[Count] >= 0x41) && (ch[Count] <= 0x46))
				{
					Ret = (ch[Count] - 0x37) * Pows(0x10,(length - (Count + 1)));	// A - F
				}
				else if ((ch[Count] >= 0x61) && (ch[Count] <= 0x66))
				{
					Ret = (ch[Count] - 0x57) * Pows(0x10,(length - (Count + 1)));	// a - f
				}
				else
				{
					Ret = 0xff;									// sȏꍇFF(255)Ԃ܂B
				}
	
				RetTmp = RetTmp + Ret;
			}
			return (uint)RetTmp;
		}
		
		//************************************************************ [֐] ***
		public int GpibInit(out string TextRet)
		{
//			uint	Delim,Eoi;
			uint	Ret;
			uint	Timeout,Ifctime;
			string	csBuf;
			uint	Master;


			Ret = gpib.Exit();									// 2dh܂B
			Ret = gpib.Ini();									// GPIB܂B
			csBuf = "GpIni";

			if ((Ret & 0xFF) != 0)
			{													// GpIniɍs`FbNB
				CheckRet("GpIni", Ret, out csBuf);
				TextRet = csBuf.ToString(); 
				return	1;
			}
			
			Master = 0;
			gpib.Boardsts(0x0a, out Master);					// }X^̃AhX擾܂B
			// }X^AX[u̔
			if (Master == 0)
			{
				Ifctime = 1;									// ł100secɂĂ܂B
				Ret = gpib.Ifc(Ifctime);
				csBuf = "GpIfc";
				if ((Ret & 0xFF) != 0)
				{												// GpIfcɍs`FbNB
					CheckRet("GpIfc", Ret, out csBuf);
					TextRet = csBuf.ToString();
					return	1;
				}
				Ret = gpib.Ren();
				csBuf = "GpRen";
				if ((Ret & 0xFF) != 0)
				{												// GpRenɍs`FbNB
					CheckRet("GpRen", Ret, out csBuf);
					TextRet = csBuf.ToString();
					return	1;
				}
			}

//			Delim = 1;										// f~^FCR+LF
//			Eoi = 1;											// EOI	Fgp
//			Ret = gpib.Delim(Delim, Eoi);
//			csBuf = "GpDelim";
//			if ((Ret & 0xFF) != 0)
//			{													// GpDelimɍs`FbNB
//				CheckRet("GpDelim", Ret, out csBuf);
//				TextRet = csBuf;
//				return	1;
//			}
			Timeout = 10000;									// 10b
			Ret = gpib.Timeout(Timeout);
			csBuf = "GpTimeout";
			if ((Ret & 0xFF) != 0)
			{													// GpTimeoutɍs`FbNB
				TextRet = csBuf.ToString();
				CheckRet("GpTimeout", Ret, out csBuf);
				return	1;
			}

			TextRet = "܂B";					// I
			return	0;
		}
		
		//******************************************************** [GpTalk()̉p] ***
		public int GpibPrint(uint DevAddr, string Str)
		{
			string	srbuf = new string(' ', 10000);				// M
			uint	MyAddr;										// }CAhXp
			string	ErrText;									// G[
			uint	Ret;										// ߂l
			int		RetTmp;										// \߂l
			uint	srlen;										// ̒

			Ret = gpib.Boardsts(0x08, out MyAddr);				// }CAhX擾
			Cmd[0] = 2;											// R}h̐
			Cmd[1] = MyAddr;									// }CAhX(PC)
			Cmd[2] = DevAddr;									// X[u@

			srlen = (uint)Str.Length;							// 𑪒
			srbuf = Str;										// CString -> char
			Ret = gpib.Talk(pCmd, srlen, srbuf);				// ۂ̑M

			if (Ret >= 3)
			{													// G[`FbN
				RetTmp = CheckRet("GpTalk", Ret, out ErrText);
				ErrText += " p܂H";
				DialogResult Resul = MessageBox.Show(ErrText, null, MessageBoxButtons.YesNo);
				if (Resul == DialogResult.No)
				{
						return 1;								// ُ
				}
			}
			return 0;											// 
		}
		
		//****************************************************** [GpListen()̉p] ***
		public int GpibInput(uint DevAddr, StringBuilder Str)
		{
			uint	MyAddr, srlen;								// }CAhXA̒p
			string	/*TmpStr, */ErrText;						// \AG[
			uint	Ret;										// ߂l
			int		RetTmp;										// \߂l

			Ret = gpib.Boardsts(0x08, out MyAddr);				// }CAhX擾
			Cmd[0] = 2;											// R}h̐
			Cmd[1] = DevAddr;									// X[u@
			Cmd[2] = MyAddr;									// }CAhX(PC)
			srlen = 10000;										// Mf[^̒𑪂Ă܂B
			Ret = gpib.Listen(pCmd, ref srlen, Str);			// ۂ̑M
			if (Ret >= 3)
			{													// G[`FbN
				RetTmp = CheckRet("GpListen", Ret, out ErrText);
				ErrText += " p܂H";
				DialogResult Resul = MessageBox.Show(ErrText, null, MessageBoxButtons.YesNo);
				if (Resul == DialogResult.No) return 1;			// ُ = 1Ԃ
			}
			return 0;											//  = 0Ԃ
		}
		
		// ************************************************* [ oCiMp֐ ] ***
		public int GpibInputB(uint DevAddr, StringBuilder IntData)
		{
			StringBuilder	szData = new StringBuilder(10000);
			uint			Ret, MyAddr, srlen;
			int				RetTmp;
			string			ErrText = "";
			string			szDataVal;
			int				i;

			Ret = gpib.Delim(0, 1);								// f~^𑊎@ƍ킹܂B
			Ret = gpib.Boardsts(0x08, out MyAddr);				// }CAhX擾
			Cmd[0] = 2;											// R}h̐
			Cmd[1] = DevAddr;									// X[u@
			Cmd[2] = MyAddr;									// }CAhX(PC)
			srlen = 2;											// Mf[^̒𑪂Ă܂B
			Ret = gpib.Listen(pCmd, ref srlen, szData);
			if (Ret != 128)
			{													// rŃf[^؂Ă邽Ret=128ɂȂ܂B
				if (Ret >= 3)
				{												// G[`FbN
					RetTmp = CheckRet("GpListen", Ret, out ErrText);
					ErrText += " p܂H";
					DialogResult Resul = MessageBox.Show(ErrText, null, MessageBoxButtons.YesNo);
					if (Resul == DialogResult.No)
					{
						return 1;							// ُ = 1Ԃ
					}
				}
			}
			Cmd[0] = 0;
			szDataVal = szData.ToString().Substring(1, 1);
			for (i = 0; i < szDataVal.Length; i++)
			{
				if (Char.IsDigit(szDataVal, i) == false)
				{
					break;
				}
			}			
			szDataVal = szDataVal.Substring(0, i);
			if (i == 0)
			{
				srlen = 0;
			}
			else
			{
				srlen = uint.Parse(szDataVal);
			}

			Ret = gpib.Listen(pCmd, ref srlen, szData);
			
			for (i = 0; i < szData.Length; i++)
			{
				if (Char.IsDigit(szData.ToString(), i) == false)
				{
					break;
				}
			}
			szDataVal = szData.ToString().Substring(0, i);
			if (i == 0)
			{
				srlen = 1;
			}
			else
			{
				srlen = uint.Parse(szDataVal) + 1;
			}

			Ret = gpib.Listen(pCmd, ref srlen, IntData);
			Ret = gpib.Delim(3, 1);								// f~^߂܂B
			return 0;
		}
		
		//****************************************************** [R}hM֐] ***
		public int GpibCommand(uint DevAddr)
		{
			string	ErrText;
			uint	Ret;
			int		RetTmp;

			Cmd[0] = 2;
			Cmd[1] = 0x3F;
			Cmd[2] = 0x5F;

			Ret = gpib.Comand(pCmd);

			if (Ret != 0)
			{
				RetTmp = CheckRet("GpComand", Ret, out ErrText);
				MessageBox.Show(ErrText, null, MessageBoxButtons.OK);
				return 1;
			}
			return 0;
		}
		
		//**************************************************************** [I֐] ***
		public void GpibExit()
		{
			uint	Master;
			uint	Ret;

			Master = 0;
			Ret = gpib.Boardsts(0x0a, out Master);				// }X^̃AhX擾܂B
			if (Ret == 80)
			{
				return;											// ĂȂꍇɖ߂܂B
			}
	
			if (Master == 0)
			{													// }X^̏ꍇ
				Cmd[0] = 2;										// R}h(bZ[W)
				Cmd[1] = 0x3f;									// AX(Xi)
				Cmd[2] = 0x5f;									// Ag[N(g[J)

				Ret = gpib.Comand(pCmd);						// R}h𑗐M܂B
				Ret = gpib.Resetren();							// @̃[g܂B
			}
	
			Ret = gpib.Exit();
		}
		
		// OPC̃`FbN ////////////////////////////////////////////////////////////////////////////////
		public void WaitOPC(uint Dev)
		{
			int				Ret;
			StringBuilder	RdData = new StringBuilder(10000);

			Ret = GpibPrint(Dev, "*OPC?");						// HƂĂ邩
			Ret = GpibInput(Dev, RdData);
		}
		
		//**************************************************** [𐔎ɕϊ] ***
		public void Str2Num(string str, uint str_len , ref int[] num, uint num_len)
		{
			int		i, j=0, cnt;
			string	start;

			start = str;
			cnt = 0;
			for (i = 0; i < str_len; i++)
			{
				/* string to integer */
				if (str[i] == ',')
				{
					if (i == 1)
					{
						start = str.Substring(j, i-j);
					}
					else
					{
						start = str.Substring(j, i-j);
					}
					try
					{
						num[cnt] = Convert.ToInt32(start);
					}
					catch (System.FormatException)
					{
						num[cnt] = 0;
					}
					j = i + 1;
					cnt++;
					if (cnt >= num_len)
					{
						break;
					}
				}
			}
			if (cnt >= num_len)
			{
				try
				{
					num[cnt] = Convert.ToInt32(start);
				}
				catch (System.FormatException)
				{
					num[cnt] = 0;
				}
			}
		}
		
		//********************************************************** [Ot`] ***
		// QŃOtpsN`[_CAOgpĂ܂B
		public void DrawGraph(Control Picture, int[] num, uint num_len, int min, int max)
		{
			Rectangle	Rect = Picture.ClientRectangle;
			Pen			hPen_Black, hPen_Red, hPen_White;
			Point[]		point = new Point[4];
			int			x_max, y_max;
			int			x_width, y_width;
			float		x_unit, y_unit;
			uint		i;

			/* Initialize */
			x_max = Rect.Right;
			y_max = Rect.Bottom;
			Graphics g = Picture.CreateGraphics();

			hPen_Black	= new Pen(Color.Black, 1);				/* Black */
			hPen_Red	= new Pen(Color.Red, 1);				/* Red   */
			hPen_White	= new Pen(Color.White, 1);				/* White */	
			/* Draw Structure */
			SolidBrush whiteBrush = new SolidBrush(Color.White);
			g.FillRectangle(whiteBrush, Picture.ClientRectangle);
			for (i = 0; i <= 10; i++)
			{
				g.DrawLine(hPen_Black, (x_max / 10) * i, 0, (x_max / 10) * i, y_max);
			}
			for (i = 0; i <= 10; i++)
			{
				g.DrawLine(hPen_Black, 0, (y_max / 10) * i, x_max, (y_max / 10) * i); 
			}
			point[0].X = (x_max / 10) * 5 - 1;	point[0].Y = 0;
			point[1].X = (x_max / 10) * 5 + 1;	point[1].Y = 0;
			point[2].X = (x_max / 10) * 5 + 1;	point[2].Y = y_max;
			point[3].X = (x_max / 10) * 5 - 1;	point[3].Y = y_max;
			g.DrawLines(hPen_Red, point);
			point[0].X = 0;		point[0].Y = (y_max / 10) * 5 - 1;
			point[1].X = 0;		point[1].Y = (y_max / 10) * 5 + 1;
			point[2].X = x_max;	point[2].Y = (y_max / 10) * 5 + 1;
			point[3].X = x_max;	point[3].Y = (y_max / 10) * 5 - 1;
			g.DrawLines(hPen_Red, point);
			/* Draw Graph */
			x_width = (int)num_len;
			y_width = max - min;
			x_unit = (float)((float)x_max / (float)x_width);
			y_unit = (float)((float)y_max / (float)y_width);
			for (i = 0; i < (num_len - 1); i++)
			{
				g.DrawLine(hPen_Black, x_unit * i, (y_width - (num[i] - min)) * y_unit, x_unit * (i + 1), (y_width - (num[i+1] - min)) * y_unit);
			}
		}
	}
}
