// Megawin Easy USBDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Megawin Easy USB.h"
#include "Megawin Easy USBDlg.h"
#include "EasyPODDLL.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


#define EASYPOD_INDEX      0x00
#define EASYCOM_INDEX      0x01
MW_WRITEDATA pWriteData;
MW_READDATA pReadData;
MW_CONNECTPOD pConnectPOD;
MW_DISCONNECTPOD pDisconnectPOD;
MW_CLEARPODBUFFER pClearPODBuffer;

MW_EasyPOD g_EasyPOD;
HANDLE g_hCOMDevice;
TCHAR szAppCaption[] = _T("Megawin Easy USB");
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMegawinEasyUSBDlg dialog

CMegawinEasyUSBDlg::CMegawinEasyUSBDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CMegawinEasyUSBDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CMegawinEasyUSBDlg)
	m_strWriteBuffer = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMegawinEasyUSBDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CMegawinEasyUSBDlg)
	DDX_Control(pDX, IDC_EDT_READ_BUFFER, m_edtReadBuffer);
	DDX_Control(pDX, IDC_EDT_WRITE_BUFFER, m_edtWriteBuffer);
	DDX_Control(pDX, IDC_CBO_BAUDRATE, m_cboBaudRate);
	DDX_Control(pDX, IDC_CBO_COMPORT, m_cboComPort);
	DDX_Control(pDX, IDC_STA_SETTING, m_staSetting);
	DDX_Control(pDX, IDC_CBO_DEVICE_TYPE, m_cboDeviceType);
	DDX_Text(pDX, IDC_EDT_WRITE_BUFFER, m_strWriteBuffer);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CMegawinEasyUSBDlg, CDialog)
	//{{AFX_MSG_MAP(CMegawinEasyUSBDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_CBN_SELCHANGE(IDC_CBO_DEVICE_TYPE, OnSelchangeCboDeviceType)
	ON_BN_CLICKED(IDC_BTN_EXIT, OnBtnExit)
	ON_BN_CLICKED(IDC_BTN_CONNECT, OnBtnConnect)
	ON_BN_CLICKED(IDC_BTN_DISCONNECT, OnBtnDisconnect)
	ON_BN_CLICKED(IDC_RDO_HEX, OnRdoHex)
	ON_BN_CLICKED(IDC_RDO_STRING, OnRdoString)
	ON_BN_CLICKED(IDC_BTN_WRITE_BYTES, OnBtnWriteBytes)
	ON_BN_CLICKED(IDC_BTN_READ_BYTES, OnBtnReadBytes)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMegawinEasyUSBDlg message handlers

BOOL CMegawinEasyUSBDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 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
	
	// TODO: Add extra initialization here
	m_cboDeviceType.AddString(_T("EasyPOD"));
	m_cboDeviceType.AddString(_T("EasyCOM"));
    m_cboDeviceType.SetCurSel(0);

    int i;
	TCHAR tmpBuffer[0x10];
	for (i=1 ; i<17 ; i++)
	{
		_stprintf(tmpBuffer, _T("COM%d"), i);
		m_cboComPort.AddString(tmpBuffer);
	}
	m_cboComPort.SetCurSel(0);

	m_cboBaudRate.AddString(_T("1200"));
	m_cboBaudRate.AddString(_T("2400"));
	m_cboBaudRate.AddString(_T("4800"));
	m_cboBaudRate.AddString(_T("9600"));
	m_cboBaudRate.AddString(_T("14400"));
	m_cboBaudRate.AddString(_T("19200"));
	//m_cboBaudRate.AddString(_T("28800"));
	m_cboBaudRate.AddString(_T("38400"));
	m_cboBaudRate.AddString(_T("56000"));
	m_cboBaudRate.AddString(_T("57600"));
	m_cboBaudRate.AddString(_T("115200"));
    m_cboBaudRate.SetCurSel(0);

    SetDlgItemText(IDC_EDT_VID, _T("0E6A"));
	static_cast<CEdit *>(GetDlgItem(IDC_EDT_VID))->SetLimitText(4);
	SetDlgItemText(IDC_EDT_PID, _T("0317"));
	static_cast<CEdit *>(GetDlgItem(IDC_EDT_PID))->SetLimitText(4);
	SetDlgItemText(IDC_EDT_INDEX, _T("1"));
	static_cast<CEdit *>(GetDlgItem(IDC_EDT_INDEX))->SetLimitText(2);
	OnSelchangeCboDeviceType();
    
	CheckDlgButton(IDC_RDO_HEX, BST_CHECKED);
    GetDlgItem(IDC_BTN_WRITE_BYTES)->EnableWindow(FALSE);
	GetDlgItem(IDC_BTN_READ_BYTES)->EnableWindow(FALSE);
	GetDlgItem(IDC_BTN_DISCONNECT)->EnableWindow(FALSE);

	if (hEaysPODDLL != NULL)
	{
        pWriteData = (MW_WRITEDATA)GetProcAddress(hEaysPODDLL, "WriteData");
		pReadData = (MW_READDATA)GetProcAddress(hEaysPODDLL, "ReadData");
		pConnectPOD = (MW_CONNECTPOD)GetProcAddress(hEaysPODDLL, "ConnectPOD");
		pDisconnectPOD = (MW_DISCONNECTPOD)GetProcAddress(hEaysPODDLL, "DisconnectPOD");
		pClearPODBuffer = (MW_CLEARPODBUFFER)GetProcAddress(hEaysPODDLL, "ClearPODBuffer");		
	}

    LOGFONT lfont;
	lfont.lfHeight = 0xFFFFFFF5;
	lfont.lfWidth = 7;
	lfont.lfEscapement = 0;
	lfont.lfOrientation = 0;
	lfont.lfWeight = 0x00000190;
	lfont.lfItalic = 0x00;
    lfont.lfUnderline = 0x00;
	lfont.lfStrikeOut = 0x00;
	lfont.lfCharSet = 0x00;
	lfont.lfOutPrecision = 0x00;
	lfont.lfClipPrecision	= 0x00;
    lfont.lfQuality = 0x00;
	lfont.lfPitchAndFamily = 0x31;
	strcpy(lfont.lfFaceName, "Courier New");        
	m_BufferFont.CreateFontIndirect(&lfont);

	m_edtWriteBuffer.SetFont(&m_BufferFont);
    m_edtReadBuffer.SetFont(&m_BufferFont);

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

void CMegawinEasyUSBDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// 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 CMegawinEasyUSBDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (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
	{
		CDialog::OnPaint();
	}
}

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

void CMegawinEasyUSBDlg::OnSelchangeCboDeviceType() 
{
	// TODO: Add your control notification handler code here
   int Index;
   Index = m_cboDeviceType.GetCurSel();
   if (Index == EASYPOD_INDEX)
   {
       SetDlgItemText(IDC_STA_SETTING, "POD Setting");
       m_staSetting.MoveWindow(284, 85, 114, 112);
	   GetDlgItem(IDC_EDT_VID)->ShowWindow(SW_SHOW);
	   GetDlgItem(IDC_EDT_PID)->ShowWindow(SW_SHOW);
	   GetDlgItem(IDC_EDT_INDEX)->ShowWindow(SW_SHOW);
	   GetDlgItem(IDC_STA_VID)->ShowWindow(SW_SHOW);
	   GetDlgItem(IDC_STA_PID)->ShowWindow(SW_SHOW);
	   GetDlgItem(IDC_STA_INDEX)->ShowWindow(SW_SHOW);
	   GetDlgItem(IDC_CBO_COMPORT)->ShowWindow(SW_HIDE);
	   GetDlgItem(IDC_CBO_BAUDRATE)->ShowWindow(SW_HIDE);
	   
   }
   else
   {
       SetDlgItemText(IDC_STA_SETTING, "COM Setting");
       m_staSetting.MoveWindow(284, 85, 114, 90);
	   GetDlgItem(IDC_EDT_VID)->ShowWindow(SW_HIDE);
	   GetDlgItem(IDC_EDT_PID)->ShowWindow(SW_HIDE);
	   GetDlgItem(IDC_EDT_INDEX)->ShowWindow(SW_HIDE);
	   GetDlgItem(IDC_STA_VID)->ShowWindow(SW_HIDE);
	   GetDlgItem(IDC_STA_PID)->ShowWindow(SW_HIDE);
	   GetDlgItem(IDC_STA_INDEX)->ShowWindow(SW_HIDE);
	   GetDlgItem(IDC_CBO_COMPORT)->ShowWindow(SW_SHOW);
	   GetDlgItem(IDC_CBO_BAUDRATE)->ShowWindow(SW_SHOW);
   }
}

void CMegawinEasyUSBDlg::OnBtnExit() 
{
	// TODO: Add your control notification handler code here
    OnOK();	
}

void CMegawinEasyUSBDlg::OnBtnConnect() 
{
	// TODO: Add your control notification handler code here
    int DeviceTypeIndex = 0;
    int DeviceIndex = 0;
	BOOL bResult = 0;
	BOOL bComError = FALSE;
	DWORD dwResult = 0;
	DWORD dwVID = 0, dwPID = 0;
    TCHAR tmpBuffer[10] = _T("");    
	TCHAR ComBuffer[10] = _T("\\\\.\\");   
	DCB dcb ;

    DeviceTypeIndex = m_cboDeviceType.GetCurSel();
    if (DeviceTypeIndex == EASYPOD_INDEX)
    {
		GetDlgItemText(IDC_EDT_VID, tmpBuffer, 5);
        dwVID = _tcstoul(tmpBuffer , NULL, 16);         
		GetDlgItemText(IDC_EDT_PID, tmpBuffer, 5);
        dwPID = _tcstoul(tmpBuffer , NULL, 16);  	   
		GetDlgItemText(IDC_EDT_INDEX, tmpBuffer, 3);
        DeviceIndex = _tcstoul(tmpBuffer , NULL, 16);  	 
		if ((dwVID != 0) && (dwPID != 0) && (DeviceIndex != 0))
		{
			g_EasyPOD.VID = dwVID;
			g_EasyPOD.PID = dwPID;
		 	dwResult = pConnectPOD(&g_EasyPOD, DeviceIndex);
			if (dwResult == ERROR_SUCCESS)
			{				
		        g_EasyPOD.ReadTimeOut = 500;
			    g_EasyPOD.WriteTimeOut = 500;
				GetDlgItem(IDC_BTN_DISCONNECT)->EnableWindow(TRUE);
				GetDlgItem(IDC_BTN_WRITE_BYTES)->EnableWindow(TRUE);
				GetDlgItem(IDC_BTN_READ_BYTES)->EnableWindow(TRUE);
				GetDlgItem(IDC_BTN_CONNECT)->EnableWindow(FALSE);
				SetDlgItemText(IDC_EDT_STATUS, "Connect !");
			}
			else
			{
                SetDlgItemText(IDC_EDT_STATUS, "Fail Connect !");
			}
		}
		else
			MessageBox(_T("POD Setting Error"), szAppCaption, MB_OK | MB_ICONERROR);		  
    }
    else
    {  	    
		if (m_cboComPort.GetCurSel() != -1)
	        m_cboComPort.GetLBText(m_cboComPort.GetCurSel(), &ComBuffer[4]);
	    if ((g_hCOMDevice = CreateFile( ComBuffer, GENERIC_READ | GENERIC_WRITE,   // open COMM device
										0,                                      // exclusive access
										NULL,                                   // no security attrs
										OPEN_EXISTING,
										//FILE_ATTRIBUTE_NORMAL |	FILE_FLAG_OVERLAPPED ,									
										FILE_ATTRIBUTE_NORMAL,									
										NULL )) == (HANDLE) -1 ) 
		{
			//ShowErrorMessage(GetLastError()) ;
			SetDlgItemText(IDC_EDT_STATUS, "Fail Connect !");
			bComError = TRUE;;   
		}	    		            
		if (bComError == FALSE)
		{
			bResult = SetupComm(g_hCOMDevice , 4096, 4096 );  // setup device buffers
			if (bResult == 0)
			{
			    //ShowErrorMessage(GetLastError());
				SetDlgItemText(IDC_EDT_STATUS, "Fail Connect !");
			    CloseHandle(g_hCOMDevice);
			    g_hCOMDevice = INVALID_HANDLE_VALUE;
			    bComError = TRUE;
            }
			else
			{
			    bResult = PurgeComm(g_hCOMDevice, PURGE_TXABORT | PURGE_RXABORT |PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
				if (bResult == 0)
				{
					//ShowErrorMessage(GetLastError());
					SetDlgItemText(IDC_EDT_STATUS, "Fail Connect !");
					CloseHandle(g_hCOMDevice);
					g_hCOMDevice = INVALID_HANDLE_VALUE;
					bComError = TRUE;
				}
			}
		}
		if (bComError == FALSE)
		{
		    dcb.DCBlength = sizeof( DCB );
			bResult = GetCommState(g_hCOMDevice, &dcb ) ;
			if (bResult == 0)
			{
				//ShowErrorMessage(GetLastError());
				SetDlgItemText(IDC_EDT_STATUS, "Fail Connect !");
				CloseHandle(g_hCOMDevice);
				g_hCOMDevice = INVALID_HANDLE_VALUE;
				bComError = TRUE;
			}
		}
        if (bComError == FALSE)
		{
			if (m_cboBaudRate.GetCurSel() == -1)
				m_cboBaudRate.SetCurSel(0); 
 			switch (m_cboBaudRate.GetCurSel())
			{  
			case 0: dcb.BaudRate = CBR_1200;    break;
			case 1: dcb.BaudRate = CBR_2400;    break;	        
			case 2: dcb.BaudRate = CBR_4800;    break;
			case 3: dcb.BaudRate = CBR_9600;    break;	        
			case 4: dcb.BaudRate = CBR_14400;    break;
			case 5: dcb.BaudRate = CBR_19200;    break;	        
			case 6: dcb.BaudRate = CBR_38400;    break;
			case 7: dcb.BaudRate = CBR_56000;    break;	        
			case 8: dcb.BaudRate = CBR_57600;    break;
			case 9: dcb.BaudRate = CBR_115200;    break;	        
			default: dcb.BaudRate = CBR_9600;    break;	        	            	         
			}
			dcb.ByteSize = 8;
			dcb.Parity = NOPARITY; 
			dcb.fParity  = 0;  
			dcb.StopBits = ONESTOPBIT;    
			dcb.fBinary  = TRUE ;		
		}
		if (bComError == FALSE)
		{
		    bResult = SetCommState(g_hCOMDevice, &dcb );		// set COM with dcb
		    if (bResult == 0)
			{
			    //ShowErrorMessage(GetLastError());
				SetDlgItemText(IDC_EDT_STATUS, "Fail Connect !");
			    CloseHandle(g_hCOMDevice);
			    g_hCOMDevice = INVALID_HANDLE_VALUE;
			    bComError = TRUE;
			}
			else
			{
			    GetDlgItem(IDC_BTN_DISCONNECT)->EnableWindow(TRUE);
				GetDlgItem(IDC_BTN_WRITE_BYTES)->EnableWindow(TRUE);
				GetDlgItem(IDC_BTN_READ_BYTES)->EnableWindow(TRUE);
				GetDlgItem(IDC_BTN_CONNECT)->EnableWindow(FALSE);
				SetDlgItemText(IDC_EDT_STATUS, "Connect !");
			}
		}			
    }	
}

void CMegawinEasyUSBDlg::OnBtnDisconnect() 
{
	// TODO: Add your control notification handler code here
    int DeviceTypeIndex = 0;
	DWORD dwResult = 0;
	BOOL bResult;

    DeviceTypeIndex = m_cboDeviceType.GetCurSel();
    if (DeviceTypeIndex == EASYPOD_INDEX)
    {
        if ((g_EasyPOD.Handle != NULL) && (g_EasyPOD.Handle != INVALID_HANDLE_VALUE))
		{
	        dwResult = pDisconnectPOD(&g_EasyPOD);
			if (dwResult == ERROR_SUCCESS)			
                SetDlgItemText(IDC_EDT_STATUS, "Disonnect !");		     					
			else
				SetDlgItemText(IDC_EDT_STATUS, "Disonnect fail!");	
			GetDlgItem(IDC_BTN_DISCONNECT)->EnableWindow(FALSE);
			GetDlgItem(IDC_BTN_CONNECT)->EnableWindow(TRUE);
			GetDlgItem(IDC_BTN_WRITE_BYTES)->EnableWindow(FALSE);
			GetDlgItem(IDC_BTN_READ_BYTES)->EnableWindow(FALSE);
		} 
    }
    else
    {
        if ((g_hCOMDevice != NULL) && (g_hCOMDevice != INVALID_HANDLE_VALUE))
		{
			bResult = CloseHandle(g_hCOMDevice);
            if (bResult != 0)			
                SetDlgItemText(IDC_EDT_STATUS, "Disonnect !");		     								
			else
                SetDlgItemText(IDC_EDT_STATUS, "Disonnect fail!");	
			GetDlgItem(IDC_BTN_DISCONNECT)->EnableWindow(FALSE);
			GetDlgItem(IDC_BTN_CONNECT)->EnableWindow(TRUE);
			GetDlgItem(IDC_BTN_WRITE_BYTES)->EnableWindow(FALSE);
			GetDlgItem(IDC_BTN_READ_BYTES)->EnableWindow(FALSE);
		}
    }	
}

DWORD CMegawinEasyUSBDlg::ShowErrorMessage(DWORD dwErrorCode)
{
	LPVOID lpMsgBuf;
	FormatMessage( 
					FORMAT_MESSAGE_ALLOCATE_BUFFER | 
					FORMAT_MESSAGE_FROM_SYSTEM | 
					FORMAT_MESSAGE_IGNORE_INSERTS,
					NULL,
					//GetLastError(),
					dwErrorCode,
					MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
					(LPTSTR) &lpMsgBuf,
					0,
					NULL 
					);
	// Process any inserts in lpMsgBuf.
	// ...
	// Display the string.
	MessageBox( (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
	// Free the buffer.
	LocalFree( lpMsgBuf );

	return ERROR_SUCCESS;
}

void CMegawinEasyUSBDlg::OnRdoHex() 
{
	// TODO: Add your control notification handler code here
	if (static_cast<CButton *>(GetDlgItem(IDC_RDO_HEX))->GetCheck() == 1)
	{
        m_edtWriteBuffer.ModifyStyle(0, ES_UPPERCASE, 0);
		m_edtWriteBuffer.SetMode(1);
		m_edtWriteBuffer.SetWindowText("");
        m_edtReadBuffer.ModifyStyle(0, ES_UPPERCASE, 0);
		m_edtReadBuffer.SetMode(1);
		m_edtReadBuffer.SetWindowText("");
	}
}

void CMegawinEasyUSBDlg::OnRdoString() 
{
	// TODO: Add your control notification handler code here
	if (static_cast<CButton *>(GetDlgItem(IDC_RDO_STRING))->GetCheck() == 1)
	{
        m_edtWriteBuffer.ModifyStyle(ES_UPPERCASE, 0, 0);
		m_edtWriteBuffer.SetMode(0);
		m_edtWriteBuffer.SetWindowText("");
        m_edtReadBuffer.ModifyStyle(ES_UPPERCASE, 0, 0);
		m_edtReadBuffer.SetMode(0);
		m_edtReadBuffer.SetWindowText("");
	}
 	
}

void CMegawinEasyUSBDlg::OnBtnWriteBytes() 
{
	// TODO: Add your control notification handler code here
	PTBYTE pTxData = NULL;
	int i = 0, j = 0;
	CString strTmp;
    DWORD dwByteToWrite = 0;
	DWORD dwByteWritten = 0;
    int DeviceTypeIndex = 0;
	DWORD dwResult = 0;
	TCHAR tmpBuffer[MAX_PATH];

	UpdateData(TRUE);
	if (static_cast<CButton *>(GetDlgItem(IDC_RDO_HEX))->GetCheck() == 1)
	{
        m_strWriteBuffer.TrimRight();
		int size = m_strWriteBuffer.GetLength() / 3 + 1;
		pTxData = new BYTE[m_strWriteBuffer.GetLength() / 3 + 1];
		for(i=0,j=0 ; i < m_strWriteBuffer.GetLength() - 1 ; i=i+3,j++)
		{
           strTmp = m_strWriteBuffer.Mid(i,2);
           pTxData[j] = static_cast<BYTE>(_tcstoul(strTmp , NULL, 16)); 
		}
		dwByteToWrite = size; 
	}
	else
	{
		dwByteToWrite = m_strWriteBuffer.GetLength();
		pTxData = (BYTE*)m_strWriteBuffer.GetBuffer(m_strWriteBuffer.GetLength());
	}
    DeviceTypeIndex = m_cboDeviceType.GetCurSel();
    if (DeviceTypeIndex == EASYPOD_INDEX)
    {
        if ((g_EasyPOD.Handle != NULL) && (g_EasyPOD.Handle != INVALID_HANDLE_VALUE))
		{
           dwResult = pWriteData(&g_EasyPOD, pTxData, dwByteToWrite, &dwByteWritten);
		   if (dwResult == ERROR_SUCCESS)
		   {
			   sprintf(tmpBuffer, _T("Write return size is : %u"), dwByteWritten);
               SetDlgItemText(IDC_EDT_STATUS, tmpBuffer);
		   }
		} 
    }
    else
    {
        if ((g_hCOMDevice != NULL) && (g_hCOMDevice != INVALID_HANDLE_VALUE))
		{
            dwResult = WriteFile( g_hCOMDevice ,
			    				  pTxData ,
                                  dwByteToWrite ,
                                  &dwByteWritten ,     // Why always return "0" ??
                                  NULL
                                );
			if (dwResult != 0)
			{
			   sprintf(tmpBuffer, _T("Write return size is : %u"), dwByteWritten);
               SetDlgItemText(IDC_EDT_STATUS, tmpBuffer);
			}			
		}
    }
}

void CMegawinEasyUSBDlg::OnBtnReadBytes() 
{
	// TODO: Add your control notification handler code here
    DWORD dwByteToRead = 0;
	DWORD dwByteRead = 0;
    int DeviceTypeIndex = 0;
	DWORD dwResult = 0;
	DWORD dwSize = 0;
	PBYTE pRxBuffer = NULL;
	PCHAR pTmpBuffer = NULL;
	TCHAR tmpBuffer[MAX_PATH];
    COMSTAT comstat;

	pRxBuffer = new BYTE[0x10000];
	memset(pRxBuffer, 0, 0x10000);
	if (pRxBuffer == NULL)
	    SetDlgItemText(IDC_EDT_STATUS, _T("Allocate memory buffer fail !"));	
    DeviceTypeIndex = m_cboDeviceType.GetCurSel();
    if (DeviceTypeIndex == EASYPOD_INDEX)
    {
        if ((g_EasyPOD.Handle != NULL) && (g_EasyPOD.Handle != INVALID_HANDLE_VALUE))
		{
		    dwByteToRead = 1;
			dwByteRead = 0;
			dwSize = 0;
		    do
			{
                dwResult = pReadData(&g_EasyPOD, pRxBuffer + dwSize, dwByteToRead, &dwByteRead);
		        if ((dwResult == ERROR_SUCCESS) && (dwByteRead == 1))
				{
					dwSize++;
				}
			}
		    while( dwResult == ERROR_SUCCESS);
			sprintf(tmpBuffer, _T("Read return size is : %u"), dwSize);
            SetDlgItemText(IDC_EDT_STATUS, tmpBuffer);
		} 
    }
    else
    {
        if ((g_hCOMDevice != NULL) && (g_hCOMDevice != INVALID_HANDLE_VALUE))
		{			
            dwByteRead = 0;
			dwByteToRead = 0;
            ClearCommError(g_hCOMDevice, &dwResult, &comstat);            
			if (comstat.cbInQue > 0)
                dwByteToRead = comstat.cbInQue;
            dwResult = ReadFile( g_hCOMDevice ,
			    				 pRxBuffer ,
                                 dwByteToRead ,
                                 &dwSize ,     // Why always return "0" ??
                                 NULL
                               );
			if (dwResult != 0)
			{
			   sprintf(tmpBuffer, _T("Read return size is : %u"), dwSize);
               SetDlgItemText(IDC_EDT_STATUS, tmpBuffer);
			}			
		}
    }	
	if (dwSize > 0)
	{
		if (static_cast<CButton *>(GetDlgItem(IDC_RDO_HEX))->GetCheck() == 1)
		{
            pTmpBuffer = new CHAR[dwSize*3+1];
			
			if (pTmpBuffer != NULL)
			{
                for(DWORD i = 0 ; i < dwSize ; i++)
				{
                    sprintf(pTmpBuffer + i*3, "%02X ", *(pRxBuffer+i));
				}
				*(pTmpBuffer + i*3 - 1) = '\0';
			}
			SetDlgItemText(IDC_EDT_READ_BUFFER, pTmpBuffer);
			delete []pTmpBuffer;
		}
		else
		{
            SetDlgItemText(IDC_EDT_READ_BUFFER, (const char *)pRxBuffer);
		}
	}
	delete []pRxBuffer;
}
