
// InfiniteDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Infinite.h"
#include "InfiniteDlg.h"
#include "ConditionDlg.h"
#include "ModeDlg.h"
#include "afxdialogex.h"
#include "CCnt.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

short					Id;										// Device ID
unsigned long			SamplingData[DATA_NUM][CHANNEL_NUM];	// Buffer for sampling
extern unsigned long	NumberOfData;
unsigned long			ReadIndex;								// Read pointer
unsigned long			WriteIndex;								// Write pointer
unsigned long			PreCount;								// Previous transfer count
unsigned long			PreCarry;								// Previous carry count
TCHAR					file_name[] = _T("infinite.csv");		// Data file name

// CInfiniteDlg dialog



CInfiniteDlg::CInfiniteDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CInfiniteDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CInfiniteDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_EDIT_TRANS_COUNT, m_TransCount);
	DDX_Control(pDX, IDC_EDIT_STATUS, m_Status);
	DDX_Control(pDX, IDC_EDIT_RETURN, m_Return);
	DDX_Control(pDX, IDC_EDIT_ERROR, m_Error);
	DDX_Control(pDX, IDC_EDIT_DEV_NAME, m_DeviceName);
}

BEGIN_MESSAGE_MAP(CInfiniteDlg, CDialogEx)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_BUTTON_CNT_INIT, &CInfiniteDlg::OnBnClickedButtonCntInit)
	ON_BN_CLICKED(IDC_BUTTON_CNTMODE, &CInfiniteDlg::OnBnClickedButtonCntmode)
	ON_BN_CLICKED(IDC_BUTTON_CONDITION, &CInfiniteDlg::OnBnClickedButtonCondition)
	ON_BN_CLICKED(IDC_BUTTON_START, &CInfiniteDlg::OnBnClickedButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_STOP, &CInfiniteDlg::OnBnClickedButtonStop)
	ON_BN_CLICKED(IDC_BUTTON_DATA, &CInfiniteDlg::OnBnClickedButtonData)
	ON_BN_CLICKED(IDC_BUTTON_COUNT, &CInfiniteDlg::OnBnClickedButtonCount)
	ON_BN_CLICKED(IDC_BUTTON_STATUS, &CInfiniteDlg::OnBnClickedButtonStatus)
	ON_BN_CLICKED(IDC_BUTTON_CNT_EXIT, &CInfiniteDlg::OnBnClickedButtonCntExit)
	ON_BN_CLICKED(IDC_BUTTON_EXIT, &CInfiniteDlg::OnBnClickedButtonExit)
END_MESSAGE_MAP()


// CInfiniteDlg message handlers

//===================================================
//	Dialog initialization
//===================================================
BOOL CInfiniteDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	//-----------------------------------
	//	Initialize dialog display
	//-----------------------------------
	m_DeviceName.SetWindowText(_T("CNT000"));

	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CInfiniteDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CInfiniteDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

//===================================================
//	Completion processing
//===================================================
void CInfiniteDlg::OnClose()
{
	long	ret;

	//-----------------------------------
	//	Completion processing
	//-----------------------------------
	ret = CntExit(Id);

	CDialogEx::OnClose();
}

//===================================================
//	CntInit()
//===================================================
void CInfiniteDlg::OnBnClickedButtonCntInit()
{
	CString	str;
	char	buf[100], error_string[256];
	TCHAR	szBuf[100], szError_string[256];
	long	ret;

	//-----------------------------------
	//	Get device name
	//-----------------------------------
	m_DeviceName.GetWindowText(szBuf, sizeof(szBuf));
	sprintf_s(buf, "%S", szBuf);
	//-----------------------------------
	//	Initialization
	//-----------------------------------
	ret = CntInit(buf, &Id);
	CntGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("CntInit ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
}

//---------------------------------------------
// Display Counter Mode Setting dialog
//---------------------------------------------
void CInfiniteDlg::OnBnClickedButtonCntmode()
{
	//------------------------------
	// Display Counter Mode Setting dialog
	//------------------------------
	CModeDlg	dlg;
	dlg.DoModal();
	return;
}

//===================================================
//	Display Condition Setting dialog
//===================================================
void CInfiniteDlg::OnBnClickedButtonCondition()
{
	CConditionDlg	dlg;
	//-----------------------------------
	//	Display Condition Setting dialog
	//-----------------------------------
	dlg.DoModal();
	return;
}

//===================================================
//	Start transfer
//===================================================
void CInfiniteDlg::OnBnClickedButtonStart()
{
	short	ChNo[CHANNEL_NUM], i;
	char	error_string[256];
	TCHAR	szError_string[256];
	CString	str;
	long	ret;

	//-----------------------------------
	// Set message notification
	//-----------------------------------
	ret = CntNotifySamplingStop(Id, m_hWnd);
	if (ret != CNT_ERR_SUCCESS) {
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntNotifySamplingStop ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	ret = CntNotifySamplingCount(Id, NumberOfData, m_hWnd);
	if (ret != CNT_ERR_SUCCESS) {
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntNotifySamplingCount ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	//	Reset FIFO (Input)
	//-----------------------------------
	ret = CntSamplingFifoReset(Id);
	if (ret != CNT_ERR_SUCCESS){
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntSamplingFifoReset ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	//-----------------------------------
	//	Set data buffer
	//-----------------------------------
	ZeroMemory((PVOID)SamplingData, DATA_NUM * CHANNEL_NUM * sizeof(unsigned long));
	ret = CntSamplingSetBuffer(Id, &SamplingData[0][0], CHANNEL_NUM, DATA_NUM, CNTS_WRITE_RING);
	if (ret != CNT_ERR_SUCCESS){
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntSamplingSetBuffer ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	//------------------------------
	// Set parameter
	//------------------------------
	for (i = 0; i<CHANNEL_NUM; i++) {
		ChNo[i] = i;
	}
	//------------------------------
	// Start count
	//------------------------------
	ret = CntStartCount(Id, &ChNo[0], CHANNEL_NUM);
	if (ret != CNT_ERR_SUCCESS){
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntStartCount ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(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
	//-----------------------------------
	_tremove(file_name);
	//-----------------------------------
	//	Start transfer
	//-----------------------------------
	ret = CntSamplingStart(Id);
	if (ret != CNT_ERR_SUCCESS){
		CntGetErrorString(ret, error_string);
		wsprintf(szError_string, _T("%S"), error_string);
		str.Format(_T("CntSamplingStart ret = %d: %s"), ret, szError_string);
		m_Return.SetWindowText(str);
		return;
	}
	m_TransCount.SetWindowText(_T(""));
	m_Status.SetWindowText(_T(""));
	m_Error.SetWindowText(_T(""));
	return;
}

//===================================================
//	Stop transfer
//===================================================
void CInfiniteDlg::OnBnClickedButtonStop()
{
	char	error_string[256];
	TCHAR	szError_string[256];
	CString	str;
	long	ret;

	//-----------------------------------
	//	Stop transfer
	//-----------------------------------
	ret = CntSamplingStop(Id);
	CntGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("CntSamplingStop ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	return;
}

//===================================================
//	Display data file
//===================================================
void CInfiniteDlg::OnBnClickedButtonData()
{
	char	buf[100];

	//-----------------------------------
	// notepad
	//-----------------------------------
	sprintf_s(buf, sizeof(buf), "notepad.exe %S", file_name);
	WinExec(buf, SW_SHOW);
	return;
}

//===================================================
//	Transfer count
//===================================================
void CInfiniteDlg::OnBnClickedButtonCount()
{
	unsigned long	count = 0, carry = 0;
	char			error_string[256];
	TCHAR			szError_string[256];
	CString			str;
	long			ret;

	//-----------------------------------
	// Get transfer count
	//-----------------------------------
	ret = CntGetSamplingCount(Id, &count, &carry);
	CntGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("CntGetSamplingCount ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	if (ret == CNT_ERR_SUCCESS){
		str.Format(_T("%lu"), count);
		m_TransCount.SetWindowText(str);
	}
	return;
}

//===================================================
//	Transfer status
//===================================================
void CInfiniteDlg::OnBnClickedButtonStatus()
{
	unsigned long	status, err;
	char			error_string[256];
	TCHAR			szError_string[256];
	CString			str;
	long			ret;

	//-----------------------------------
	// Get transfer status
	//-----------------------------------
	ret = CntGetSamplingStatus(Id, &status, &err);
	CntGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("CntGetSamplingStatus ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	if (ret != CNT_ERR_SUCCESS){
		return;
	}

	// Status
	str = "";
	if (status & CNTS_STATUS_BMSTOP)	str += "BmStop,";
	if (status & CNTS_STATUS_CNTSTART)	str += "CntStart,";
	if (status & CNTS_STATUS_CNTSTOP)	str += "CntStop,";
	if (status & CNTS_STATUS_TRGIN)		str += "TrgIn,";
	if (status & CNTS_STATUS_OVERRUN)	str += "Overrun";
	m_Status.SetWindowText(str);
	// Error
	str = "";
	if (err & CNTS_STATUS_FIFOFULL)		str += "FifoFull,";
	if (err & CNTS_STATUS_SGOVERIN)		str += "S/GOverIn,";
	if (err & CNTS_STATUS_TRGERR)		str += "TrgErr,";
	if (err & CNTS_STATUS_CLKERR)		str += "ClkErr,";
	if (err & CNTS_STATUS_SLAVEHALT)	str += "SlaveHalt,";
	if (err & CNTS_STATUS_MASTERHALT)	str += "MasterHalt";

	m_Error.SetWindowText(str);
	return;
}

//===================================================
//	CntExit
//===================================================
void CInfiniteDlg::OnBnClickedButtonCntExit()
{
	char			error_string[256];
	TCHAR			szError_string[256];
	CString			str;
	long			ret;

	//-----------------------------------
	// CntExit
	//-----------------------------------
	ret = CntExit(Id);
	CntGetErrorString(ret, error_string);
	wsprintf(szError_string, _T("%S"), error_string);
	str.Format(_T("CntExit ret = %d: %s"), ret, szError_string);
	m_Return.SetWindowText(str);
	return;
}

//===================================================
//	Exit
//===================================================
void CInfiniteDlg::OnBnClickedButtonExit()
{
	OnOK();
	return;
}

//===================================================
// Counter event notification processing
//===================================================
LRESULT CInfiniteDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
	long			ret;
	unsigned long	count, carry;
	unsigned long	data_count, ch_no, Cnt;
	FILE			*fp;
	TCHAR			buf[100];
	CString			str;

	switch (message) {
	case CNTM_SAMPLING_COUNT:	// Specified number transfer completion
		//-----------------------------------
		// Retrieve transfer position on data buffer
		//-----------------------------------
		ret = CntGetSamplingWritePointer(Id, &WriteIndex, &count, &carry);
		//-----------------------------------
		// Check overflow error
		//-----------------------------------
		if (carry == PreCarry){
			if (count > (PreCount + DATA_NUM)) {
				str.Format(_T("Overrun Error!(count = %lu)"), count);
				m_Error.SetWindowText(str);
				return TRUE;
			}
		}
		//-----------------------------------
		// 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 TRUE;
		}
		//-----------------------------------
		// Write transferred data to file
		//-----------------------------------
		//-----------------------------------
		// Open file
		//-----------------------------------
		if ((_tfopen_s(&fp, file_name, _T("a"))) != 0) {
			str.Format(_T("fopen : file open error."));
			m_Return.SetWindowText(str);
			return TRUE;
		}
		//-----------------------------------
		// Write data
		//-----------------------------------
		if (WriteIndex > ReadIndex){
			Cnt = count - (WriteIndex - ReadIndex);
			for (data_count = ReadIndex; data_count < WriteIndex; data_count++){
				wsprintf(buf, _T("%8d: , "), Cnt);
				for (ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++){
					wsprintf(buf, _T("%s%08X, "), buf, SamplingData[data_count][ch_no]);
				}
				wsprintf(buf, _T("%s%08X\n"), buf, SamplingData[data_count][ch_no]);
				_fputts(buf, fp);

				Cnt++;
			}
		}
		else{
			Cnt = count - (DATA_NUM - ReadIndex + WriteIndex);
			for (data_count = ReadIndex; data_count < DATA_NUM; data_count++){
				wsprintf(buf, _T("%8d: , "), Cnt);
				for (ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++){
					wsprintf(buf, _T("%s%08X, "), buf, SamplingData[data_count][ch_no]);
				}
				wsprintf(buf, _T("%s%08X\n"), buf, SamplingData[data_count][ch_no]);
				_fputts(buf, fp);

				Cnt++;
			}
			for (data_count = 0; data_count < WriteIndex; data_count++){
				wsprintf(buf, _T("%8d: , "), Cnt);
				for (ch_no = 0; ch_no < CHANNEL_NUM - 1; ch_no++){
					wsprintf(buf, _T("%s%08X, "), buf, SamplingData[data_count][ch_no]);
				}
				wsprintf(buf, _T("%s%08X\n"), buf, SamplingData[data_count][ch_no]);
				_fputts(buf, fp);

				Cnt++;
			}
		}
		//-----------------------------------
		// Close file
		//-----------------------------------
		fclose(fp);
		//-----------------------------------
		// Set read pointer
		//-----------------------------------
		ReadIndex = WriteIndex;
		PreCount = count;
		PreCarry = carry;
		//-----------------------------------
		// Display transfer count value
		//-----------------------------------
		str.Format(_T("%lu"), count);
		m_TransCount.SetWindowText(str);
		break;

	case CNTM_SAMPLING_STOP:	// Transfer completion
		m_Status.SetWindowText(_T("Stopped!"));
		::PostMessage(m_hWnd, CNTM_SAMPLING_COUNT, wParam, lParam);
		break;
	}

	return CDialogEx::DefWindowProc(message, wParam, lParam);
}