                                          // cabrio_downloaderv01Dlg.cpp : implementation file
//

#include "stdafx.h"
#include "cabrio_downloaderv01.h"
#include "cabrio_downloaderv01Dlg.h"
#include "norflashdrv.h"
#include "windows.h"
#include "OKDialog.h"
#include "TFSDialog.h"
#include "VerDialog.h"
#include "DumpDialog.h"
#include "DescriptionSaveCheck.h"
#include "BootloaderDlg.h"
#include "NorDumpDialog.h"
#include "NandDump.h"
#include "math.h"
#include "flashloader_USB.h"
//#include "TfsExplorer.h"

//#define _INCLUDE_CALSET_
#define _MULTI_DOWNLOADER_
#define _DWL_BOOTLOADER_

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

#include "tool_api.h"
#include "Env.h"


ToolProgressCb_t ToolProgressCb;
ToolProgressCbDump_t ToolProgressCbDump;
ToolFileHandleCb_t ToolFileHandleCb;

int check=0;

//HWND hCommWnd;
//CCommThread gSerialPort;

const UINT gComPort[] = { 1, 2, 3, 4, 5, 6, 7, 8 ,9,10,11,12,13,14,15,16,17,18,19,20};
const UINT gComSpeed[] = { CBR_115200, 230400, 460800, 921600 };

int g_nProgressCounter =0;
int g_nDownloadedSector = 0;

BYTE g_BaudRate[3] = {
	COMPORT_BAUDRATE_115K,
	COMPORT_BAUDRATE_460K,
	COMPORT_BAUDRATE_921K

};

static UInt8 cActionType;   // κ ٿε 
static UInt8 cDriverStatus;

UINT TfsExplorerThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;
	CString str;

	pDlg->TfsExplorer(cActionType);

	return true;
}

UINT TimeThread(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;
	CString str;

	pDlg->TfsExplorer(cActionType);

	return true;
}


UINT BadBlkChkThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;
	CString str;

//	pDlg->BadBlkChk();

	return true;
}

UINT MakeThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;
	CString str;

	pDlg->MakeNewFormat(0);

	return true;
}

UINT BackThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;
	CString str;

	pDlg->BackTheData(0);

	return true;
}
UINT AutoDownloadThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;
	CString str;
	int nResult;
	pDlg->m_nMainPercent = 0;
	g_nDownloadedSector=0;

	nResult=pDlg->ConnectWithMS();
	pDlg->ShowMessage_ConnectWithMS(nResult);
	if (nResult!=CON_SUCCESS)
		return true;

	switch (cActionType)
	{
		case DWL_ALL:
			g_nDownloadedSector = pDlg->GetSectorNum(IMGSET_START_ADDR,pDlg->m_nImageSize)
				+pDlg->GetSectorNum2(RSRC1_START_ADDR,pDlg->m_nRscrSize) 
				+pDlg->GetSectorNum2(RSRC2_START_ADDR,pDlg->m_nRscr2Size)
				+pDlg->GetSectorNum2(FACTORYFS_START_ADDR,pDlg->m_nFactoryFSSize);
			//case including calset file
			if (pDlg->m_boolCalset==TRUE)
			{
				g_nDownloadedSector+=pDlg->GetSectorNum(CALSET_START_ADDR,pDlg->m_nParamDepSize);
			}
			
			g_nProgressCounter = 0;

			if (pDlg->NorDownload(DWL_IMGSET,1)==false)	return true;

			//Calset ϴ üũ
			if (pDlg->m_boolCalset==TRUE)
			{
				if (pDlg->NorDownload(DWL_CALSET,1)==false) return true;
			}


			pDlg->DisconnectMS();
			
			if (pDlg->Erase(cActionType)==false) return true;

			if (pDlg->NandDownload(DWL_RSRC1,1)==false)	return true;
			if (pDlg->NandDownload(DWL_RSRC2,1)==false) return true;
			if (pDlg->NandDownload(DWL_FACTORYFS,1)==false) return true;

			pDlg->ShowTotalTime();
			
			return true;
			break;
		default:
			break;
	}
	return true;

}

UINT AllDownloadThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;
	CString str;

	
	pDlg->m_nMainPercent = 0;
	g_nDownloadedSector=0;
	switch (cActionType)
	{
		case DWL_ALL:
			g_nDownloadedSector = pDlg->GetSectorNum(IMGSET_START_ADDR,pDlg->m_nImageSize)
				+pDlg->GetSectorNum2(RSRC1_START_ADDR,pDlg->m_nRscrSize) 
				+pDlg->GetSectorNum2(RSRC2_START_ADDR,pDlg->m_nRscr2Size)
				+pDlg->GetSectorNum2(FACTORYFS_START_ADDR,pDlg->m_nFactoryFSSize);
			
			//case including calset file
			if (pDlg->m_boolCalset==TRUE)
			{
				g_nDownloadedSector+=(pDlg->GetSectorNum(CALSET_START_ADDR,pDlg->m_nParamDepSize)+1);
			}

			g_nProgressCounter = 0;

			
			if (pDlg->NorDownload(DWL_IMGSET,2)==false) return true;
			pDlg->DisplayButton(CURRENT_NOR_DRIVER,1,IMGSET_START_ADDR);
			if (pDlg->m_boolCalset==TRUE)
			{
				if (pDlg->NorDownload(DWL_CALSET,2)==false) return true;
				pDlg->DisplayButton(CURRENT_NOR_DRIVER,1,CALSET_START_ADDR);
			}


			
			pDlg->DisconnectMS();

			pDlg->DisplayButton(CURRENT_NOR_DRIVER,1,IMGSET_START_ADDR);
			if (pDlg->m_boolCalset==TRUE)
			{
				pDlg->DisplayButton(CURRENT_NOR_DRIVER,1,CALSET_START_ADDR);
			}

			if (pDlg->Erase(cActionType)==false) return true;
			pDlg->DisplayButton(CURRENT_NOR_DRIVER,1,IMGSET_START_ADDR);
			if (pDlg->m_boolCalset==TRUE)
			{
				pDlg->DisplayButton(CURRENT_NOR_DRIVER,1,CALSET_START_ADDR);
			}
			if (pDlg->nConnectMode==UART_MODE)
				Sleep(1000*3);

			if (pDlg->NandDownload(DWL_RSRC1,2)==false)	return true;
			pDlg->DisplayButton(CURRENT_NAND_DRIVER,1,RSRC1_START_ADDR);
			Sleep(1000);
			if (pDlg->NandDownload(DWL_RSRC2,2)==false)	return true;
			pDlg->DisplayButton(CURRENT_NAND_DRIVER,1,RSRC2_START_ADDR);
			Sleep(1000);
			if (pDlg->NandDownload(DWL_FACTORYFS,2)==false)	return true;


			pDlg->ShowTotalTime();
			
			return true;
			break;
		default:
			break;
	}
	return true;

}

UINT DlbootloaderThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;

	//int result;
	//pDlg->ShowStatus("\n  * Change to Download ready state",4);
	pDlg->Dlbootloader();
	return true;
}

UINT DisconnectThread(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;

	pDlg->ShowStatus("\n  * Change to Download ready state",4);
	pDlg->DisconnectMS();
	return true;
}

UINT ConnectionThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;
	
	pDlg->ShowStatus("\n  * Connecting to target phone",4);
	pDlg->st.Format("\n     Try to open COM%d\t>",pDlg->m_ComPort+1);
	pDlg->ShowStatus(pDlg->st,3);
//	pDlg->ShowStatus("\n    Listen for the Download Mode signal of target phone.....");
	pDlg->nCon_Result=pDlg->ConnectWithMS();
	pDlg->ShowMessage_ConnectWithMS(pDlg->nCon_Result);
	return true;

}

UINT NorDownloadThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;
	CString str;
	
	pDlg->m_nMainPercent = 0;
	g_nDownloadedSector=0;

	switch (cActionType)
	{
		case DWL_ALL:
			g_nDownloadedSector = pDlg->GetSectorNum(IMGSET_START_ADDR,pDlg->m_nImageSize)+8;

			if (pDlg->m_boolCalset==TRUE)
				g_nDownloadedSector+=(pDlg->GetSectorNum(CALSET_START_ADDR,pDlg->m_nParamDepSize)+1);

			g_nProgressCounter = 0;


			if (pDlg->NorDownload(DWL_IMGSET,1)==false) return true;

			if (pDlg->m_boolCalset==TRUE)
			{
				if(pDlg->NorDownload(DWL_CALSET,1)==false) return true;
			}


			pDlg->ShowTotalTime();
			return true;
			break;

		case DWL_IMGSET:
			g_nDownloadedSector = (pDlg->GetSectorNum(IMGSET_START_ADDR,pDlg->m_nImageSize));
			break;

		case DWL_CALSET:
			g_nDownloadedSector = (pDlg->GetSectorNum(CALSET_START_ADDR,pDlg->m_nParamDepSize));
			break;

		case DWL_MANUAL:
			g_nDownloadedSector = (pDlg->GetSectorNum(pDlg->m_fAddress,pDlg->m_nManulImageSize));
			break;

		default:
			break;
	}

	g_nProgressCounter = 0;

	//Driver Downloading
	pDlg->NorDownload(cActionType,0);
	

	return true;
}


UINT EraseThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;

	pDlg->Erase(cActionType);

	return true;
}

UINT NorEraseThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;

	pDlg->m_nMainPercent = 0;
	g_nProgressCounter = 0;

	if (cActionType==OP_ERASE_BOOTLOADER)
		g_nDownloadedSector = pDlg->GetSectorNum(0,0x10000);
	else
		g_nDownloadedSector = pDlg->GetSectorNum(IMGSET_START_ADDR,0x1FE0000);
	pDlg->NorErase(cActionType);

	return true;
}

UINT NorDumpThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;

	pDlg->m_nMainPercent = 0;
	g_nProgressCounter = 0;
	pDlg->NorDump(cActionType);

	return true;
}

UINT NandDumpThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;

	pDlg->m_nMainPercent = 0;
	g_nProgressCounter = 0;
	pDlg->NandDump(cActionType);

	return true;
}

UINT TFSFormatThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;

	pDlg->TFS_Format(0);

	return true;
}

UINT BadBlkCheckThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;

	pDlg->BadBlkCheck();

	return true;
}



UINT NandDownloadThreadFunc(LPVOID pParam)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)pParam;
	CString str;
	
	pDlg->m_nMainPercent = 0;
	switch (cActionType)
	{
		case DWL_ALL:
			g_nDownloadedSector = pDlg->GetSectorNum2(RSRC1_START_ADDR,pDlg->m_nRscrSize) +
									pDlg->GetSectorNum2(RSRC2_START_ADDR,pDlg->m_nRscr2Size)+
									pDlg->GetSectorNum2(FACTORYFS_START_ADDR,pDlg->m_nFactoryFSSize);
							
			g_nProgressCounter = 0;

			/*NandDownload(cActionType,A,B)
			A --> 1  (Driver Downloading)
			  --> 0  (Without Driver Downloading);
			B --> 1  (All Downloading setting);*/

			if (pDlg->NandDownload(DWL_RSRC1,1)==false) return true;
			Sleep(1000);
			if (pDlg->NandDownload(DWL_RSRC2,1)==false) return true;
			Sleep(1000);
			if (pDlg->NandDownload(DWL_FACTORYFS,1)==false) return true;

			pDlg->ShowTotalTime();

			return true;
			break;
	
		case DWL_RSRC1:
			g_nDownloadedSector = pDlg->GetSectorNum2(RSRC1_START_ADDR,pDlg->m_nRscrSize);
			break;

		case DWL_RSRC2:
			g_nDownloadedSector = pDlg->GetSectorNum2(RSRC2_START_ADDR,pDlg->m_nRscr2Size);
			break;

		case DWL_FACTORYFS:
			g_nDownloadedSector = pDlg->GetSectorNum2(FACTORYFS_START_ADDR,pDlg->m_nFactoryFSSize);
			break;

		case DWL_FLASHALL:
			g_nDownloadedSector = pDlg->GetSectorNum2(TFS_START_ADDR,pDlg->m_nEntireFlashSize);
			break;
		case DWL_MANUAL_NAND:
			g_nDownloadedSector = pDlg->GetSectorNum2(pDlg->m_fAddress,pDlg->m_nManualNandImageSize);
			break;

		default:
			break;
	}
	
	g_nProgressCounter = 0;
	pDlg->NandDownload(cActionType,0);

	return true;
}

void FileHandleCallBackFunc(UInt8 * m,unsigned long nSize)
{
	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)AfxGetApp()->m_pMainWnd;

	if( pDlg == NULL )
	{
		AfxMessageBox("ProgressCallBackFunc Error :");
	}
	pDlg->m_DumpFile.Write(m,nSize);
/*	if (m[0]==0xcc)
		AfxMessageBox("cc detected ..;;");*/

}

void DumpProgressCallBackFunc( Boolean endOfSector, UInt8 * m,unsigned long addr)
{

	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)AfxGetApp()->m_pMainWnd;

	int i=0;
	CString test;
	unsigned long temp;
	pDlg->m_ctrCN.EnableWindow(true);

	if( pDlg == NULL )
	{
		AfxMessageBox("ProgressCallBackFunc Error :");
	}

	if( endOfSector )
	{
		g_nProgressCounter++;
		pDlg->m_nMainPercent = (g_nProgressCounter * 100) / g_nDownloadedSector;
		pDlg->m_progressMain.SetPos(pDlg->m_nMainPercent);


		temp=pDlg->temp_nfrom;

		test.Format(" %d / %d ",g_nProgressCounter,g_nDownloadedSector);
		pDlg->m_editSubStatus.SetWindowText(test);

		if (temp==0)
			test.Format("   0x0000 : \t");
		else
			test.Format("\n   0x%x : \t",addr);
		pDlg->ShowStatus(test);
		
		if (cActionType==OP_NAND_DUMP)
		{
		/*	for (i=0;i<64;i++)
			{
				test.Format(" %c",m[i]);
				pDlg->all_size++;
				if (m[i]=='b' && m[i+1]=='b')
					pDlg->ShowStatus(test,3);
				else
				{
					test.Format(" o");
					pDlg->ShowStatus(test,4);
					pDlg->used_size++;
				}
				i=i+2;
			}*/
			pDlg->temp_nfrom+=(long)aNandFlashTable[0].BlockSize;
//			pDlg->ShowStatus(test);
		}
		if (cActionType==OP_NOR_DUMP)
		{
			pDlg->temp_nfrom+=(long)aNorFlashTable[0].LargeBlockSize;

		}
					
		test.Format("   Dump   >>>   OK");
			pDlg->ShowStatus(test,3);
	//	pDlg->ShowStatus(test,5);

	}
}

void ProgressCallBackFunc( Boolean endOfSector,Boolean bChecksum, unsigned long lAddr,unsigned int nWrite,Boolean bErase)
{

	CCabrio_downloaderv01Dlg *pDlg = (CCabrio_downloaderv01Dlg*)AfxGetApp()->m_pMainWnd;
	CString test;
	pDlg->m_ctrCN.EnableWindow(true);
	if( pDlg == NULL )
	{
		AfxMessageBox("ProgressCallBackFunc Error : hCommWnd");
	}

	if (bChecksum)
	{
		//bChecksum TRUEϰ Ű lAddr Erroró  
		switch(lAddr)
		{
			case 0:
				pDlg->ShowStatus(" checksum : ");
				test.Format("0x%X\n",nWrite);
				pDlg->ShowStatus(test,4);
				break;
			case 1:
				pDlg->ShowStatus(" checksum ");
				pDlg->ShowStatus(" Error\n",4);
				break;
			case 2:
				//imgset, calset ߰  ٲ  ֱ
				pDlg->ShowStatus("\n");
				break;
			case 3:
				pDlg->ShowStatus(" Fail -> Resend data\n",4);
				break;
			case 4:
				pDlg->ShowStatus(" Sync error\n",4);
				break;
			case 5:
				pDlg->ShowStatus(" Invalid ACK received\n",4);
				break;
			case 6:
				pDlg->ShowStatus(" Not response at the target phone\n",4);
				break;
			default:
				// ü 
				pDlg->ShowStatus(" Unknown error\n",4);
				break;
		}
			
		return;
	}
	if( endOfSector )
	{
		g_nProgressCounter++;
		pDlg->m_nMainPercent = (g_nProgressCounter * 100) / g_nDownloadedSector;
		pDlg->m_progressMain.SetPos(pDlg->m_nMainPercent);
		
		test.Format(" %d / %d ",g_nProgressCounter,g_nDownloadedSector);
		pDlg->m_editSubStatus.SetWindowText(test);

		if (lAddr==0x0)
			//ּҰ 0x0϶ \t  ѹ  ش.
		{
			if (bErase)
				pDlg->st.Format("\r\n    0 x %X\t\t Erase   %d bytes\t. . . .    OK ",lAddr,nWrite);
			else
			pDlg->st.Format("    0 x %X\t\t Download   %d bytes\t. . . .  ",lAddr,nWrite);
		}
		else
		{	if (bErase)
				pDlg->st.Format("\r\n    0 x %X\t Erase   %d bytes\t. . . .    OK ",lAddr,nWrite);
		else
			pDlg->st.Format("    0 x %X\t Download   %d bytes\t. . . .  ",lAddr,nWrite);
		}

		pDlg->ShowStatus(pDlg->st);
		pDlg->DisplayButton(cDriverStatus,g_nProgressCounter%2,lAddr);

	}

}

/////////////////////////////////////////////////////////////////////////////
// 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()

/////////////////////////////////////////////////////////////////////////////
// CCabrio_downloaderv01Dlg dialog

CCabrio_downloaderv01Dlg::CCabrio_downloaderv01Dlg(CWnd* pParent /*=NULL*/)
	: CDialog(CCabrio_downloaderv01Dlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CCabrio_downloaderv01Dlg)
	m_radio = -1;
	m_boolECC = FALSE;
	m_boolAuto = FALSE;
	m_boolAutoReboot = FALSE;
	m_boolCalset = FALSE;
	m_radioMode = -1;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CCabrio_downloaderv01Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CCabrio_downloaderv01Dlg)
	DDX_Control(pDX, IDC_RICHEDIT_FLASHTYPE2, m_ctrlNandFlash);
	DDX_Control(pDX, IDC_BUTTON_MANUAL_NAND_IMAGE, m_btnManualNand);
	DDX_Control(pDX, IDC_BUTTON_MANUAL_IMAGE, m_btnManualNor);
	DDX_Control(pDX, IDC_EDIT_MANUAL_NAND_IMAGE_PATH, m_editManualNandImagePath);
	DDX_Control(pDX, IDC_EDIT_MANUAL_NAND, m_editManualNandAddress);
	DDX_Control(pDX, IDC_EDIT_DN, m_editDN);
	DDX_Control(pDX, IDC_EDIT_TIME, m_editTime);
	DDX_Control(pDX, IDC_EDIT_MANUAL_IMAGE_PATH, m_editManualImagePath);
	DDX_Control(pDX, IDC_EDIT_MANUAL, m_editManualAddress);
	DDX_Control(pDX, IDC_BUTTON_NOR_DUMP, m_ctrNorDump);
	DDX_Control(pDX, IDC_BUTTON_NOR_ALLERASE, m_ctrNorErase);
	DDX_Control(pDX, IDC_BUTTON_NAND_DUMP, m_ctrNandDump);
	DDX_Control(pDX, IDC_BUTTON_BOOTLOADER_ERASE, m_ctrBootloaderErase);
	DDX_Control(pDX, IDC_EDIT_ENTIRE_FLASH_PATH, m_editEntireFlashPath);
	DDX_Control(pDX, IDC_BUTTON_NAND_ENTIRE_FLASH, m_ctrEntireFlash);
	DDX_Control(pDX, IDC_BUTTON_BCHK, m_ctrlBChk);
	DDX_Control(pDX, IDC_BUTTON_INFO, m_btnInfo);
	DDX_Control(pDX, IDC_EDIT_SUBSTATUS, m_editSubStatus);
	DDX_Control(pDX, IDOK, m_idok);
	DDX_Control(pDX, IDC_BUTTON_DLBOOTLOADER, m_ctrlDlbootloader);
	DDX_Control(pDX, IDC_BUTTON_DISCONNECT, m_ctrlDisconnect);
	DDX_Control(pDX, IDC_RICHEDIT_CONNECT, m_ctrlConnect);
	DDX_Control(pDX, IDC_RICHEDIT_FLASHTYPE, m_ctrlNFlash);
	DDX_Control(pDX, IDC_BUTTON_START, m_ctrlStart);
	DDX_Control(pDX, IDC_EDIT_FILENAME, m_editFileName);
	DDX_Control(pDX, IDC_EDIT_CHECKSUM, m_editCheckSum);
	DDX_Control(pDX, IDC_EDIT_FILESIZE, m_editFileSize);
	DDX_Control(pDX, IDC_BUTTON_TFS_FORMAT, m_ctrTFSFormat);
	DDX_Control(pDX, IDC_BUTTON_CABRIO, m_ctrCabrio);
	DDX_Control(pDX, IDC_BUTTON_TITLE, m_ctrTitle);
	DDX_Control(pDX, IDC_BUTTON_CN, m_ctrCN);
	DDX_Control(pDX, IDC_BUTTON_SYSPARM_DEP, m_ctrSysDep);
	DDX_Control(pDX, IDC_BUTTON_CAP, m_ctrCap);
	DDX_Control(pDX, IDC_BUTTON_NAND_FACTORYFS, m_ctrFactoryFS);
	DDX_Control(pDX, IDC_BUTTON_NAND_RSCR2, m_ctrRscr2);
	DDX_Control(pDX, IDC_BUTTON_NAND_RSCR, m_ctrRscr);
	DDX_Control(pDX, IDC_PROGRESS_MAIN, m_progressMain);
	DDX_Control(pDX, IDC_BUTTON_DOWNLOAD2, m_ctrDownloadButton);
	DDX_Control(pDX, IDC_EDIT_RSCR2_PATH, m_editRscr2Path);
	DDX_Control(pDX, IDC_EDIT_RSCR_PATH, m_editRscrPath);
	DDX_Control(pDX, IDC_EDIT_PARAM_DEP_PATH, m_editParamDepPath);
	DDX_Control(pDX, IDC_EDIT_FACTORYFS_PATH, m_editFactoryFSPath);
	DDX_Control(pDX, IDC_RICHEDIT_STATUS, m_editStatus);
	DDX_Control(pDX, IDC_BUTTON_PHONE_IMAGE, m_ctrPhoneImage);
	DDX_Control(pDX, IDC_COMBO_BAUDRATE, m_cbxBaudRate);
	DDX_Control(pDX, IDC_EDIT_IMAGE_PATH, m_editImagePath);
	DDX_Control(pDX, IDC_COMBO_COMPORT, m_ctrlComPort);
	DDX_Radio(pDX, IDC_RADIO3, m_radio);
	DDX_Check(pDX, IDC_CHECK_ECC, m_boolECC);
	DDX_Check(pDX, IDC_CHECK_AUTO, m_boolAuto);
	DDX_Check(pDX, IDC_CHECK_AUTO_REBOOT, m_boolAutoReboot);
	DDX_Check(pDX, IDC_CHECK_CALSET, m_boolCalset);
	DDX_Radio(pDX, IDC_RADIO_UART, m_radioMode);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CCabrio_downloaderv01Dlg, CDialog)
	//{{AFX_MSG_MAP(CCabrio_downloaderv01Dlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_CBN_SELCHANGE(IDC_COMBO_COMPORT, OnSelchangeComboComport)
	ON_BN_CLICKED(IDC_BUTTON_PHONE_IMAGE, OnButtonPhoneImage)
	ON_CBN_SELCHANGE(IDC_COMBO_BAUDRATE, OnSelchangeComboBaudrate)
	ON_BN_CLICKED(IDC_BUTTON_NAND_RSCR, OnButtonNandRscr)
	ON_BN_CLICKED(IDC_BUTTON_NAND_RSCR2, OnButtonNandRscr2)
	ON_BN_CLICKED(IDC_BUTTON_NAND_FACTORYFS, OnButtonNandFactoryfs)
	ON_BN_CLICKED(IDC_BUTTON_SYSPARM_DEP, OnButtonSysparmDep)
	ON_BN_CLICKED(IDC_BUTTON_DOWNLOAD2, OnButtonDownload2)
	ON_BN_CLICKED(IDC_BUTTON_CAP, OnButtonCap)
	ON_BN_CLICKED(IDC_BUTTON2, OnButtonCN)
	ON_WM_CTLCOLOR()
	ON_BN_CLICKED(IDC_BUTTON_TITLE, OnButtonTitle)
	ON_BN_CLICKED(IDC_BUTTON_TFS_FORMAT, OnButtonTfsFormat)
	ON_BN_CLICKED(IDC_BUTTON_START, OnButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_DISCONNECT, OnButtonDisconnect)
	ON_BN_CLICKED(IDC_BUTTON_DLBOOTLOADER, OnButtonDlbootloader)
	ON_BN_CLICKED(IDC_BUTTON_CABRIO, OnButtonCabrio)
	ON_BN_CLICKED(IDC_BUTTON_INFO, OnButtonInfo)
	ON_BN_CLICKED(IDC_BUTTON_BCHK, OnButtonBchk)
	ON_BN_CLICKED(IDC_BUTTON_NOR_DUMP, OnButtonNorDump)
	ON_BN_CLICKED(IDC_BUTTON_NAND_DUMP, OnButtonNandDump)
	ON_BN_CLICKED(IDC_BUTTON_BOOTLOADER_ERASE, OnButtonBootloaderErase)
	ON_BN_CLICKED(IDC_BUTTON_NOR_ALLERASE, OnButtonNorAllerase)
	ON_BN_CLICKED(IDC_BUTTON_NAND_ENTIRE_FLASH, OnButtonNandEntireFlash)
	ON_EN_CHANGE(IDC_EDIT_MANUAL, OnChangeEditManual)
	ON_BN_CLICKED(IDC_BUTTON_MANUAL_IMAGE, OnButtonManualImage)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BUTTON_MANUAL_NAND_IMAGE, OnButtonManualNandImage)
	ON_EN_CHANGE(IDC_EDIT_MANUAL_NAND, OnChangeEditManualNand)
	ON_BN_CLICKED(IDC_RADIO_UART, OnRadioUart)
	ON_BN_CLICKED(IDC_RADIO_USB, OnRadioUsb)
	ON_BN_CLICKED(IDC_BUTTON_CAL_INFO, OnButtonCalInfo)
	ON_BN_CLICKED(IDC_BUTTON_RSRC_INFO, OnButtonRsrcInfo)
	ON_BN_CLICKED(IDC_BUTTON_RSRC2_INFO, OnButtonRsrc2Info)
	ON_WM_CANCELMODE()
	ON_BN_CLICKED(IDC_BUTTON_FAC_INFO, OnButtonFacInfo)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CCabrio_downloaderv01Dlg message handlers

BOOL CCabrio_downloaderv01Dlg::OnInitDialog()
{
	

	CDialog::OnInitDialog();
    CString str;
	// 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
	ToolProgressCb = ProgressCallBackFunc;
	ToolProgressCbDump = DumpProgressCallBackFunc;
	ToolFileHandleCb = FileHandleCallBackFunc;
//	hCommWnd = this->m_hWnd;

	m_ComPort = AfxGetApp()->GetProfileInt("CabrioDL", "m_nPort", m_ComPort);
	m_ctrlComPort.SetCurSel(m_ComPort);

	m_nBaudRate = AfxGetApp()->GetProfileInt("CabrioDL", "m_nBaudRate", m_nBaudRate);
	m_cbxBaudRate.SetCurSel(m_nBaudRate);
	


	m_nDownloadNum=AfxGetApp()->GetProfileInt("CabrioDL","m_nDownloadNum",m_nDownloadNum);

	if(m_nDownloadNum<0 || m_nDownloadNum>10000)
		m_nDownloadNum=0;

	str.Format("%d",m_nDownloadNum);
	m_editDN.SetWindowText(str);


	m_boolECC = FALSE; //ECC 
	
	bConnect=false;
	m_editStatus.EnableWindow(true);
	m_editSubStatus.EnableWindow(true);
	m_ctrCN.EnableWindow(false);

	str.Format("  Disconnect");
	ShowEnv(str,4);

	str.Format("  Disconnect");
	ShowEnv(str,3);
	
	totaltime=0;

	m_fAddress=0;
	SetDlgItemText(IDC_EDIT_MANUAL,"0");
	SetDlgItemText(IDC_EDIT_MANUAL_NAND,"0");

	
	
  //  m_my_brush.CreateSolidBrush(RGB(0,0,255)); // Brush Ӽ Ѵ.



	
	InitVariables();
//	LockControls();
	
	pThread=NULL;
	RestoreProgramSetting();


	 m_font.CreateFont( // m_font  Ŭ   ִٰ 
        35, // nHeight 
         10, // nWidth 
         1, // nEscapement 
         5, // nOrientation 
         1, // nWeight 
         0, // bItalic 
         0, // bUnderline 
         0, // cStrikeOut 
         0, // nCharSet 
         OUT_DEFAULT_PRECIS, // nOutPrecision 
         0, // nClipPrecision 
         DEFAULT_QUALITY, // nQuality 
         DEFAULT_PITCH | FF_DONTCARE, // nPitchAndFamily 
   //      "Fixedsys" // lpszFacename 
		   "Arial Black"
    ); 
    //
	 
	 m_font2.CreateFont( // m_font  Ŭ   ִٰ 
        20, // nHeight 
        9, // nWidth 
         1, // nEscapement 
         0, // nOrientation 
         0, // nWeight 
         0, // bItalic 
         0, // bUnderline 
         0, // cStrikeOut 
         0, // nCharSet 
         OUT_DEFAULT_PRECIS, // nOutPrecision 
         0, // nClipPrecision 
         DEFAULT_QUALITY, // nQuality 
         DEFAULT_PITCH | FF_DONTCARE, // nPitchAndFamily 
        "Arial" // lpszFacename 
//		   "Tahoma"
    ); 

	 m_font3.CreateFont( // m_font  Ŭ   ִٰ 
        15, // nHeight 
        7, // nWidth 
         1, // nEscapement 
         0, // nOrientation 
         0, // nWeight 
         0, // bItalic 
         0, // bUnderline 
         0, // cStrikeOut 
         0, // nCharSet 
         OUT_DEFAULT_PRECIS, // nOutPrecision 
         0, // nClipPrecision 
         DEFAULT_QUALITY, // nQuality 
         DEFAULT_PITCH | FF_DONTCARE, // nPitchAndFamily 
        "Arial" // lpszFacename 
//		   "Tahoma"
    ); 

	 m_font4.CreateFont( // m_font  Ŭ   ִٰ 
        16, // nHeight 
        6, // nWidth 
         1, // nEscapement 
         0, // nOrientation 
         0, // nWeight 
         0, // bItalic 
         0, // bUnderline 
         0, // cStrikeOut 
         0, // nCharSet 
         OUT_DEFAULT_PRECIS, // nOutPrecision 
         0, // nClipPrecision 
         DEFAULT_QUALITY, // nQuality 
         DEFAULT_PITCH | FF_DONTCARE, // nPitchAndFamily 
        "Verdana Black" // lpszFacename 
//		   "Tahoma"
    );

	 m_font5.CreateFont( // m_font  Ŭ   ִٰ 
        20, // nHeight 
        7, // nWidth 
         1, // nEscapement 
         0, // nOrientation 
         90, // nWeight 
         0, // bItalic 
         0, // bUnderline 
         0, // cStrikeOut 
         0, // nCharSet 
         OUT_DEFAULT_PRECIS, // nOutPrecision 
         0, // nClipPrecision 
         DEFAULT_QUALITY, // nQuality 
         DEFAULT_PITCH | FF_DONTCARE, // nPitchAndFamily 
        "Arial Black" // lpszFacename 
//		   "Tahoma"
    );

	m_font6.CreateFont( // m_font  Ŭ   ִٰ 
        14, // nHeight 
        5, // nWidth 
         0, // nEscapement 
         0, // nOrientation 
         0, // nWeight 
         0, // bItalic 
         0, // bUnderline 
         0, // cStrikeOut 
         0, // nCharSet 
         OUT_DEFAULT_PRECIS, // nOutPrecision 
         0, // nClipPrecision 
         DEFAULT_QUALITY, // nQuality 
         DEFAULT_PITCH | FF_DONTCARE, // nPitchAndFamily 
        "Arial" // lpszFacename 
//		   "Tahoma"
    );

	m_font7.CreateFont( // m_font  Ŭ   ִٰ 
        15, // nHeight 
        6, // nWidth 
         0, // nEscapement 
         0, // nOrientation 
         0, // nWeight 
         0, // bItalic 
         0, // bUnderline 
         0, // cStrikeOut 
         0, // nCharSet 
         OUT_DEFAULT_PRECIS, // nOutPrecision 
         0, // nClipPrecision 
         DEFAULT_QUALITY, // nQuality 
         DEFAULT_PITCH | FF_DONTCARE, // nPitchAndFamily 
        "Arial" // lpszFacename 
//		   "Tahoma"
    ); 

//	m_font6.CreatePointFont(75,"Arial");
	//ư Ʈ 
	 m_ctrCabrio.SetFont(&m_font, TRUE);

//	m_ctrCN.SetFont(&m_font3, TRUE);               
//	m_ctrDownloadButton.SetFont(&m_font3, TRUE);
//	m_ctrTitle.SetFont(&m_font3, TRUE);
	//m_ctrCap.SetFont(&m_font3, TRUE);
//	m_ctrTFSFormat.SetFont(&m_font3, TRUE);
//	m_ctrCN.SetFont(&m_font3, TRUE);
	m_ctrlStart.SetFont(&m_font3,TRUE);
//	m_ctrlSetDS.SetFont(&m_font3,TRUE);
//	m_ctrlGetDS.SetFont(&m_font3,TRUE);
//	m_ctrlDisconnect.SetFont(&m_font3,TRUE);
//	m_ctrlDlbootloader.SetFont(&m_font3,TRUE);
//	m_idok.SetFont(&m_font3,TRUE);
	m_editTime.SetFont(&m_font7, TRUE);
	SetTimer(0,1000,NULL);
	ReadyControls();
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CCabrio_downloaderv01Dlg::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 CCabrio_downloaderv01Dlg::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 CCabrio_downloaderv01Dlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

/*
void CCabrio_downloaderv01Dlg::OnCommRead(WPARAM wParam, LPARAM lParam)
{
	BYTE ch;
	static DWORD TFSsize;
	CString strTemp;
	int count = 0;

#if 0
	while ( gSerialPort.m_QueueRead.GetByte( &ch ) )
	{
		if( ch != '\r' )
		{
			if( count % 10 == 0 )
			{
			strTemp.Format("%c",ch);
		m_ctrlRichEditBox.SetSel(-1,-1);
		m_ctrlRichEditBox.ReplaceSel(strTemp);
			}
			count++;
		}

	}
	#endif
}
*/

void CCabrio_downloaderv01Dlg::OnSelchangeComboComport() 
{
	// TODO: Add your control notification handler code here
	m_ComPort = m_ctrlComPort.GetCurSel();
	AfxGetApp()->WriteProfileInt("CabrioDL", "m_nPort", m_ComPort );	
	
}

void CCabrio_downloaderv01Dlg::OnButtonPhoneImage() 
{
	// TODO: Add your control notification handler code here
		// TODO: Add your control notification handler code here
	char szFilter[] = "Image File(*.img)|*.img|*.*|*.*||";
	CFile File;
	UInt8 * v_code=new UInt8[4];
	CFileDialog dlg(TRUE, NULL, m_strImageFileName, OFN_HIDEREADONLY,szFilter);
	
	if(dlg.DoModal() == IDOK)
	{	
		m_strImageFileName = dlg.GetPathName();
		
		if(File.Open(m_strImageFileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
		{
			//Check imgset file   address 0x88 0xcc 0xae 0xce 0xaa
			File.Seek(40,CFile::begin);
			File.Read(v_code,4);

		//	if (v_code[0]==0xba && v_code[1]==0xbe && v_code[2]==0xfa && v_code[3]==0xce)
			if (1)
			{
				//Check OK				
				m_editImagePath.SetWindowText((LPCTSTR) dlg.GetPathName());
				File.Close();			
			}
			else
			{
				AfxMessageBox("Invalid imgset file");
				File.Close();
				delete v_code;
				return;
			}	
			
		}
		else
		{
			AfxMessageBox("Image File Size Error");
			delete v_code;
			return;
		}

		AfxGetApp()->WriteProfileString("CabrioDL", "m_strImageFileName",m_strImageFileName);
	}
	else
	{
		delete v_code;
		return;
	}

	
	delete v_code;

	
	//μ
	
	int i=0,j=0,cnt=0,bResult,bResult2;
	int t=0;
	int length=0;
	CString tPath,tStr;
	CString tCalset,tRsrc1,tRsrc2,tFactory,nRsrc1,nRsrc2,nCalset,nFactory;

	
	tPath=m_strImageFileName;

	GetFileName(tPath);
	
	//õ z220_imgset.img θ ̿Ͽ δܰ  丮 
	//ڿ . 
	while(1)
	{
		i = tPath.Find("\\",j+1);
		if (i!=-1)
		{
			t=j;
			j=i;
		//	depth[cnt]=i;
		}
		else
			break;
		cnt++;
	}

	length=tPath.GetLength();
	tStr=tPath.Right(length-j-1);

	
	bResult=tStr.Find("A401");
	bResult2=tStr.Find("A401_");


	
	if (bResult2==-1 && bResult==0)
	{
		//Ĺ    
		tPath.Delete(j,length-j);

		//  ý 
		// ڵ鸵
		bResult=tStr.Find(".");  // '_'  ã´.
		length=tStr.GetLength(); 
		tStr.Delete(bResult,length-bResult) ;   // '_' պκ  ܵΰ .
		
		tStr="\\"+tStr;
		
		tCalset=tPath;
		tRsrc1=tPath;
		tRsrc2=tPath;
		tFactory=tPath;

		nRsrc1=tStr;
		nRsrc2=tStr;
		nCalset=tStr;
		nFactory=tStr;
	
	
		nCalset=nCalset+"_calset.img";
		tCalset.Insert(j,nCalset);
		m_editParamDepPath.SetWindowText(tCalset);
		m_strParamDepFileName=tCalset;
		
		AfxGetApp()->WriteProfileString("CabrioDl","m_strParamDepFileName",m_strParamDepFileName);


		
		nRsrc1=nRsrc1+"_rsrc.cnt";
		tRsrc1.Insert(j,nRsrc1);
		m_editRscrPath.SetWindowText(tRsrc1);
		m_strRscrFileName=tRsrc1;
		AfxGetApp()->WriteProfileString("CabrioDL", "m_strRscrFileName",m_strRscrFileName);

		nRsrc2=nRsrc2+"_rsrc2.cnt";
		tRsrc2.Insert(j,nRsrc2);
		m_editRscr2Path.SetWindowText(tRsrc2);
		m_strRscr2FileName=tRsrc2;
		AfxGetApp()->WriteProfileString("CabrioDL", "m_strRscr2FileName",m_strRscr2FileName);

		nFactory=nFactory+"_FactoryFS.bin";
		tFactory.Insert(j,nFactory);
		m_editFactoryFSPath.SetWindowText(tFactory);
		m_strFactoryFSFileName=tFactory;
		AfxGetApp()->WriteProfileString("CabrioDL", "m_strFactoryFSFileName",m_strFactoryFSFileName);
	}
	else
	{
		//Ϲ ̳ʸ  μ 
		tPath.Delete(t,length-t);

		tCalset=tPath;
		tRsrc1=tPath;
		tRsrc2=tPath;
		tFactory=tPath;

		tCalset.Insert(t,"\\build\\nor_param\\A401_calset.img");
		m_editParamDepPath.SetWindowText(tCalset);
		m_strParamDepFileName=tCalset;
		AfxGetApp()->WriteProfileString("CabrioDl","m_strParamDepFileName",m_strParamDepFileName);

		tRsrc1.Insert(t,"\\build\\nand_img\\Rsrc_A401.cnt");		
		m_editRscrPath.SetWindowText(tRsrc1);
		m_strRscrFileName=tRsrc1;
		AfxGetApp()->WriteProfileString("CabrioDL", "m_strRscrFileName",m_strRscrFileName);

		tRsrc2.Insert(t,"\\build\\nand_img\\Rsrc2_A401.cnt");
		m_editRscr2Path.SetWindowText(tRsrc2);
		m_strRscr2FileName=tRsrc2;
		AfxGetApp()->WriteProfileString("CabrioDL", "m_strRscr2FileName",m_strRscr2FileName);

		tFactory.Insert(t,"\\build\\nand_img\\FactoryFs_A401.bin");
		m_editFactoryFSPath.SetWindowText(tFactory);
		m_strFactoryFSFileName=tFactory;
		AfxGetApp()->WriteProfileString("CabrioDL", "m_strFactoryFSFileName",m_strFactoryFSFileName);
	}
}



void CCabrio_downloaderv01Dlg::InitVariables()
{

}

void CCabrio_downloaderv01Dlg::RestoreProgramSetting()
{
	//NAND flash ڵ 
	m_strImageFileName = AfxGetApp()->GetProfileString("CabrioDL", "m_strImageFileName", "");
	m_editImagePath.SetWindowText(m_strImageFileName);
}



//Ű 
//-------------------------------------------------------------------
//1. download type
//2. driver  : CURRENT_WITHOUT_DRIVER ϰ ش ̹ ٿε
//3.  ޼  ǥ : 0 ->ǥ
//					    	 1 ->ǥ
bool CCabrio_downloaderv01Dlg::NorDownload(UInt8 cActionType,int prompt)
{

	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	UInt32 startAddr;
	Result_t result;
	char buf[20];
	double duration;
//	UpdateData(true);
	bool rslt;
	int type2;
	char * cTime;
	char * timeinfo=LPSTR(LPCTSTR(str_time));  //ð ´.

	LockControls();


	clock_t StartTime, FinishTime;

	
	str.Format("COM%d",m_ComPort+1);
	char * arg_device=LPSTR(LPCTSTR(str));

	if (nConnectMode==UART_MODE)
	{
		if (cDriverStatus==CURRENT_WITHOUT_DRIVER || cDriverStatus==CURRENT_NAND_DRIVER)
		{
			rslt=NorDriverDownload(&comPortCfg,1);
			if (rslt==false) goto _cleanup;
		}
	}
	

	type2=cActionType;

	switch(cActionType)
	{
		case DWL_IMGSET:
			str2.Format("\n  * NOR : Imgset Download");
			ShowStatus(str2,4);
			break;
		case DWL_CALSET:
			str2.Format("\n  * NOR : Calset Download");
			ShowStatus(str2,4);
			break;
		case DWL_MANUAL:
			str2.Format("\n  * NOR : Manual Download");
			ShowStatus(str2,4);
			break;
		default:
			rslt=false;
			break;
	}


	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];


	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");
		return false;
	}

	

	StartTime = clock();

	if (nConnectMode==UART_MODE)
	{

		Sleep(1000*1);
		str2.Format("\n    Open Comport\t\t\t\t> > > ");
		ShowStatus(str2);


		comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

		if (comPort==0)
		{
			str2.Format("FAIL");
			ShowStatus(str2,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

		
		
		if( initBaudRate != dnldBaudRate ) 
		{
			str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
			ShowStatus(str2);
			
			result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,1 ) ;

			if( RESULT_OK != result )
			{
				str2.Format("FAIL\n");
				ShowStatus(str2,4);
				rslt=false;
				goto _cleanup;	
			}
			else
			{
				str2.Format("OK");
				ShowStatus(str2,3);
			}

			TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
		}
		else
		{
			result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,1 ) ;

			if( RESULT_OK != result )
			{
				str2.Format("FAIL\n");
				ShowStatus(str2,4);
				rslt=false;
				goto _cleanup;	
			}
			else
			{
				str2.Format("OK");
				ShowStatus(str2,3);
			}

			TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
		}
	}



	switch(type2)
	{
		case DWL_IMGSET:

			if (m_boolBootloader==TRUE)	// without Bootloader
				startAddr = 0xABCDEFAB;
			if (m_boolBootloader==FALSE)		// include Bootloader
				startAddr = 0xBABEFACE;

			itoa(m_nImageSize,buf,10);
			str2.Format("%s bytes",buf);
			m_editFileSize.SetWindowText(str2);
			GetCheckSum(m_strImageFileName);
			GetFileName(m_strImageFileName);
			str2.Format("\n    imgset Download start!!\n");
			ShowStatus(str2);
			str2.Format("-----------------------------------------------------------------------------------------------\n");
			ShowStatus(str2);
			if (nConnectMode==UART_MODE)
				result = TOOL_NorFlashDownload(comPort,(UInt8*)m_strImageFileName.GetBuffer(MYBUFF_SIZE),startAddr,0,ToolProgressCb ) ;
			else
				result = TOOL_NorFlashDownload(&comPortCfg,(UInt8*)m_strImageFileName.GetBuffer(MYBUFF_SIZE),startAddr,0,ToolProgressCb ) ;
                        result = TOOL_SetTime(comPort,timeinfo);
			FinishTime=clock();
			break;

		case DWL_CALSET:
			startAddr = 0xBABEFACE;
			itoa(m_nParamDepSize,buf,10);
			str2.Format("%s bytes",buf);
			m_editFileSize.SetWindowText(str2);
			GetCheckSum(m_strParamDepFileName);
			GetFileName(m_strParamDepFileName);
			str2.Format("\n    Now Z220_calset Downloading start!!\n");
			ShowStatus(str2);
			str2.Format("-----------------------------------------------------------------------------------------------\n");
			ShowStatus(str2);
			if (nConnectMode==UART_MODE)
				result = TOOL_NorFlashDownload(comPort,(UInt8*)m_strParamDepFileName.GetBuffer(MYBUFF_SIZE),startAddr,0,ToolProgressCb ) ;
			else
				result = TOOL_NorFlashDownload(&comPortCfg,(UInt8*)m_strParamDepFileName.GetBuffer(MYBUFF_SIZE),startAddr,0,ToolProgressCb ) ;
			FinishTime=clock();
			break;

		case DWL_MANUAL:
			startAddr = m_fAddress;
			itoa(m_nManulImageSize,buf,10);
			str2.Format("%s bytes",buf);
			m_editFileSize.SetWindowText(str2);
			GetCheckSum(m_strManualImage);
			GetFileName(m_strManualImage);
			str2.Format("\n    Now Manual Download start!!( Start address : 0x%x File Size : %d\n",startAddr,m_nManulImageSize);
			ShowStatus(str2);
			str2.Format("-----------------------------------------------------------------------------------------------\n");
			ShowStatus(str2);
			if (nConnectMode==UART_MODE)
				result = TOOL_NorFlashDownload(comPort,(UInt8*)m_strManualImage.GetBuffer(MYBUFF_SIZE),startAddr,m_nManulImageSize,ToolProgressCb ) ;
			else
				result = TOOL_NorFlashDownload(&comPortCfg,(UInt8*)m_strManualImage.GetBuffer(MYBUFF_SIZE),startAddr,m_nManulImageSize,ToolProgressCb ) ;

			FinishTime=clock();

		default:
			rslt=false;
			break;
	}
	
	ShowStatus("\n      Download");

	if( RESULT_OK != result ) 
	{
		str.Format("  Failed");
		ShowStatus(str,4);
		str.Format( "Error flashing image set : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		goto _cleanup;
	}
	else
	{
		str.Format("  Completed");
		ShowStatus(str,3);
	}


	if (nConnectMode==UART_MODE)
	{
		if( initBaudRate != dnldBaudRate ) 
		{
			result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
			if( RESULT_OK != result ) 
			{
				str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
				AfxMessageBox(str);
				rslt=false;
				goto _cleanup;
			}

			TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
		}
	}
	
	//
	if (prompt==0 && m_boolAutoReboot==true)
	{
		result = TOOL_PhoneReset(comPort);
		if( RESULT_OK != result )
		{
			str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
			AfxMessageBox(str);
			rslt=false;
	
			goto _cleanup;
		}

	}

	
	rslt=true;
	
_cleanup:
	if (nConnectMode==UART_MODE)
		TOOL_CloseDnldPort( comPort ) ;
	duration = (double)(FinishTime - StartTime) / CLOCKS_PER_SEC;
	totaltime+=duration;
	str.Format("  ( Elapsed Time : %5.1fs)\n", duration);
	ShowStatus(str,4);
/*	str.Format("\n   Flash CheckSum : %x\n",GetFlashChecksum());
	ShowStatus(str,1);*/
	

	if (m_boolAuto==false || m_boolAutoReboot==true)
	{
		if (prompt==0 && result==RESULT_OK)
			MessageBox("Download Finished","  NOTICE  ");
	}
	if (m_boolAutoReboot==true)
		ReadyControls();

	if ((m_radio==7) && rslt==true)
		return rslt;

	InitControls();
	return rslt;
	
}

bool CCabrio_downloaderv01Dlg::Dlbootloader()
{
	Result_t		result;
	UInt32			startAddr;
//	ComPortCfg_t	comPortCfg;
	CString str;
	double duration;

	AfxMessageBox("Bootloader Download available in UART Comport");
	LockControls();
	str.Format("COM%d",m_ComPort+1);

	//
	// set up the COM configuration structure - zero the structure
	// so that  default values will be supplied by the API
	//
	memset( (char*)&comPortCfg,0,sizeof(ComPortCfg_t) );
	strcpy( (char*)comPortCfg.comPortName,str ) ;  // COM port name
	comPortCfg.baudRate = g_BaudRate[m_cbxBaudRate.GetCurSel()];//COMPORT_BAUDRATE_115K;

	//
	// download the flash driver
	// flashdrv_all.img
	

	str.Format("-----------------------------------------------------------------------------\n  Bootloader Download mode ");
	ShowStatus(str,3);
	if (m_cbxBaudRate.GetCurSel()==0)
	{
		str.Format("( COM%d  BaudRate : 115k )\n-----------------------------------------------------------------------------\n",m_ComPort+1);
	}
	if (m_cbxBaudRate.GetCurSel()==1)
	{
		str.Format("( COM%d  BaudRate : 460k )\n-----------------------------------------------------------------------------\n",m_ComPort+1);
	}
	if (m_cbxBaudRate.GetCurSel()==2)
	{
		str.Format("( COM%d  BaudRate : 921k )\n-----------------------------------------------------------------------------\n",m_ComPort+1);
	}
	
	ShowStatus(str,3);
	//ð
	clock_t StartTime, FinishTime;

	str.Format("  bootloader.img Downloading.........");
	ShowStatus(str);

	StartTime = clock();

	result = TOOL_DownloadBootloaderDrv(&comPortCfg);

//	Sleep(1000*2);
	
	if( result != RESULT_OK ) 
	{
		if( result == RESULT_TOOL_FILE_OPEN_ERROR )
		{
			str.Format("Make sure whether flashdrv_all.img file is in same folder");
			MessageBox(str,"Downloading Failure");
		}
		else
		{
			CString str;
			str.Format("%s",TOOL_GetResultStr(result));
			MessageBox(str,"Downloading Failure");
		}
		str.Format("FAIL\n");
		ShowStatus(str,4);
		str.Format("\n  Turn On/Off the target phone!!!\n");
		ShowStatus(str,4);
		ReadyControls();
		return false;
	}

		//flashdrv_nandimg downloading successfully..
	str.Format("OK\n");
	ShowStatus(str,1);


	startAddr = 0x0000000;
	str.Format("\n  Now Bootloader Downloading........");
	ShowStatus(str);
	Sleep(1000*1);
	CString tempname="bootloader.img";
	result = TOOL_DownloadBootloader(&comPortCfg,0xbabeface);


	if( result != RESULT_OK ) 
	{
		CString str;
		str.Format("FAIL\n");
		ShowStatus(str,4);
		str.Format("%s",TOOL_GetResultStr(result));
		MessageBox(str,"Downloading Failure");
		str.Format("\n  Turn On/Off the target phone!!!\n");
		ShowStatus(str,4);

		goto init;
	}
	FinishTime = clock();
	str.Format("OK\n");
	ShowStatus(str,3);
//	MessageBox("Bootloader Download finished\nYou Must Turn","Download Completed");

	duration = (double)(FinishTime - StartTime) / CLOCKS_PER_SEC;

	str.Format("\n (Total Elapsed Time : %5.1fs)\n\n", duration);
	ShowStatus(str,4);
	cDriverStatus=CURRENT_WITHOUT_DRIVER;

init:
	ReadyControls();
	return true;
	

}

bool CCabrio_downloaderv01Dlg::Erase(UInt8 cActionType)
{

	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	Result_t result;
	bool rslt;


	str.Format("COM%d",m_ComPort+1);
	char * arg_device=LPSTR(LPCTSTR(str));

	if (nConnectMode==UART_MODE)
	{
		if ( (cDriverStatus==CURRENT_WITHOUT_DRIVER) || (cDriverStatus==CURRENT_NOR_DRIVER)|| 
			(cActionType==DWL_ALL))
		{
			rslt=NandDriverDownload(&comPortCfg,1);
			if (rslt==false)
				goto _cleanup;
		}
	}


	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	str2.Format("\n  * NAND Flash all erase");
	ShowStatus(str2,4);



	
	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");
		rslt=false;
		goto _cleanup;
	}

	if (nConnectMode==UART_MODE)
	{
		str2.Format("\n    Open Comport\t\t\t\t> > > ");
		ShowStatus(str2);

		
	//	Sleep(1000*1);
		comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

		if (comPort==0)
		{
			str2.Format("FAIL");
			ShowStatus(str,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

	//	Sleep(1000*3);
		if( initBaudRate != dnldBaudRate ) 
		{
			str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
			ShowStatus(str2);

			result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
			if( RESULT_OK != result )
			{
				str2.Format("FAIL\n");
				ShowStatus(str2,4);
				rslt=false;
				goto _cleanup;	
			}
			else
			{
				str2.Format("OK");
				ShowStatus(str2,3);
			}

			TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
		}

	}
	Sleep(1000*1);



	str.Format("\n    Now NAND All blocks erasing\t\t> > > ");
	ShowStatus(str);

	if (nConnectMode==UART_MODE)
		result=TOOL_FlashErase(comPort);
	else
		result=TOOL_FlashErase(&comPortCfg);

	


	if( RESULT_OK != result ) 
	{
		str.Format("Fail");
		ShowStatus(str,4);
		str.Format( "Error flashing erase : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		
		goto _cleanup;
	}
	else
	{
	//	Sleep(1000*20);
		str.Format("OK\n");
		ShowStatus(str,3);
	}



	
	if (nConnectMode==UART_MODE)
	{
		//flashdrv_nandimg downloading successfully..
		if( initBaudRate != dnldBaudRate ) 
		{
			result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
			if( RESULT_OK != result ) 
			{
				str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
				AfxMessageBox(str);	
				rslt=false;
				goto _cleanup;
			}

			TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
		}
	}
	rslt=true;
	cDriverStatus=CURRENT_NAND_DRIVER;
_cleanup:
	if (nConnectMode==UART_MODE)
		TOOL_CloseDnldPort( comPort );
	
	if (result==RESULT_OK && m_boolAuto==false && cActionType!=DWL_ALL)
		MessageBox("All Erase complete","NOTICE");
	InitControls();
	m_ctrCN.EnableWindow(true);
	return rslt;
}

bool CCabrio_downloaderv01Dlg::NorErase(UInt8 cActionType)
{

	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	Result_t result;
	bool rslt;


	str.Format("COM%d",m_ComPort+1);
	char * arg_device=LPSTR(LPCTSTR(str));

	if (nConnectMode==UART_MODE)
	{
		if ( (cDriverStatus==CURRENT_WITHOUT_DRIVER) || (cDriverStatus==CURRENT_NAND_DRIVER)|| 
			(cActionType==DWL_ALL))
		{
			rslt=NorDriverDownload(&comPortCfg,1);
			if (rslt==false)
				goto _cleanup;
		}
	}


	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	if (cActionType==OP_ERASE_BOOTLOADER)
	{
		str2.Format("\n  * Bootloader erase");
		ShowStatus(str2,4);
	}
	else
	{
		str2.Format("\n  * NOR Flash all erase");
		ShowStatus(str2,4);
	}



	
	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");
		rslt=false;
		goto _cleanup;
	}

	if (nConnectMode==UART_MODE)
	{
		str2.Format("\n    Open Comport\t\t\t\t> > > ");
		ShowStatus(str2);

		Sleep(1000*1);
		comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

		if (comPort==0)
		{
			str2.Format("FAIL");
			ShowStatus(str,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

		Sleep(1000*1);
		if( initBaudRate != dnldBaudRate ) 
		{
			str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
			ShowStatus(str2);

			result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
			if( RESULT_OK != result )
			{
				str2.Format("FAIL\n");
				ShowStatus(str2,4);
				rslt=false;
				goto _cleanup;	
			}
			else
			{
				str2.Format("OK");
				ShowStatus(str2,3);
			}

			TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
		}

	}
	Sleep(1000*1);



	str.Format("\n    Now erasing start!!\n");
	ShowStatus(str);
	str2.Format("-----------------------------------------------------------------------------------------------\n");
	ShowStatus(str2);
	
	if (nConnectMode==UART_MODE)
	{
		if (cActionType==OP_ERASE_BOOTLOADER)
			result=TOOL_NorErase(comPort,0,ToolProgressCb);
		if (cActionType==OP_NOR_ERASE)
			result=TOOL_NorErase(comPort,0x10000,ToolProgressCb);
	}
	else
	{
		if (cActionType==OP_ERASE_BOOTLOADER)
			result=TOOL_NorErase(&comPortCfg,0,ToolProgressCb);
		if (cActionType==OP_NOR_ERASE)
			result=TOOL_NorErase(&comPortCfg,0x10000,ToolProgressCb);

	}
	if( RESULT_OK != result ) 
	{
		str.Format("Fail");
		ShowStatus(str,4);
		str.Format( "Error flashing erase : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		
		goto _cleanup;
	}
		
	if (nConnectMode==UART_MODE)
	{
		//flashdrv_nandimg downloading successfully..
		if( initBaudRate != dnldBaudRate ) 
		{
			result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
			if( RESULT_OK != result ) 
			{
				str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
				AfxMessageBox(str);	
				rslt=false;
				goto _cleanup;
			}

			TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
		}
	}
	ShowStatus("\n      Erase");

	str.Format("  Completed!!!\n\n");
	ShowStatus(str,3);

	if (cActionType==OP_ERASE_BOOTLOADER && nConnectMode==USB_MODE)
		TOOL_PhoneReset(&comPortCfg);
	if (cActionType==OP_ERASE_BOOTLOADER && nConnectMode==UART_MODE)
		TOOL_PhoneReset(comPort);

	rslt=true;
	cDriverStatus=CURRENT_NOR_DRIVER;
_cleanup:

	if (nConnectMode==UART_MODE)
		TOOL_CloseDnldPort( comPort );
	
	if (result==RESULT_OK)
		MessageBox("All Erase complete","NOTICE");
	ReadyControls();
	m_ctrCN.EnableWindow(true);
	return rslt;
}

void CCabrio_downloaderv01Dlg::DisplayButton(UInt8 type,int a,unsigned long addr)
{
	switch(type)
	{
		case CURRENT_NAND_DRIVER:
			if ((addr>=0 && addr<=0x117FFFF))
			{
				if (a==0)
					//GetDlgItem(IDC_BUTTON_NAND_RSCR)->SetFont(&m_font4);
					m_ctrRscr.SetFont(&m_font4, TRUE);
				if (a==1)
					//GetDlgItem(IDC_BUTTON_NAND_RSCR)->SetFont(&m_font5);
					m_ctrRscr.SetFont(&m_font5, TRUE);
				break;
			}
			if ((addr>=0x1180000 && addr<=0x137FFFF))
			{
				if (a==0)
					//GetDlgItem(IDC_BUTTON_NAND_RSCR2)->SetFont(&m_font4);
					m_ctrRscr2.SetFont(&m_font4, TRUE);
				if (a==1)
					//GetDlgItem(IDC_BUTTON_NAND_RSCR2)->SetFont(&m_font5);
					m_ctrRscr2.SetFont(&m_font5, TRUE);

				break;
			}
			if ((addr>=0x1380000 && addr<=0x147FFFF))
			{
				if (a==0)
					//GetDlgItem(IDC_BUTTON_NAND_FACTORYFS)->SetFont(&m_font4);
					m_ctrFactoryFS.SetFont(&m_font4, TRUE);
				if (a==1)
					//GetDlgItem(IDC_BUTTON_NAND_FACTORYFS)->SetFont(&m_font5);
					m_ctrFactoryFS.SetFont(&m_font5, TRUE);
				break;
			}
			break;
		case CURRENT_NOR_DRIVER:
			if ((addr>=0x10000 && addr<=0x1F3FFFF) || (addr>=0x1F80000 && addr<=0x1FDFFFF))
			{
				if (a==0)
					//GetDlgItem(IDC_BUTTON_PHONE_IMAGE)->SetFont(&m_font4);
					m_ctrPhoneImage.SetFont(&m_font4,TRUE);
				if (a==1)
					//GetDlgItem(IDC_BUTTON_PHONE_IMAGE)->SetFont(&m_font5);
					m_ctrPhoneImage.SetFont(&m_font5,TRUE);
				break;
			}
			if ((addr>=0x1F40000 && addr<=0x1F7FFFF))
			{
				if (a==0)
					//GetDlgItem(IDC_BUTTON_SYSPARM_DEP)->SetFont(&m_font4);
					m_ctrSysDep.SetFont(&m_font4,TRUE);
				if (a==1)
					//GetDlgItem(IDC_BUTTON_SYSPARM_DEP)->SetFont(&m_font5);
					m_ctrSysDep.SetFont(&m_font5,TRUE);
				break;
			}
			break;
		default:
			break;
	}
	


}

bool CCabrio_downloaderv01Dlg::BadBlkCheck()
{
	int i;
	int * pBadMap;
	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	Result_t result;
	bool rslt;


	str.Format("COM%d",m_ComPort+1);
	char * arg_device=LPSTR(LPCTSTR(str));

	if (cDriverStatus==CURRENT_WITHOUT_DRIVER || cDriverStatus==CURRENT_NOR_DRIVER )
	{
		rslt=NandDriverDownload(&comPortCfg,1);
		if (rslt==false)
			goto _cleanup;
	}

	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	str2.Format("\n  * Display bad block information ");
	ShowStatus(str2,4);


	
	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");

			goto _cleanup;
	}

	str2.Format("\n    Open Comport.......................................");
	ShowStatus(str2);

	

//	Sleep(1000*1);
	comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

	if (comPort==0)
	{
		str2.Format("FAIL");
		ShowStatus(str,4);
		goto _cleanup;	
	}
	else
	{
		str2.Format("OK");
		ShowStatus(str2,3);
	}

//	Sleep(1000*3);
	if( initBaudRate != dnldBaudRate ) 
	{
		str2.Format("\n    Set Target Phone BaudRate................");
		ShowStatus(str2);

		result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
		if( RESULT_OK != result )
		{
			str2.Format("FAIL\n");
			ShowStatus(str2,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

		TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
	}


	Sleep(1000*1);

	str.Format("\n    Now NAND Bad Block Checking..............");



	ShowStatus(str);

	result=TOOL_BadBlkCheck(comPort);

	if( RESULT_OK != result ) 
	{
		str.Format("Fail");
		ShowStatus(str,4);
		str.Format( "Error flashing erase : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		goto _cleanup;
	}
	else
	{
		str.Format("OK\n");
		ShowStatus(str,3);
	}
	

	Sleep(1000*3);

	str2.Format("\n\n  * Bad Block Information\n");
	ShowStatus(str2,4);

	// EditBox Ѵ.
	pBadMap=GetBadBlk();

	for (i=0;i<80;i++)
	{
		if (*(pBadMap+i)==-1)
		{
			if (i==0)
			{
				str.Format("  There is no Bad Block.\n\n" );
				ShowStatus(str);
			}
			else
			{
				str.Format("\n    There are %d Bad Block.\n\n",i);
				ShowStatus(str,4);
			}
			break;
		}
		str.Format("    Detected bad block : %d\n",*(pBadMap+i));
		ShowStatus(str);
	}
		

	


	




	//flashdrv_nandimg downloading successfully..


	if( initBaudRate != dnldBaudRate ) 
	{
		result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
		if( RESULT_OK != result ) 
		{
			str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
			AfxMessageBox(str);	
			rslt=false;
			goto _cleanup;
		}

		TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
	}
	
	rslt=true;
	cDriverStatus=CURRENT_NAND_DRIVER;

_cleanup:
	TOOL_CloseDnldPort( comPort );
	InitControls();
	return rslt;
}




#if 1
//spare   ǥ
bool CCabrio_downloaderv01Dlg::BadBlkChk()
{

	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	Result_t result;
	bool rslt;


	str.Format("COM%d",m_ComPort+1);
	char * arg_device=LPSTR(LPCTSTR(str));

	if (cDriverStatus==CURRENT_WITHOUT_DRIVER || cDriverStatus==CURRENT_NOR_DRIVER )
	{
		rslt=NandDriverDownload(&comPortCfg,1);
		if (rslt==false)
			goto _cleanup;
	}

	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	str2.Format("\n  * NV Block Reset");
	ShowStatus(str2,4);


	
	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");

			goto _cleanup;
	}

	str2.Format("\n    Open Comport.......................................");
	ShowStatus(str2);

	

//	Sleep(1000*1);
	comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

	if (comPort==0)
	{
		str2.Format("FAIL");
		ShowStatus(str,4);
		goto _cleanup;	
	}
	else
	{
		str2.Format("OK");
		ShowStatus(str2,3);
	}

//	Sleep(1000*3);
	if( initBaudRate != dnldBaudRate ) 
	{
		str2.Format("\n    Set Target Phone BaudRate................");
		ShowStatus(str2);

		result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
		if( RESULT_OK != result )
		{
			str2.Format("FAIL\n");
			ShowStatus(str2,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

		TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
	}


	Sleep(1000*1);

	str.Format("\n    Now NV Block Reset..............");



	ShowStatus(str);

	result=TOOL_BadBlkChk(comPort);

	


	if( RESULT_OK != result ) 
	{
		str.Format("Fail");
		ShowStatus(str,4);
		str.Format( "Error flashing erase : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		goto _cleanup;
	}
	else
	{
		str.Format("OK\n");
		ShowStatus(str,3);
	}




	//flashdrv_nandimg downloading successfully..


	if( initBaudRate != dnldBaudRate ) 
	{
		result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
		if( RESULT_OK != result ) 
		{
			str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
			AfxMessageBox(str);	
			rslt=false;
			goto _cleanup;
		}

		TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
	}
	
	rslt=true;
	cDriverStatus=CURRENT_NAND_DRIVER;
_cleanup:
	TOOL_CloseDnldPort( comPort );
	MessageBox("NV Block reset complete","  NOTICE  ");
	InitControls();
	return rslt;
}
#endif

bool CCabrio_downloaderv01Dlg::MakeNewFormat(UInt8 cDriverStatus)
{
	

	CTFSDialog hDialog;
	
	if(hDialog.DoModal() == IDCANCEL)
	{
		InitControls();
		return false;
	}


	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	Result_t result;
	bool rslt;


	str.Format("COM%d",m_ComPort+1);
	char * arg_device=LPSTR(LPCTSTR(str));

	if (cDriverStatus==CURRENT_WITHOUT_DRIVER || cDriverStatus==CURRENT_NOR_DRIVER)
	{
		rslt=NandDriverDownload(&comPortCfg,1);
		if (rslt==false)
			goto _cleanup;
	}

	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	str2.Format("\n  * Make New Format");
	ShowStatus(str2,4);


	
	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");

			goto _cleanup;
	}

	str2.Format("\n    Open Comport\t\t\t\t> > > ");
	ShowStatus(str2);

	

//	Sleep(1000*1);
	comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

	if (comPort==0)
	{
		str2.Format("FAIL");
		ShowStatus(str,4);
		goto _cleanup;	
	}
	else
	{
		str2.Format("OK");
		ShowStatus(str2,3);
	}

//	Sleep(1000*3);
	if( initBaudRate != dnldBaudRate ) 
	{
		str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
		ShowStatus(str2);

		result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
		if( RESULT_OK != result )
		{
			str2.Format("FAIL\n");
			ShowStatus(str2,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

		TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
	}


	Sleep(1000*1);

	str.Format("\n    Now Make new format\t\t> > > ");



	ShowStatus(str);

	result=TOOL_Make(comPort);

	


	if( RESULT_OK != result ) 
	{
		str.Format("Fail");
		ShowStatus(str,4);
		str.Format( "Error flashing erase : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		goto _cleanup;
	}
	else
	{
		str.Format("OK\n");
		ShowStatus(str,3);
	}




	//flashdrv_nandimg downloading successfully..


	if( initBaudRate != dnldBaudRate ) 
	{
		result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
		if( RESULT_OK != result ) 
		{
			str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
			AfxMessageBox(str);	
			rslt=false;
			goto _cleanup;
		}

		TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
	}
	
	rslt=true;
	cDriverStatus=CURRENT_NAND_DRIVER;
_cleanup:
	TOOL_CloseDnldPort( comPort );
	MessageBox("OK!!!!","  NOTICE  ");
	InitControls();
	return rslt;
}

bool CCabrio_downloaderv01Dlg::BackTheData(UInt8 cDriverStatus)
{
	

	CTFSDialog hDialog;
	
	if(hDialog.DoModal() == IDCANCEL)
	{
		InitControls();
		return false;
	}


	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	Result_t result;
	bool rslt;


	str.Format("COM%d",m_ComPort+1);
	char * arg_device=LPSTR(LPCTSTR(str));

	if (cDriverStatus==CURRENT_WITHOUT_DRIVER || cDriverStatus==CURRENT_NOR_DRIVER)
	{
		rslt=NandDriverDownload(&comPortCfg,1);
		if (rslt==false)
			goto _cleanup;
	}

	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	str2.Format("\n  * Backup data");
	ShowStatus(str2,4);


	
	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");

			goto _cleanup;
	}

	str2.Format("\n    Open Comport\t\t\t\t> > > ");
	ShowStatus(str2);

	

//	Sleep(1000*1);
	comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

	if (comPort==0)
	{
		str2.Format("FAIL");
		ShowStatus(str,4);
		goto _cleanup;	
	}
	else
	{
		str2.Format("OK");
		ShowStatus(str2,3);
	}

//	Sleep(1000*3);
	if( initBaudRate != dnldBaudRate ) 
	{
		str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
		ShowStatus(str2);

		result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
		if( RESULT_OK != result )
		{
			str2.Format("FAIL\n");
			ShowStatus(str2,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

		TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
	}


	Sleep(1000*1);

	str.Format("\n    Now NAND TFS Format Setting\t\t> > > ");



	ShowStatus(str);

	result=TOOL_Back(comPort);

	


	if( RESULT_OK != result ) 
	{
		str.Format("Fail");
		ShowStatus(str,4);
		str.Format( "Error flashing erase : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		goto _cleanup;
	}
	else
	{
		str.Format("OK\n");
		ShowStatus(str,3);
	}




	//flashdrv_nandimg downloading successfully..


	if( initBaudRate != dnldBaudRate ) 
	{
		result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
		if( RESULT_OK != result ) 
		{
			str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
			AfxMessageBox(str);	
			rslt=false;
			goto _cleanup;
		}

		TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
	}
	
	rslt=true;
	cDriverStatus=CURRENT_NAND_DRIVER;
_cleanup:
	TOOL_CloseDnldPort( comPort );
	MessageBox("OK!!!!","  NOTICE  ");
	InitControls();
	return rslt;
}



bool CCabrio_downloaderv01Dlg::TFS_Format(UInt8 cDriverStatus)
{
	

	CTFSDialog hDialog;
	
	if(hDialog.DoModal() == IDCANCEL)
	{
		InitControls();
		return false;
	}


	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	Result_t result;
	bool rslt;


	str.Format("COM%d",m_ComPort+1);
	char * arg_device=LPSTR(LPCTSTR(str));

	if (nConnectMode==UART_MODE)
	{
		if (cDriverStatus==CURRENT_WITHOUT_DRIVER || cDriverStatus==CURRENT_NOR_DRIVER)
		{
			rslt=NandDriverDownload(&comPortCfg,1);
			if (rslt==false)
				goto _cleanup;
		}
	}

	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	str2.Format("\n  * TFS Format");
	ShowStatus(str2,4);


	
	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");

			goto _cleanup;
	}

	if (nConnectMode==UART_MODE)
	{
		str2.Format("\n    Open Comport\t\t\t\t> > > ");
		ShowStatus(str2);

		

	//	Sleep(1000*1);
		comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

		if (comPort==0)
		{
			str2.Format("FAIL");
			ShowStatus(str,4);
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

	//	Sleep(1000*3);
		if( initBaudRate != dnldBaudRate ) 
		{
			str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
			ShowStatus(str2);

			result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
			if( RESULT_OK != result )
			{
				str2.Format("FAIL\n");
				ShowStatus(str2,4);
				rslt=false;
				goto _cleanup;	
			}
			else
			{
				str2.Format("OK");
				ShowStatus(str2,3);
			}

			TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
		}
	}

	Sleep(1000*1);

	str.Format("\n    Now NAND TFS Format Setting\t\t> > > ");



	ShowStatus(str);

	if (nConnectMode==UART_MODE)
		result=TOOL_TFSformat(comPort);
	else
		result=TOOL_TFSformat(&comPortCfg);

	


	if( RESULT_OK != result ) 
	{
		str.Format("Fail");
		ShowStatus(str,4);
		str.Format( "Error flashing erase : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		goto _cleanup;
	}
	else
	{
		str.Format("OK\n");
		ShowStatus(str,3);
	}




	//flashdrv_nandimg downloading successfully..

	if (nConnectMode==UART_MODE)
	{
		if( initBaudRate != dnldBaudRate ) 
		{
			result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
			if( RESULT_OK != result ) 
			{
				str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
				AfxMessageBox(str);	
				rslt=false;
				goto _cleanup;
			}

			TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
		}
	}
	
	rslt=true;
	cDriverStatus=CURRENT_NAND_DRIVER;
_cleanup:
	if (nConnectMode==UART_MODE)
		TOOL_CloseDnldPort( comPort );
	MessageBox("TFS All Erased. Turn On/Off","  NOTICE  ");
	InitControls();
	return rslt;
}

static void CbFunc( UInt32 downloadedBytes )
{
	;

}


bool CCabrio_downloaderv01Dlg::NandDownload(UInt8 cActionType,int prompt)
{

	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	UInt32 startAddr;
	Result_t result;
	char buf[20];
	double duration;
	bool rslt;
//	UpdateData(true);

	LockControls();

	clock_t StartTime, FinishTime;
	
	str.Format("COM%d",m_ComPort+1);
		char * arg_device=LPSTR(LPCTSTR(str));

	
	
	// UART Mode  loader ٿε Ѵ.
	if (nConnectMode==UART_MODE)
	{
		if (cDriverStatus==CURRENT_WITHOUT_DRIVER || cDriverStatus==CURRENT_NOR_DRIVER)
		{
			rslt=NandDriverDownload(&comPortCfg,1);
			if (rslt==false) goto _cleanup;
		}
	}


	
	switch(cActionType)
	{
		case DWL_RSRC1:
			str2.Format("\n  * NAND : Rsrc1 Download");
			ShowStatus(str2,4);
			break;
		case DWL_RSRC2:
			str2.Format("\n  * NAND : Rsrc2 Download");
			ShowStatus(str2,4);
			break;
		case DWL_FACTORYFS:
			str2.Format("\n  * NAND : FactoryFS Download");
			ShowStatus(str2,4);
			break;
			
		case DWL_FLASHALL:
			str2.Format("\n  * NAND : Entire Flash Download");
			ShowStatus(str2,4);
			break;

		case DWL_MANUAL_NAND:
			str2.Format("\n  * NAND : Manual Download");
			ShowStatus(str2,4);
			break;

		default:
			break;
	}


	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");
		return false;

	}



	StartTime = clock();

	if (nConnectMode==UART_MODE)
	{
		Sleep(1000*1);
		str2.Format("\n    Open Comport\t\t\t\t> > > ");
		ShowStatus(str2);
		comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

		if (comPort==0)
		{
			str2.Format("FAIL");
			ShowStatus(str2,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

		if( initBaudRate != dnldBaudRate ) 
		{
			str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
			ShowStatus(str2);
			result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,1 ) ;
			if( RESULT_OK != result )
			{
				str2.Format("FAIL\n");
				ShowStatus(str2,4);
				rslt=false;
				goto _cleanup;	
			}
			else
			{
				str2.Format("OK");
				ShowStatus(str2,3);
			}

			TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
		}
		else
		{
			str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
			ShowStatus(str2);
			result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,1 ) ;
			if( RESULT_OK != result )
			{
				str2.Format("FAIL\n");
				ShowStatus(str2,4);
				rslt=false;
				goto _cleanup;	
			}
			else
			{
				str2.Format("OK");
				ShowStatus(str2,3);
			}

			TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
		}
		Sleep(1000*4);
	}

	switch(cActionType)
	{
		case DWL_RSRC1:
			startAddr = RSRC1_START_ADDR;
			itoa(m_nRscrSize,buf,10);
			str.Format("%s bytes",buf);
			m_editFileSize.SetWindowText(str);
			GetCheckSum(m_strRscrFileName);
			GetFileName(m_strRscrFileName);
			str.Format("\n    Now Rsrc1 Download start!!\n");
			ShowStatus(str);
			str2.Format("-----------------------------------------------------------------------------------------------\n");
			ShowStatus(str2);
			
			if (nConnectMode==UART_MODE)
				result = TOOL_NandFlashDownload(comPort,(UInt8*)m_strRscrFileName.GetBuffer(MYBUFF_SIZE),startAddr,ToolProgressCb ) ;
			else
				result = TOOL_NandFlashDownload(&comPortCfg,(UInt8*)m_strRscrFileName.GetBuffer(MYBUFF_SIZE),startAddr,ToolProgressCb ) ;
			FinishTime=clock();
			break;
		case DWL_RSRC2:
			startAddr = RSRC2_START_ADDR;
			itoa(m_nRscr2Size,buf,10);
			str.Format("%s bytes",buf);
			m_editFileSize.SetWindowText(str);
			GetCheckSum(m_strRscr2FileName);
			GetFileName(m_strRscr2FileName);
			str.Format("\n    Now Rsrc2 Download start!!\n");
			ShowStatus(str);
			str2.Format("-----------------------------------------------------------------------------------------------\n");
			ShowStatus(str2);
			
			if (nConnectMode==UART_MODE)
				result = TOOL_NandFlashDownload(comPort,(UInt8*)m_strRscr2FileName.GetBuffer(MYBUFF_SIZE),startAddr,ToolProgressCb ) ;
			else
				result = TOOL_NandFlashDownload(&comPortCfg,(UInt8*)m_strRscr2FileName.GetBuffer(MYBUFF_SIZE),startAddr,ToolProgressCb ) ;
			FinishTime=clock();
			break;

		case DWL_FACTORYFS:
			startAddr = FACTORYFS_START_ADDR;
			itoa(m_nFactoryFSSize,buf,10);
			str.Format("%s bytes",buf);
			m_editFileSize.SetWindowText(str);
			GetCheckSum(m_strFactoryFSFileName);
			GetFileName(m_strFactoryFSFileName);
			str.Format("\n    Now FactoryFS Download start!!\n");
			ShowStatus(str);
			str2.Format("-----------------------------------------------------------------------------------------------\n");
			ShowStatus(str2);
		
			if (nConnectMode==UART_MODE)
				result = TOOL_NandFlashDownload(comPort,(UInt8*)m_strFactoryFSFileName.GetBuffer(MYBUFF_SIZE),startAddr,ToolProgressCb ) ;
			else
				result = TOOL_NandFlashDownload(&comPortCfg,(UInt8*)m_strFactoryFSFileName.GetBuffer(MYBUFF_SIZE),startAddr,ToolProgressCb ) ;
			FinishTime=clock();
			break;

		case DWL_FLASHALL:
			startAddr = TFS_START_ADDR;
			itoa(m_nEntireFlashSize,buf,10);
			str.Format("%s bytes",buf);
			m_editFileSize.SetWindowText(str);
			GetCheckSum(m_strEntireFlashFileName);
			GetFileName(m_strEntireFlashFileName);
			str.Format("\n    Now TFS Flash Download start!!\n");
			ShowStatus(str);
			str2.Format("-----------------------------------------------------------------------------------------------\n");
			ShowStatus(str2);
			
			if (nConnectMode==UART_MODE)
				result = TOOL_NandFlashDownload(comPort,(UInt8*)m_strEntireFlashFileName.GetBuffer(MYBUFF_SIZE),startAddr,ToolProgressCb ) ;
			else
				result = TOOL_NandFlashDownload(&comPortCfg,(UInt8*)m_strEntireFlashFileName.GetBuffer(MYBUFF_SIZE),startAddr,ToolProgressCb ) ;
			
			FinishTime=clock();
			break;
		case DWL_MANUAL_NAND:
			startAddr = m_fAddress;
			itoa(m_nManualNandImageSize,buf,10);
			str2.Format("%s bytes",buf);
			m_editFileSize.SetWindowText(str2);
			GetCheckSum(m_strManualNandImage);
			GetFileName(m_strManualNandImage);
			str2.Format("\n    Now Manual Download start!!( Start address : 0x%x File Size : %d )\n",startAddr,m_nManualNandImageSize);
			ShowStatus(str2);
			str2.Format("-----------------------------------------------------------------------------------------------\n");
			ShowStatus(str2);
			
			if (nConnectMode==UART_MODE)
				result = TOOL_NandFlashDownload(comPort,(UInt8*)m_strManualNandImage.GetBuffer(MYBUFF_SIZE),startAddr,ToolProgressCb ) ;
			else
				result = TOOL_NandFlashDownload(&comPortCfg,(UInt8*)m_strManualNandImage.GetBuffer(MYBUFF_SIZE),startAddr,ToolProgressCb ) ;
			FinishTime=clock();
			break;
		default:
			rslt=false;
			break;
	}
	
	ShowStatus("\n      Download");

	if( RESULT_OK != result ) 
	{
		str.Format("  Failed");
		ShowStatus(str,4);
		str.Format( "Error flashing image set : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		
		rslt=false;
		goto _cleanup;
	}
	else
	{
		str.Format("  Completed");
		ShowStatus(str,3);
	}

	if (nConnectMode==UART_MODE)
	{
		Sleep(1000*2);
		if( initBaudRate != dnldBaudRate ) 
		{
			result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
			if( RESULT_OK != result )
			{
				str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
				AfxMessageBox(str);
				rslt=false;
				goto _cleanup;
			}

			TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
		}
	}
	Sleep(1000*1);
	
	//
	if ((cActionType==DWL_FACTORYFS && m_boolAutoReboot==true))
	{
		result = TOOL_PhoneReset(comPort);
		
		if( RESULT_OK != result )
		{
			str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
			AfxMessageBox(str);	
		}
		rslt=false;
		goto _cleanup;

	}

	
	rslt=true;
	
_cleanup:
	if (nConnectMode==UART_MODE)
		TOOL_CloseDnldPort( comPort ) ;
	
	duration = (double)(FinishTime - StartTime) / CLOCKS_PER_SEC;
	totaltime+=duration;
	str.Format(" ( Elapsed Time : %5.1fs)\n", duration);
	ShowStatus(str,4);
	if (prompt==0 && result==RESULT_OK)
		MessageBox("Download Finished","  NOTICE  ");
	
	if (cActionType==DWL_FACTORYFS)
		InitControls();

	if ((m_radio==1 || m_radio==7) && rslt==true)
		return rslt;

	InitControls();
	return rslt;
}


bool CCabrio_downloaderv01Dlg::NorDriverDownload(ComPortCfg_t *comPortCfg,int cActionType)
{
	CString str;
	Result_t result;
	double duration;
	clock_t StartTime, FinishTime;

	
	str.Format("\n\n  * NOR Flash Driver Download"); 
	ShowStatus(str,4);

	StartTime=clock();

	//flashdrv_nand.img downloading.....

	str.Format("\n     NOR Flash driver Downloading\t\t> > > ");
	ShowStatus(str);

	result = TOOL_DownloadFlashDriver(comPortCfg,DRV_NOR);


	//ó 
	if( result != RESULT_OK ) 
	{
		if( result == RESULT_TOOL_FILE_OPEN_ERROR )
		{
			str.Format("Make sure whether flashdrv_nand.img file is in same folder");
			MessageBox(str,"Downloading Failure");
		}
		else
		{
			CString str;
			str.Format("%s",TOOL_GetResultStr(result));
			MessageBox(str,"Downloading Failure");
			
		}
		str.Format("FAIL\n");
		ShowStatus(str,4);
		str.Format("\n   Turn On/Off the target phone!!!\n");
		ShowStatus(str,4);
		
		InitControls();
		return false;
	}

	str.Format("OK\n");
	ShowStatus(str,1);


	str.Format("     Flash type Checking\t\t\t> > > ");
	ShowStatus(str);
	Sleep(1000*1);

	if (!FlashCheck(*(GetIDType())))
	{
		str.Format("FAIL\n");
		ShowStatus(str,4);
		str.Format("\n  Turn On/Off the target phone!!!\n");
		ShowStatus(str,4);
		InitControls();
		return false;
	}
	str.Format("OK\n");
	ShowStatus(str,1);
	FinishTime=clock();

	duration = (double)(FinishTime - StartTime) / CLOCKS_PER_SEC;
	totaltime+=duration;
	
	str.Format("    ( Elapsed Time : %5.1fs)\n", duration);
	ShowStatus(str,4);
	cDriverStatus=CURRENT_NOR_DRIVER;
	//flashdrv_nandimg downloading successfully..
	return true;
	
}

bool CCabrio_downloaderv01Dlg::NandDriverDownload(ComPortCfg_t *comPortCfg,int cActionType)
{
	
	CString str;
	Result_t result;
	double duration;
	clock_t StartTime, FinishTime;

	

	
	str.Format("\n\n  * NAND Flash Driver Download"); 
	ShowStatus(str,4);
	str.Format("\n     preboot downloading\t\t\t> > > "); 
	ShowStatus(str);

	StartTime=clock();
	result = TOOL_DownloadFlashDriver(comPortCfg,DRV_PREBOOT);
	
	if( result != RESULT_OK ) 
	{
		if( result == RESULT_TOOL_FILE_OPEN_ERROR )
		{
			str.Format("Make sure whether preboot.img file is in same folder");
			MessageBox(str,"Downloading Failure");
		}
		else
		{
			CString str;
			str.Format("%s",TOOL_GetResultStr(result));
			MessageBox(str,"Downloading Failure");
			
		}
		
		str.Format("FAIL\n");
		ShowStatus(str,4);
		str.Format("\n  Turn On/Off the target phone!!!\n");
		ShowStatus(str,4);
		InitControls();
		return false;
	}
	
	str.Format("OK\n");
	ShowStatus(str,1);
	//preboot downloading successfully..

	//preboot.img ٿε Ŀ  ӵ ٽ  ӵ 
	comPortCfg->baudRate = g_BaudRate[m_cbxBaudRate.GetCurSel()];//COMPORT_BAUDRATE_115K;

	//flashdrv_nand.img downloading.....
	
	str.Format("     NAND Flash driver downloading\t\t> > > ");
	ShowStatus(str);

	result = TOOL_DownloadFlashDriver(comPortCfg,DRV_NAND);


	
	//ó 
	if( result != RESULT_OK ) 
	{
		if( result == RESULT_TOOL_FILE_OPEN_ERROR )
		{
			str.Format("Make sure whether flashdrv_nand.img file is in same folder");
			MessageBox(str,"Downloading Failure");
		}
		else
		{
			CString str;
			str.Format("%s",TOOL_GetResultStr(result));
			MessageBox(str,"Downloading Failure");
			
		}
		str.Format("FAIL\n");
		ShowStatus(str,4);
		str.Format("\n  Turn On/Off the target phone!!!\n");
		ShowStatus(str,4);
		
		InitControls();
		return false;
	}

	str.Format("OK\n");
	ShowStatus(str,1);


	str.Format("     Flash Type Checking\t\t\t> > > ");
	ShowStatus(str);
	Sleep(1000*1);

	if (!FlashCheck(*(GetIDType())))
	{
		str.Format("FAIL\n");
		ShowStatus(str,4);
		str.Format("\n  Turn On/Off the target phone!!!\n");
		ShowStatus(str,4);
		InitControls();
		return false;
	}
	str.Format("OK\n");
	ShowStatus(str,1);
	FinishTime=clock();

	duration = (double)(FinishTime - StartTime) / CLOCKS_PER_SEC;
	totaltime+=duration;
	
	str.Format("    ( Elapsed Time : %5.1fs)\n", duration);
	ShowStatus(str,4);
	cDriverStatus=CURRENT_NAND_DRIVER;
	//flashdrv_nandimg downloading successfully..
	return true;
	
}

int CCabrio_downloaderv01Dlg::FlashCheck(unsigned char t)
{
	if (t== K9K1216D0C_ID)
	{
		m_ctrlNandFlash.SetWindowText("K9K1216D0C 512");
		return 1;
	}
	if (t== K9F5616D0C_ID)
	{
		m_ctrlNandFlash.SetWindowText("K9F5616D0C 256");
		return 1;
	}
	if (t==LRS1896SHARPTB)
	{
		m_ctrlNFlash.SetWindowText("LRS1896TB 256");
		return 1;
	}
	if (t==LRS1896SHARPBB)
	{
		m_ctrlNFlash.SetWindowText("LRS1896BB 256");
		return 1;
	}

	if (t==KAP29WN00M_ONENAND_ADIE)
	{
		m_ctrlNFlash.SetWindowText("MLC NOR 512");
		return 1;
	}

	if (t==0x34)
	{
		m_ctrlNandFlash.SetWindowText("EC34");
		return 1;
	}

	if (t==0x24)
	{
		m_ctrlNandFlash.SetWindowText("EC24");
		return 1;
	}

	return 0;
}





/**********************************************************************/
/* InitControls()													  */
/**********************************************************************/
/*  control ҵ鿡  ʱȭ ۾                       */
/**********************************************************************/
void CCabrio_downloaderv01Dlg::InitControls()
{
	CString str;
	m_ctrDownloadButton.EnableWindow(true);
	m_ctrCap.EnableWindow(true);
	m_ctrBootloaderErase.EnableWindow(true);
	m_ctrNorErase.EnableWindow(true);
	m_ctrNorDump.EnableWindow(true);
	m_ctrNandDump.EnableWindow(true);
	m_ctrCN.EnableWindow(false);   //ÿ ȰȭǾ Ѵ.
	m_ctrTFSFormat.EnableWindow(true);
	m_ctrlDisconnect.EnableWindow(true);
	m_ctrlDlbootloader.EnableWindow(false);
	m_ctrlBChk.EnableWindow(true);
	m_btnManualNor.EnableWindow(true);
	m_btnManualNand.EnableWindow(true);
	m_editManualAddress.EnableWindow(true);
	m_editManualNandAddress.EnableWindow(true);



	m_ctrlComPort.EnableWindow(false);
	m_cbxBaudRate.EnableWindow(false);
//	m_editStatus.EnableWindow(true);
	m_ctrlStart.EnableWindow(false);



	m_ctrPhoneImage.EnableWindow(true);
	m_ctrSysDep.EnableWindow(true);
	m_ctrRscr.EnableWindow(true);
	m_ctrRscr2.EnableWindow(true);
	m_ctrFactoryFS.EnableWindow(true);

	m_ctrPhoneImage.SetFont(&m_font6);
	m_ctrSysDep.SetFont(&m_font6);
	m_ctrRscr.SetFont(&m_font6);
	m_ctrRscr2.SetFont(&m_font6);
	m_ctrFactoryFS.SetFont(&m_font6);
	m_ctrEntireFlash.EnableWindow(true);

	m_nMainPercent = 0;
	m_progressMain.SetRange(0, 100);
	m_progressMain.SetPos(m_nMainPercent);

	m_editFileSize.SetWindowText(" ");;
	m_editFileName.SetWindowText(" ");;
	m_editCheckSum.SetWindowText(" ");;

//	m_font4.CreatePointFont(8, "Arial");
	
	ShowStatus(" ",5);
}

void CCabrio_downloaderv01Dlg::LockControls()
{
	m_ctrDownloadButton.EnableWindow(false);
	m_ctrCap.EnableWindow(false);
	m_ctrBootloaderErase.EnableWindow(false);
	m_ctrNorErase.EnableWindow(false);
	m_ctrNorDump.EnableWindow(false);
	m_ctrNandDump.EnableWindow(false);
	m_ctrCN.EnableWindow(false);
	m_ctrTFSFormat.EnableWindow(false);
	m_ctrlDlbootloader.EnableWindow(false);
	m_ctrlBChk.EnableWindow(false);
	m_ctrEntireFlash.EnableWindow(false);
	m_btnManualNor.EnableWindow(false);
	m_btnManualNand.EnableWindow(false);
	m_editManualAddress.EnableWindow(false);
	m_editManualNandAddress.EnableWindow(false);


	m_ctrlComPort.EnableWindow(false);
	m_cbxBaudRate.EnableWindow(false);
//	m_editStatus.EnableWindow(true);
	m_ctrlStart.EnableWindow(false);
	m_ctrlDisconnect.EnableWindow(false);




	m_ctrPhoneImage.EnableWindow(false);
	m_ctrSysDep.EnableWindow(false);



	m_ctrRscr.EnableWindow(false);
	m_ctrRscr2.EnableWindow(false);
	m_ctrFactoryFS.EnableWindow(false);

}

void CCabrio_downloaderv01Dlg::ReadyControls()
{
	CString str;
	//button
	m_ctrDownloadButton.EnableWindow(false);
//	m_ctrDownloadButton.EnableWindow(true);
	m_ctrCap.EnableWindow(false);
	m_ctrBootloaderErase.EnableWindow(false);
	m_ctrNorErase.EnableWindow(false);
	m_ctrNorDump.EnableWindow(false);
	m_ctrNandDump.EnableWindow(false);
	m_ctrCN.EnableWindow(false);
	m_ctrTFSFormat.EnableWindow(false);
	m_ctrlDisconnect.EnableWindow(false);
	m_ctrlBChk.EnableWindow(false);
	m_btnManualNor.EnableWindow(false);
	m_btnManualNand.EnableWindow(false);
	m_editManualAddress.EnableWindow(false);
	m_editManualNandAddress.EnableWindow(false);
#ifdef _DWL_BOOTLOADER_
	m_ctrlDlbootloader.EnableWindow(true);
#else
	m_ctrlDlbootloader.EnableWindow(false);
#endif

	//env
	m_ctrlComPort.EnableWindow(true);
	m_cbxBaudRate.EnableWindow(true);
	m_ctrlStart.EnableWindow(true);

	
	//Data type
	m_ctrPhoneImage.EnableWindow(true);
	m_ctrSysDep.EnableWindow(true);
	m_ctrRscr.EnableWindow(true);
	m_ctrRscr2.EnableWindow(true);
	m_ctrFactoryFS.EnableWindow(true);
	m_ctrEntireFlash.EnableWindow(true);

	m_ctrPhoneImage.SetFont(&m_font6,TRUE);
	m_ctrSysDep.SetFont(&m_font6,TRUE);
	m_ctrRscr.SetFont(&m_font6,TRUE);
	m_ctrRscr2.SetFont(&m_font6,TRUE);
	m_ctrFactoryFS.SetFont(&m_font6,TRUE);

	str.Format("Disconnect");
	ShowEnv(str,4);

	str.Format("Disconnect");
	ShowEnv(str,2);
	
	m_nMainPercent = 0;
	m_progressMain.SetRange(0, 100);
	m_progressMain.SetPos(m_nMainPercent);

	m_editFileSize.SetWindowText(" ");;
	m_editFileName.SetWindowText(" ");;
	m_editCheckSum.SetWindowText(" ");;


	str.Format("\n * How to use Download Mode");
	ShowStatus(str,4);
#ifdef _INCLUDE_CALSET_
	ShowStatus("  (Include Calset)",3);
#endif

	str.Format("\n    1. Turn off the target phone!!!");
	ShowStatus(str);
	str.Format("\n    2. Select COM Port(USB or UART) , Baud Rate.");
	ShowStatus(str);
	str.Format("\n    3. Push the Start Button.");
	ShowStatus(str);
	str.Format("\n    4. Turn on the target phone!!!\n");
	ShowStatus(str);




}


/**********************************************************************/
/* InitControls()													  */
/**********************************************************************/
/*  control ҵ鿡  ʱȭ ۾                       */
/**********************************************************************/
unsigned long CCabrio_downloaderv01Dlg::GetFileSize(CString filename)
{
	CFile File;

	
	if(File.Open(filename,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
	{
	
		DWORD FileLength = File.GetLength(); 
		File.Close();

		return FileLength;

	}
	else
	{
		
	}

	return 0;
}

int CCabrio_downloaderv01Dlg::GetSectorNum(unsigned long startAddr, unsigned long filesize)
{
	int result;
	unsigned int s,t,u;
	unsigned long tSize=0;
	unsigned int blocknum=0;
	unsigned long nFrom=0, nTo=0;
	result = 0;
	s = t = u = 0;
	
	tSize=startAddr;

	// 0x0 small block ϴ  
	nFrom=aNorFlashTable[0].TopBlkNum * aNorFlashTable[0].SmallBlockSize;

	// ÷ ʺ small block ϴ 
	nTo=aNorFlashTable[0].FlashEntireSize 
		- (aNorFlashTable[0].BottomBlkNum * aNorFlashTable[0].SmallBlockSize);

	while(1)
	{
		if (tSize>=(startAddr+filesize))
			break;
		
		if (tSize<nFrom)
		{
			tSize=tSize+aNorFlashTable[0].SmallBlockSize;
			blocknum++;
			continue;
		}
		
		if (tSize>=nFrom && tSize<nTo)
		{
			tSize=tSize+aNorFlashTable[0].LargeBlockSize;
			blocknum++;
			continue;
		}
		if (tSize>=nTo)
		{
			tSize=tSize+aNorFlashTable[0].SmallBlockSize;
			blocknum++;
			continue;
		}
	}
	return blocknum;
}

int CCabrio_downloaderv01Dlg::GetSectorNum2(unsigned long startAddr, unsigned long filesize)
{
	int result;
	unsigned int s,t,u;
	unsigned long tSize=0;
	unsigned int blocknum=0;
	result = 0;
	s = t = u = 0;


	tSize=startAddr;
	while(1)
	{
		if (tSize>=(startAddr+filesize))
			break;

		tSize=tSize+aNandFlashTable[0].BlockSize;
		blocknum++;
		continue;

	}
	return blocknum;
}


void CCabrio_downloaderv01Dlg::OnSelchangeComboBaudrate() 
{
	// TODO: Add your control notification handler code here
	m_nBaudRate = m_cbxBaudRate.GetCurSel();
	AfxGetApp()->WriteProfileInt("CabrioDL", "m_nBaudRate", m_nBaudRate );
	
}


void CCabrio_downloaderv01Dlg::OnButtonNandRscr() 
{
	// TODO: Add your control notification handler code here
	char szFilter[] = "Rscr.cnt File(*.cnt)|*.cnt|*.*|*.*||";
	CFile File;

	CFileDialog dlg(TRUE, NULL, m_strRscrFileName, OFN_HIDEREADONLY,szFilter);
	
	if(dlg.DoModal() == IDOK)
	{
		m_strRscrFileName = dlg.GetPathName();
		if(File.Open(m_strRscrFileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
		{	
			m_editRscrPath.SetWindowText((LPCTSTR) dlg.GetPathName());
			File.Close();
		}
		else
		{
			AfxMessageBox("File open failed");
		}

		AfxGetApp()->WriteProfileString("CabrioDL", "m_strRscrFileName",m_strRscrFileName);
	}		
}

void CCabrio_downloaderv01Dlg::OnButtonNandRscr2() 
{
	// TODO: Add your control notification handler code here
	char szFilter[] = "Rscr2.cnt File(*.cnt)|*.cnt|*.*|*.*||";
	CFile File;

	CFileDialog dlg(TRUE, NULL, m_strRscr2FileName, OFN_HIDEREADONLY,szFilter);
	
	if(dlg.DoModal() == IDOK)
	{
		m_strRscr2FileName = dlg.GetPathName();
		if(File.Open(m_strRscr2FileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
		{	
			m_editRscr2Path.SetWindowText((LPCTSTR) dlg.GetPathName());
			File.Close();
		}
		else
		{
			AfxMessageBox("File open failed");
		}

		AfxGetApp()->WriteProfileString("CabrioDL", "m_strRscr2FileName",m_strRscr2FileName);
	}		


}

void CCabrio_downloaderv01Dlg::OnButtonNandFactoryfs() 
{
	// TODO: Add your control notification handler code here
	char szFilter[] = "FactoryFS.bin File(*.bin)|*.bin|*.*|*.*||";
	CFile File;

	CFileDialog dlg(TRUE, NULL, m_strFactoryFSFileName, OFN_HIDEREADONLY,szFilter);
	
	if(dlg.DoModal() == IDOK)
	{
		m_strFactoryFSFileName = dlg.GetPathName();	
		if(File.Open(m_strFactoryFSFileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
		{
			m_editFactoryFSPath.SetWindowText((LPCTSTR) dlg.GetPathName());
			File.Close();
		}
		else
		{
			AfxMessageBox("File open failed");
		}

		AfxGetApp()->WriteProfileString("CabrioDL", "m_strFactoryFSFileName",m_strFactoryFSFileName);
	}

	
}






void CCabrio_downloaderv01Dlg::OnButtonSysparmDep() 
{
	// TODO: Add your control notification handler code here
	char szFilter[] = "sysparm_dep.img File(*.img)|*.img|*.*|*.*||";
	CFile File;

	CFileDialog dlg(TRUE, NULL, m_strParamDepFileName, OFN_HIDEREADONLY,szFilter);
	
	if(dlg.DoModal() == IDOK)
	{
		m_strParamDepFileName = dlg.GetPathName();
		if(File.Open(m_strParamDepFileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
		{	
			m_editParamDepPath.SetWindowText((LPCTSTR) dlg.GetPathName());
			File.Close();
		}
		else
		{
			AfxMessageBox("Image File Size Error");
		}

		AfxGetApp()->WriteProfileString("CabrioDL", "m_strParamDepFileName",m_strParamDepFileName);
	}		
	
}

void CCabrio_downloaderv01Dlg::ShowHead()
{
	CString str;
	str.Format("\n-----------------------------------------------------------------------------\n  NAND Flash Download mode ");
	ShowStatus(str,3);
	if (m_cbxBaudRate.GetCurSel()==0)
	{
		str.Format("( COM%d  BaudRate : 115k )\n-----------------------------------------------------------------------------\n",m_ComPort+1);
	}
	if (m_cbxBaudRate.GetCurSel()==1)
	{
		str.Format("( COM%d  BaudRate : 460k )\n-----------------------------------------------------------------------------\n",m_ComPort+1);
	}
	if (m_cbxBaudRate.GetCurSel()==2)
	{
		str.Format("( COM%d  BaudRate : 921k )\n-----------------------------------------------------------------------------\n",m_ComPort+1);
	}
	ShowStatus(str,3);
}


void CCabrio_downloaderv01Dlg::OnButtonDownload2() 
{
	
	// TODO: Add your control notification handler code here
	LockControls();
	UpdateData(true);
	CString str;

	totaltime=0;

	//COM, SPEED   ó
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		goto init;

	//RADIO   б
	switch(m_radio)
	{
		case 0:
			//***********************//
			//*RSRC.CNT ٿε*//
			//***********************//
			m_nRscrSize = GetFileSize(m_strRscrFileName);

			if(!m_nRscrSize)
			{
				AfxMessageBox("Check the file location");
				goto error;
			}
			if(m_nRscrSize>RSRC1_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}


			cActionType=DWL_RSRC1;
			
			//  ̹ NOR flashϰ 
			//¸ ´. 
			if (cDriverStatus==CURRENT_NOR_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}
			
			pThread=AfxBeginThread(NandDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
			

			goto init;
			break;
		case 1:
			//***********************//
			//*NAND ALL     ٿε*//
			//***********************//
			m_nRscrSize = GetFileSize(m_strRscrFileName);

			if(!m_nRscrSize)
			{
				AfxMessageBox("Rscr file not existed");
				AfxMessageBox("Verify a path of Rscr file");
				goto error;
			}
			if(m_nRscrSize>RSRC1_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}

			m_nRscr2Size = GetFileSize(m_strRscr2FileName);

			if(!m_nRscr2Size)
			{
				AfxMessageBox("Rscr2 file not existed");
				AfxMessageBox("Verify a path of Rscr2 file");
				goto error;
			}
			if(m_nRscr2Size>RSRC2_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}

			m_nFactoryFSSize = GetFileSize(m_strFactoryFSFileName);

			if(!m_nFactoryFSSize)
			{
				AfxMessageBox("FactoryFS file not existed");
				AfxMessageBox("Verify a path of FactoryFS file");
				goto error;
			}
			if(m_nFactoryFSSize>FACTORYFS_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}

			cActionType=DWL_ALL;
			//  ̹ NOR flashϰ 
			//¸ ´. 
			if (cDriverStatus==CURRENT_NOR_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}

			pThread=AfxBeginThread(NandDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);

			goto init;
			break;
		case 2:
			//************************//
			//*RSRC2.CNT ٿε*//
			//************************//
			m_nRscr2Size = GetFileSize(m_strRscr2FileName);

			if(!m_nRscr2Size)
			{
				AfxMessageBox("Check the file location");
				goto error;
			}
			if(m_nRscr2Size>RSRC2_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}
			cActionType=DWL_RSRC2;

			if (cDriverStatus==CURRENT_NOR_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}
			
			pThread=AfxBeginThread(NandDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
			
			goto init;
			break;
		case 3:
			//****************************//
			//*FactoryFS.bin ٿε*//
			//****************************//
			m_nFactoryFSSize = GetFileSize(m_strFactoryFSFileName);

			if(!m_nFactoryFSSize)
			{
				AfxMessageBox("Check the file location");
				goto error;
			}
			if(m_nFactoryFSSize>FACTORYFS_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}


			cActionType=DWL_FACTORYFS;
			if (cDriverStatus==CURRENT_NOR_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}

			pThread=AfxBeginThread(NandDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
			
			
			goto init;
			break;

		case 4:
			//****************************//
			//*NOR FLASH ALL     ٿε*//
			//****************************//
			m_nImageSize = GetFileSize(m_strImageFileName);
			if(!m_nImageSize)
			{
				AfxMessageBox("Check the file location");
				goto error;
			}
			if(m_nImageSize>IMGSET_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}


			m_nParamDepSize = GetFileSize(m_strParamDepFileName);
			
			if (m_boolCalset==TRUE)
			{
				if(!m_nParamDepSize)
				{
					AfxMessageBox("Check the file location");
					goto error;
				}
				if(m_nParamDepSize>CALSET_SIZE)
				{
					AfxMessageBox("File size error");
					goto error;
				}
			}
		
			cActionType=DWL_ALL;
			if (cDriverStatus==CURRENT_NAND_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}

			pThread=AfxBeginThread(NorDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
			
			goto init;
			break;

			//all nor
		case 5:
			//****************************//
			//*Z220_imgset.img ٿε    *//
			//****************************//
			m_nImageSize = GetFileSize(m_strImageFileName);

			if(!m_nImageSize)
			{
				AfxMessageBox("Check the file location");
				AfxMessageBox("Verify a path of Z220_calset file");
				goto error;
			}
			if(m_nImageSize>IMGSET_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}

			cActionType=DWL_IMGSET;

			if (cDriverStatus==CURRENT_NAND_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}

			pThread=AfxBeginThread(NorDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
			
			goto init;

			break;

		
		case 6:
			//****************************//
			//*Z220_calset.img  ٿε*//
			//****************************//
			m_nParamDepSize = GetFileSize(m_strParamDepFileName);

			if(!m_nParamDepSize)
			{
				AfxMessageBox("Check the file location");
				AfxMessageBox("Verify a path of Z220_calset file");
				goto error;
			}
			if(m_nParamDepSize>CALSET_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}

			cActionType=DWL_CALSET;
			if (cDriverStatus==CURRENT_NAND_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}

			pThread=AfxBeginThread(NorDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
			
			goto init;
			break;

		
		case 7:
			//****************************//
			//*NAND+NOR ALL  ٿε*//
			//****************************//
			m_nImageSize = GetFileSize(m_strImageFileName);
			if(!m_nImageSize)
			{
				AfxMessageBox("Check the file location");
				AfxMessageBox("Verify a path of Z220_imgset file");
				goto error;
			}
			if(m_nImageSize>IMGSET_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}

			m_nParamDepSize = GetFileSize(m_strParamDepFileName);
			if (m_boolCalset==TRUE)
			{
				if(!m_nParamDepSize)
				{
					AfxMessageBox("Check the file location");
					AfxMessageBox("Verify a path of Z220_calset file");
					goto error;
				}
				if(m_nParamDepSize>CALSET_SIZE)
				{
					AfxMessageBox("File size error");
					goto error;
				}
			}

			m_nRscrSize = GetFileSize(m_strRscrFileName);
			if(!m_nRscrSize)
			{
				AfxMessageBox("Rscr file not existed");
				AfxMessageBox("Verify a path of Rscr file");
				goto error;
			}
			if(m_nRscrSize>RSRC1_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}

			m_nRscr2Size = GetFileSize(m_strRscr2FileName);
			if(!m_nRscr2Size)
			{
				AfxMessageBox("Rscr2 file not existed");
				AfxMessageBox("Verify a path of Rscr2 file");
				goto error;
			}
			if(m_nRscr2Size>RSRC2_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}

			m_nFactoryFSSize = GetFileSize(m_strFactoryFSFileName);
			if(!m_nFactoryFSSize)
			{
				AfxMessageBox("FactoryFS file not existed");
				AfxMessageBox("Verify a path of FactoryFS file");
				goto error;
			}
			if(m_nFactoryFSSize>FACTORYFS_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}

			cActionType=DWL_ALL;
			
			if (cDriverStatus==CURRENT_NAND_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}
			pThread=AfxBeginThread(AllDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
			
			goto init;
			break;

		case 8:
			//****************************//
			//*ü ÷       ٿε*//
			//****************************//
			m_nEntireFlashSize = GetFileSize(m_strEntireFlashFileName);

			if(!m_nEntireFlashSize)
			{
				AfxMessageBox("Check the file location");
				goto error;
			}
			if(m_nEntireFlashSize!=ENTIRE_FLASH_SIZE)
			{
				AfxMessageBox("File size error");
				goto error;
			}


			cActionType=DWL_FLASHALL;
			if (cDriverStatus==CURRENT_NOR_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}

			pThread=AfxBeginThread(NandDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
			
			
			goto init;
			break;
		
		case 9:
			//****************************//
			//*NOR Flash κ    ٿε*//
			//****************************//
			m_nManulImageSize = GetFileSize(m_strManualImage);

#define NOR_BLOCKSIZE		128*1024
			m_fAddress = m_fAddress - (m_fAddress % NOR_BLOCKSIZE);
			if(!m_nManulImageSize)
			{
				AfxMessageBox("Check the file location");
				goto error;
			}

			if (m_nManulImageSize + m_fAddress > 0x1FFFFFF)
			{
				AfxMessageBox("Image file size too big");
				goto error;
			}

			str.Format("Start Address check OK!!\r\nCheck start block Address : 0x%x",m_fAddress);
			AfxMessageBox(str);


			cActionType=DWL_MANUAL;

			if (cDriverStatus==CURRENT_NAND_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}

			pThread=AfxBeginThread(NorDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
			
			goto init;
			break;

		case 10:
			//****************************//
			//*NAND Flash κ    ٿε*//
			//****************************//
			m_nManualNandImageSize = GetFileSize(m_strManualNandImage);

#define NAND_BLOCKSIZE			0x20000
#define NAND_BLOCKNUM			512
#define NAND_PROTECT_BLOCK1		0x14E0000
#define NAND_PROTECT_BLOCK2		0x1500000
#define NAND_FLASH_SIZE			NAND_BLOCKSIZE * NAND_BLOCKNUM
			

			m_fAddress = m_fAddress - (m_fAddress % NAND_BLOCKSIZE);

			if(!m_nManualNandImageSize)
			{
				AfxMessageBox("Check the file location");
				goto error;
			}
			
			// check Protect area

			if (m_fAddress>=NAND_PROTECT_BLOCK1 && m_fAddress<=NAND_PROTECT_BLOCK2)
			{
				AfxMessageBox("start address -> PROTECT AREA\r\nCheck the start adress!!!!");
				goto error;
			}

			if (m_nManualNandImageSize + m_fAddress > NAND_FLASH_SIZE)
			{
				AfxMessageBox("Image file size too big");
				goto error;
			}

			str.Format("Start Address check OK!!\r\nCheck start block Address : 0x%x",m_fAddress);
			AfxMessageBox(str);



			cActionType=DWL_MANUAL_NAND;

			if (cDriverStatus==CURRENT_NOR_DRIVER)
			{
				DisconnectMS();
				cDriverStatus=CURRENT_WITHOUT_DRIVER;
			}

			pThread=AfxBeginThread(NandDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
			
			goto init;
			
		default:
			break;
	}


	AfxMessageBox("Please select download item");

error:
	InitControls();
	return;

init:
	bConnect=true;
	++m_nDownloadNum;
	AfxGetApp()->WriteProfileInt("CabrioDL","m_nDownloadNum",m_nDownloadNum);
	str.Format("%d",m_nDownloadNum);
	m_editDN.SetWindowText(str);
	UpdateData(TRUE);
	UpdateData(FALSE);
}



void CCabrio_downloaderv01Dlg::ShowMessage_ConnectWithMS(int a)
{
	switch(a)
	{
		case 0:
			ShowStatus("Available\n\n",3);
			InitControls();
			break;

		case 1:
			MessageBox("Timeout : No Response at the target phone","Failure");
	//		ShowStatus("Failure\n\n",4);
			bConnect=false;
			ReadyControls();
			break;

		case 2:
			MessageBox("Wrong BaudRate","Failure");
	//		ShowStatus("Failure\n\n",4);
			bConnect=false;
			ReadyControls();
			break;

		case -1:
			MessageBox("Comm Error","Failure");
		//	ShowStatus("Failure\n\n",4);
			bConnect=false;
			ReadyControls();
			break;

		case -2:
			MessageBox("Received Wrong Char from MS","Failure");
		//	ShowStatus("Failure\n\n",4);
			bConnect=false;
			ReadyControls();
			break;
			
		case -3:
			MessageBox("Invalid Env","Failure");
		//	ShowStatus("Failure\n\n",4);
			bConnect=false;
			ReadyControls();
			break;
		case -4:
			MessageBox("USB not detected","Failure");

		default:
			break;
	
	}
}

/* ShowEnv(str,1) --> FlashEdit		Blue
   ShowEnv(str,2)     ConnectEdit	Blue
   ShowEnv(str,3)     FlashEdit		Red
   ShowEnv(str,4)	  ConnectEdit	Red */

void CCabrio_downloaderv01Dlg::ShowEnv(CString str,int a)
{



	CString temp;
	CHARFORMAT cf ;
	
	cf.cbSize = sizeof(CHARFORMAT);
	cf.dwMask = CFM_COLOR|CFM_BOLD;
	cf.dwEffects = ~CFE_AUTOCOLOR|CFE_BOLD;

	switch (a)
	{
	case 1:

		m_ctrlNFlash.SetFocus();
		cf.crTextColor = RGB(0, 0, 255);
		m_ctrlNFlash.SetSelectionCharFormat(cf);

		m_ctrlNFlash.SetSel(0,-1);
		m_ctrlNFlash.ReplaceSel( str );
		m_ctrlNFlash.SetFocus();

		break;
	case 2:
		m_ctrlNandFlash.SetFocus();
		cf.crTextColor = RGB(0, 0, 255);
		m_ctrlNandFlash.SetSelectionCharFormat(cf);
		
		m_ctrlNandFlash.SetSel(0,-1);
		m_ctrlNandFlash.ReplaceSel( str );
		m_ctrlNandFlash.SetFocus();

		break;
	case 3:
		m_ctrlNFlash.SetFocus();
		cf.crTextColor = RGB(255, 0, 0);
		m_ctrlNFlash.SetSelectionCharFormat(cf);
		
		m_ctrlNFlash.SetSel(0,-1);
		m_ctrlNFlash.ReplaceSel( str );
		m_ctrlNFlash.SetFocus();
		
		break;
	case 4:
		m_ctrlNandFlash.SetFocus();
		cf.crTextColor = RGB(255, 0, 0);
		m_ctrlNandFlash.SetSelectionCharFormat(cf);
		
		m_ctrlNandFlash.SetSel(0,-1);
		m_ctrlNandFlash.ReplaceSel( str );
		m_ctrlNandFlash.SetFocus();
		
		break;
	
	default:
		break;
		return;

		
	}
	
}

void CCabrio_downloaderv01Dlg::ShowStatus(CString str)
{

	m_editStatus.LineScroll( m_editStatus.GetLineCount(), -1 );
	
	CHARFORMAT cf ;
	//int total_ch;
	m_editStatus.SetFocus();


	cf.cbSize = sizeof(CHARFORMAT);
	cf.dwMask = CFM_COLOR|CFM_BOLD;
	cf.dwEffects = ~CFE_AUTOCOLOR|~CFE_BOLD;


	cf.crTextColor = RGB(255, 255, 255);
	m_editStatus.SetSelectionCharFormat(cf);

	m_editStatus.SetSel(-1,-1);
	m_editStatus.ReplaceSel( str );
	m_editStatus.SetFocus();


}

void CCabrio_downloaderv01Dlg::ShowTotalTime()
{
	CString str;
	str.Format("\n  * TOTAL Elapsed Time : %5.1fs\n", totaltime);
	ShowStatus(str,4);
	MessageBox("All Download Finished","NOTICE");
}

void CCabrio_downloaderv01Dlg::ShowStatus(CString str,int a)
{



	CString temp;
	CHARFORMAT cf ;
	m_editStatus.SetFocus();

	
	cf.cbSize = sizeof(CHARFORMAT);


	if (a==0 || a==5)
	{
			cf.dwMask = CFM_COLOR|CFM_BOLD;;
			cf.dwEffects = ~CFE_AUTOCOLOR|CFE_BOLD;
	}
	else
	{

		if (a==3 || a==4)
		{
			cf.dwMask = CFM_COLOR|CFM_BOLD;
			cf.dwEffects = ~CFE_AUTOCOLOR|CFE_BOLD;
		}
		else
		{
			cf.dwMask = CFM_COLOR|CFM_BOLD;
			cf.dwEffects = ~CFE_AUTOCOLOR|CFE_BOLD;
		}
	}

	if (a==5)
		cf.crTextColor = RGB(255,255,255);
	if (a==0)
		cf.crTextColor = RGB(0, 0, 0);
	if (a==1 || a==3)
		cf.crTextColor = RGB(0, 0, 255);
	if (a==2 || a==4)
		cf.crTextColor = RGB(255, 0, 0);

	m_editStatus.SetSelectionCharFormat(cf);
	
	if (a==5)
	{
		str=str+"\r";
		m_editSubStatus.SetSel(0, -1);
		m_editSubStatus.ReplaceSel( str );
		m_editSubStatus.SetFocus();
	}
	else
	{
		m_editStatus.SetSel(-1,-1);
		m_editStatus.ReplaceSel( str );
		m_editStatus.SetFocus();
	}


}


void CCabrio_downloaderv01Dlg::OnButtonCap() 
{

	COKDialog hDialog;
	

	if (cActionType!=DWL_ALL)
	{
		if(hDialog.DoModal() == IDCANCEL)
		{
			InitControls();
			return;
		}
	}
	
	LockControls();
	UpdateData(true);
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		goto init;
	
	cActionType=OP_NAND_ERASE;

	if (cDriverStatus==CURRENT_NOR_DRIVER)
	{
		DisconnectMS();
		cDriverStatus=CURRENT_WITHOUT_DRIVER;
	}
	


	pThread=AfxBeginThread(EraseThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST  );
init:
	;
}




char * CCabrio_downloaderv01Dlg::PathMake(CString str)
{
	CString temp;
	char * ss=LPSTR(LPCTSTR(str));
	char * m;
	char t[1000];
	char q[1000];
	int n=0;


	//̸ ϰ, θ Ѵ.
	m=strrchr(ss,92);
	strncpy(t,ss,m-ss+1);
	*(m+1)='\0';
	*(ss+strlen(ss)-1)='\0';

	m=strrchr(ss,92);
	strncpy(q,ss,m-ss+1);
	*(m+1)='\0';
	*(ss+strlen(ss)-1)='\0';
	
	return ss;
}




// Cancel 
void CCabrio_downloaderv01Dlg::OnButtonCN() 
{
	// TODO: Add your control notification handler code here
	Result_t		result;

	CString str;

	TOOL_CloseFP();

	HANDLE hThread = pThread->m_hThread;

	DWORD dwExitCode =0;

	TerminateThread(hThread, dwExitCode);

	result=TOOL_CloseComPort(&comPortCfg);
	if (result!=0)
	{
		str.Format("  There is not Downloading Thread\n\n");
		MessageBox(str,"Erase Failure");
	}
	else
	{
		str.Format("  CANCELED\n\n  Turn Off the target phone!!!!!\n");
		ShowStatus(str,4);
	}


	m_progressMain.SetPos(0);
	CString test;

	test.Format(" ");
	//	pDlg->m_editSubStatus.SetWindowText(test);
		
	ShowStatus(test,5);

	cDriverStatus=CURRENT_WITHOUT_DRIVER;

	ReadyControls();

	

}

HBRUSH CCabrio_downloaderv01Dlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 
{
//	HBRUSH hbr = CCabrio_downloaderv01Dlg::OnCtlColor(pDC, pWnd, nCtlColor);
	HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
	// TODO: Change any attributes of the DC here

	HBRUSH brush;
#define COLOR_BLACK RGB( 0, 0, 0)
#define COLOR_BLUE RGB( 0, 0,128)
#define COLOR_GREEN RGB( 0,128, 0)
#define COLOR_CYAN RGB( 0,128,128)
#define COLOR_RED RGB(128, 0, 0)
#define COLOR_MAGENTA RGB(128, 0,128)
#define COLOR_BROWN RGB(128,128, 0)
#define COLOR_DARKGRAY RGB(128,128,128)
#define COLOR_LIGHTGRAY RGB(192,192,192)
#define COLOR_LIGHTBLUE RGB( 0, 0,255)
#define COLOR_LIGHTGREEN RGB( 0,255, 0)
#define COLOR_LIGHTCYAN RGB( 0,255,255)
#define COLOR_LIGHTRED RGB(255, 0, 0)
#define COLOR_LIGHTMAGENTA RGB(255, 0,255)
#define COLOR_YELLOW RGB(255,255, 0)
#define COLOR_WHITE RGB(255,255,255)

	if (pWnd->GetDlgCtrlID()==IDC_BUTTON_TITLE)
	{
	brush=CreateSolidBrush(COLOR_RED);
	pDC->SetBkColor(RGB(0, 0, 255));
	hbr=brush;
	}
	return hbr;
}



void CCabrio_downloaderv01Dlg::OnButtonTitle() 
{
	// TODO: Add your control notification handler code here
	CVerDialog hDialog;
	int a;
	
	a=hDialog.DoModal();

	if (a==IDOK)
	{
		return;
	}
//	ReadyControls();
}

void CCabrio_downloaderv01Dlg::GetFileName(CString path)
{
	CString tPath;
	CString tStr;

	int n=0,length=0,cnt=0,i=0,t=0,j=0;;

#if 0
	//̸ ϰ, θ Ѵ.
	m=strrchr(ss,92);
	strncpy(t,m+1,strlen(ss)-strlen(m));
	temp.Format("%s",t);
	strcpy(v_FileName,t);
#endif

	tPath=path;

	while(1)
	{
		i = tPath.Find("\\",j+1);
		if (i!=-1)
		{
			t=j;
			j=i;
		//	depth[cnt]=i;
		}
		else
			break;
		cnt++;
	}
	
	length=path.GetLength();
	tStr=tPath.Right(length-j-1);

	m_editFileName.SetWindowText(tStr);

}

void CCabrio_downloaderv01Dlg::GetCheckSum(CString Filename)
{
	CFile File;
	DWORD Checksum = 0;
	BYTE * buffer;
	
	if(File.Open(Filename,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
	{
		DWORD i;
		DWORD FileLength = File.GetLength(); 
		

		buffer = new BYTE[FileLength];
		File.ReadHuge(buffer,FileLength);
		File.Close();
		for( i=0; i < FileLength; i++ )
		{
			
			Checksum += buffer[i];
		}

		CString str;
		str.Format("0x%lX",Checksum);

		m_editCheckSum.SetWindowText(str);
		

	
		delete buffer;
	}
	else
	{
		;
	}
}


void CCabrio_downloaderv01Dlg::OnButtonTfsFormat() 
{
	// TODO: Add your control notification handler code here
	
	LockControls();
	UpdateData(true);
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		goto init;


	
	if (cDriverStatus==CURRENT_NOR_DRIVER)
	{
		DisconnectMS();
		cDriverStatus=CURRENT_WITHOUT_DRIVER;
	}

	

	pThread=AfxBeginThread(TFSFormatThreadFunc, (LPVOID)this, THREAD_PRIORITY_HIGHEST  );
	
	init:
	;
//	InitControls();
}

void CCabrio_downloaderv01Dlg::OnButtonStart() 
{
	// TODO: Add your control notification handler code here
	CString str;


	LockControls();

	
	UpdateData(true);
#if 1
	if (m_radioMode==0)
	{
		nConnectMode=UART_MODE;
		AfxMessageBox("UART Mode is not available in this tool!!");
		ReadyControls();
		return;
	}
	if (m_radioMode==1)
	{
		nConnectMode=USB_MODE;
	//	AfxMessageBox("Check the USB Comport number!");
	}
#endif

	if (m_radioMode==-1)
	{
		AfxMessageBox("Select a comm type by USB or by UART.\r\nTry again!!");
		ReadyControls();
		return;
	}






	if (m_boolAuto==true)
	{
		m_nImageSize = GetFileSize(m_strImageFileName);
		if(!m_nImageSize)
		{
			AfxMessageBox("NOR : imgset - not existed");
			AfxMessageBox("Verify a path of Z220_imgset file");
			goto init;
		}
		if (m_boolCalset==TRUE)
		{
			m_nParamDepSize = GetFileSize(m_strParamDepFileName);

			if(!m_nParamDepSize)
			{
				AfxMessageBox("NOR: calset - not existed");
				AfxMessageBox("Verify a path of Z220_calset file");
				goto init;
			}
		}
		
		m_nRscrSize = GetFileSize(m_strRscrFileName);

		if(!m_nRscrSize)
		{
			AfxMessageBox("NAND : Rscr1 file not existed");
			AfxMessageBox("Verify a path of Rscr file");
			goto init;
		}
		m_nRscr2Size = GetFileSize(m_strRscr2FileName);

		if(!m_nRscr2Size)
		{
			AfxMessageBox("NAND : Rscr2 file not existed");
			AfxMessageBox("Verify a path of Rscr2 file");
			goto init;
		}
		m_nFactoryFSSize = GetFileSize(m_strFactoryFSFileName);

		if(!m_nFactoryFSSize)
		{
			AfxMessageBox("NAND : FactoryFS file not existed");
			AfxMessageBox("Verify a path of FactoryFS file");
			goto init;
		}

		ShowStatus("\n  * Connecting to target phone",4);
		str.Format("\n     Try to open COM%d\t>",m_ComPort+1);
		ShowStatus(str,3);
	//	nCon_Result=ConnectWithMS();
	//	ShowMessage_ConnectWithMS(nCon_Result);

		cActionType=DWL_ALL;
		pThread=AfxBeginThread(AutoDownloadThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST);
	}
	else
		pThread=AfxBeginThread(ConnectionThreadFunc, (LPVOID)this, THREAD_PRIORITY_HIGHEST);
	
	
	//InitControls();
	return;
init:
	str.Format("  Connect");
	ShowEnv(str,4);
	ReadyControls();
}

void CCabrio_downloaderv01Dlg::DisconnectMS()
{
	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	Result_t result;



	cDriverStatus=CURRENT_WITHOUT_DRIVER;

	if (nConnectMode==UART_MODE)
	{
		initBaudRate=g_BaudRate[0];
		dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];


		str.Format("COM%d",m_ComPort+1);
		char * arg_device=LPSTR(LPCTSTR(str));
		

		str2.Format("\n   * Reconnecting (Flash Driver Change)");
		ShowStatus(str2,4);
		str2.Format("\n    Open Comport\t\t\t\t> > > ");
		ShowStatus(str2);

		
		comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

		if (comPort==0)
		{
			str2.Format("FAIL");
			ShowStatus(str,4);
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

	/*	if( initBaudRate != dnldBaudRate ) 
		{
			str2.Format("\n    Set Target Phone BaudRate................");
			ShowStatus(str2);

			result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
			if( RESULT_OK != result )
			{
				str2.Format("FAIL\n");
				ShowStatus(str2,4);
				goto _cleanup;	
			}
			else
			{
				str2.Format("OK");
				ShowStatus(str2,3);
			}

			TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
		}*/


		Sleep(1000*1);

		str.Format("\n    Now Reconnecting\t\t\t> > > ");



		ShowStatus(str);

		result=TOOL_Disconnect(comPort);

		if (result!=RESULT_OK)
		{
			str.Format("FAIL");
			ShowStatus(str,4);
		}
		else
		{
			str.Format("OK");
			ShowStatus(str,3);
		}
	}
	



_cleanup:
	if (nConnectMode==UART_MODE)
	{
		TOOL_CloseDnldPort( comPort ) ;
	}
	else
		InitControls();
		m_ctrCN.EnableWindow(true);


	if (comPort!=0 && result==RESULT_OK && (m_radio==4 || m_radio==7 || m_radio==1))
		m_ctrCN.EnableWindow(true);
	else
		InitControls();	
}

//#define _USB_CONNET_

// divisor must be 1xxx xxx1, initvalue=0x00, 0xFF
UInt8 CCabrio_downloaderv01Dlg::GetCRC7(UInt8 *bpdata, UInt8 totlen, UInt8 initvalue, UInt8 divisor, UInt8 bit0)
{
	UInt8 shiftdata, newbit, dvs_mask, dvs_and, temp8;
	UInt16 i,shiftdata1;

	if(initvalue == 0x00)
	{
		shiftdata = initvalue;
		dvs_mask = divisor & 0x7E;
		dvs_and = ~(divisor & 0x7F);

		for(i=0; i<(8*totlen); i++)
		{
			newbit = GetBit(bpdata,(UInt32)i) ^ ((shiftdata & 0x40)>>6);
			shiftdata <<= 1;
			if(newbit)
				temp8 = dvs_mask;
			else
				temp8 = 0x0000;
			temp8 ^= (shiftdata & dvs_mask);
			shiftdata = (shiftdata & dvs_and) | temp8 | newbit;

			if( ((i&7) == 7) && (bit0 == 0) )
			{
				CString str;
				str.Format("\n\rcrc7_sw=0x",(shiftdata<<1) | bit0);
				AfxMessageBox(str);
			}
		}

		return ((shiftdata<<1) | bit0);
	}
	else
	{
		shiftdata1 = (UInt16)initvalue;

		for(i=0; i<(8*totlen); i++)
		{
			shiftdata1 <<= 1;
			shiftdata1 += GetBit(bpdata,(UInt32)i);
			if( shiftdata1 >= 0x80 )
				shiftdata1 ^= divisor;
		}

		for(i=0; i<7; i++)
		{
			shiftdata1 <<= 1;
			if( shiftdata1 >= 0x80 )
				shiftdata1 ^= divisor;
		}

		return ((UInt8)(shiftdata1<<1) | bit0);
	}
}

UInt16 CCabrio_downloaderv01Dlg::GetCRC16(UInt8 *bpdata, UInt16 totlen, UInt16 initvalue, UInt32 divisor)
{
	UInt16 shiftdata, newbit, dvs_mask, dvs_and, temp16;
	UInt32 i, i1, shiftdata1;

	if(initvalue == 0x0000)
	{
		shiftdata = initvalue;
		dvs_mask = (UInt16)(divisor & 0xFFFE);
		dvs_and = ~((UInt16)(divisor & 0xFFFF));

		for(i=0; i<(8*totlen); i++)
		{
			newbit = (UInt16)GetBit(bpdata,(UInt32)i) ^ (shiftdata>>15);
			shiftdata <<= 1;
			if(newbit)
				temp16 = dvs_mask;
			else
				temp16 = 0x0000;
			temp16 ^= (shiftdata & dvs_mask);
			shiftdata = (shiftdata & dvs_and) | temp16 | newbit;
		}

		return shiftdata;
	}
	else
	{
		shiftdata1 = (UInt32)initvalue;

		for(i1=0; i1<(8*totlen); i1++)
		{
			shiftdata1 <<= 1;
			shiftdata1 += GetBit(bpdata,i1);
			if( shiftdata1 >= 0x10000 )
				shiftdata1 ^= divisor;
		}

		for(i1=0; i1<16; i1++)
		{
			shiftdata1 <<= 1;
			if( shiftdata1 >= 0x10000 )
				shiftdata1 ^= divisor;
		}

		return (UInt16)shiftdata1;
	}
}

UInt8 CCabrio_downloaderv01Dlg::GetBit(UInt8 *bpdata, UInt32 bitaddr)
{
	UInt8 bitloc, mybyte;
	bitloc = 7 - (UInt8)(bitaddr&0x07);
	mybyte = 0x01 << bitloc;

	return (*(bpdata + (bitaddr>>3)) & mybyte)>>bitloc;
}

/*
BOOL CCabrio_downloaderv01Dlg::GetBlkDataFromImage(UInt8 *bp, FILE *fp, UInt16 blklength)
{
	UInt8 c;
	UInt16 i;
	for(i=0; i<blklength; i++)
	{
		if (fread(&c, 1, 1, fp) == 1)
		{
			*(bp+i) = c;
		}
		else
		{
			AfxMessageBox("\nError in Reading Image File!");
			return FALSE;
		}
	}
	return TRUE;
}
*/

void CCabrio_downloaderv01Dlg::GetBlkDataFromArray(UInt8 *bp, UInt8 const *ap, UInt32 startaddr, UInt16 blklength)
{
	UInt16 i;
	for(i=0; i<blklength; i++)
	{
		*(bp+i) = *(ap + startaddr + i);
	}
}


#define _USB_CONNET_

int CCabrio_downloaderv01Dlg::ConnectWithMS()
{

	CString str;
	unsigned char rxChar,txChar;
	Result_t result;
	UInt8 saveBaudRate;
	UInt32	nByte;
	UInt8	*fileBuffer = 0,p;
	int cnt=0;

	
	static UInt8 block_buff[BLOCK_LENGTH];

	char * tName="flashloader_test.img";
	UInt32 totblks=0,lastblklength=0,blklength=0;
	
	UInt8	ch,c,c1,c2,crcon,block_pattern;
	UInt16	crc7_blk,crc16_blk,i,j,k;

	LockControls();
	
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		return CON_ENV_ERROR;
	
	str.Format("COM%d",m_ComPort+1);

	/*    Comport      
	/ COM BAUD SPEED FLASHNAME    ComportCfg_t ü */
	memset( (char*)&comPortCfg,0,sizeof(ComPortCfg_t) );
	strcpy( (char*)comPortCfg.comPortName,str ) ;  // COM port name
	comPortCfg.baudRate = g_BaudRate[m_cbxBaudRate.GetCurSel()];//COMPORT_BAUDRATE_115K;

	
	switch( comPortCfg.baudRate )
	{
		case FP_Speed_921k:
		case FP_Speed_460k:
		case FP_Speed_115k:
			break ;
		default:
			result = RESULT_TOOL_INVALID_VALUE ;
			nCon_Result=CON_SPEED_SET_ERROR;
			goto _cleanup ;
	}

	saveBaudRate = comPortCfg.baudRate ;
	comPortCfg.baudRate = COMPORT_BAUDRATE_115K ;

	TOOL_CloseComPort(&comPortCfg);

	{
		
		do
		{
			result = TOOL_OpenComPort( &comPortCfg,NOPARITY) ;
			cnt ++;
			
			if (cnt%5==0)
				ShowStatus(">",3);
			
			Sleep(100);
			if(cnt > 120)
			{

				ShowStatus("\r      USB Comport is not detected\n",4);
				ReadyControls();
				nCon_Result=CON_OVERTRY;
				TOOL_CloseComPort(&comPortCfg);
				return nCon_Result;
			}
		}while(RESULT_OK != result);
	}


	str.Format(" Comport Detected\n");

	
	ShowStatus(str,3);
	ShowStatus("\n   - Turn on the target phone immediately!!!!\n",4);
	ShowStatus("      Listen for the BOOT signal\t\t\t> > > " );

	rxChar=0xff;
	
	//listen for char 1 byte 0xA5
	while(RESULT_OK==TOOL_ReadComPortWithTimeout(&comPortCfg,&rxChar,1,TIMEOUT_SEC))
	{
		if (rxChar==0xA5)
		{
			ShowStatus("OK\n",3);
			goto _sendack;
		}
		
	}
		
	//TIMEOUT  
	if (rxChar==0xff)
	{
		//AfxMessageBox("TIMEOUT");
		ShowStatus("FAIL\n",4);
		ShowStatus("      (Check Comport connection & Bootloader existence)\n",3);
		nCon_Result=CON_TIMEOUT;
		goto _cleanup;
	}

	//Received wrong char
	if (rxChar!=BOOT_CHAR)
	{
		nCon_Result=CON_WRONG_BOOTCHAR;
		ShowStatus("Wrong code! Try again\n",4);	
		goto _cleanup ;
	}

	if(result == RESULT_TOOL_TIMEOUT)
	{
		//AfxMessageBox("TIMEOUT");
		nCon_Result=CON_TIMEOUT;
		ShowStatus("Timeout\n",4);	
		goto _cleanup;
	}		


_sendack:
	
	ShowStatus("      Send the Download start signal\t\t> > > " );
	//sending 1byte char 0xc9
	txChar=DWL_START_CHAR;
//	txChar=FACTORY_MODE_CHAR;
	result=TOOL_WriteComPort(&comPortCfg,&txChar,1,&nByte);

	if (result!=RESULT_OK)
	{
		ShowStatus("FAIL\n",4);
		//AfxMessageBox("Comm Error");
		nCon_Result=CON_COMM_ERROR;
		goto _cleanup ;
	}
	
	ShowStatus("OK\n",3);
	//listen for ack from MS
	rxChar=0xff;

	ShowStatus("      Listen for the Download start ACK signal\t> > > " );
	do
	{

		while(RESULT_OK==TOOL_ReadComPortWithTimeout(&comPortCfg,&rxChar,1,1))
		{

			if (rxChar==DWL_START_CHAR)
		//	if (rxChar==FACTORY_MODE_CHAR)
			{
				ShowStatus("OK\n",3);
				nCon_Result=CON_SUCCESS;

				//Connect â connectǥ
				str.Format("  Connect");
				ShowEnv(str,4);
	
				if (cnt==1)
				{
					ShowStatus("\n      UART Download Mode\t> > > ");
					TOOL_CloseComPort( &comPortCfg ) ;
					return nCon_Result;
				}
				else
					break;

			}	
		}
        
		//rxChar    Timeoutð Ͱ   
		if (rxChar==0xff)
		{
			ShowStatus("Timeout\n",3);
			nCon_Result=CON_TIMEOUT;
			InitControls();
			goto _cleanup;
		}

	//	if (rxChar!=FACTORY_MODE_CHAR)
		if (rxChar!=DWL_START_CHAR)
		{
			ShowStatus("Wrong code\n",3);
			nCon_Result=CON_WRONG_BOOTCHAR;
			InitControls();
			goto _cleanup ;
		}
		if (rxChar!=DWL_START_CHAR)
		{
			ShowStatus("COMPORT_ERROR\n",3);
			nCon_Result=CON_COMM_ERROR;
			InitControls();
			goto _cleanup;		

		}
		else
			break;

	} while (1);

	
	result=TOOL_CloseComPort( &comPortCfg ) ;
	
// loader to sram

	union {						// sector size
		UInt32	sector_size;
		struct {
			UInt8	sector_size_byte0;	// lowest byte sector size
			UInt8	sector_size_byte1;	// low byte sector size
			UInt8	sector_size_byte2;	// high byte sector size
			UInt8	sector_size_byte3;	// highest byte sector size
		};
	} ss;
	
	union {						// file size
		UInt32	image_size;
		struct {
			UInt8	image_size_byte0; // lowest byte file of size
			UInt8	image_size_byte1; // low byte file of size
			UInt8	image_size_byte2; // high byte file of size
			UInt8	image_size_byte3; // highest byte of file size
		};
	} is;

	union {						// start address
		UInt32	start_addr;
		struct {
			UInt8	start_addr_byte0; // lowest byte start address
			UInt8	start_addr_byte1; // low byte start address
			UInt8	start_addr_byte2; // high byte start address
			UInt8	start_addr_byte3; // highest byte start address
		};
	} sa;

	
	str.Format("COM%d",m_ComPort+1);
	memset( (char*)&comPortCfg,0,sizeof(ComPortCfg_t) );
	strcpy( (char*)comPortCfg.comPortName,str ) ;  // COM port name
	comPortCfg.baudRate = g_BaudRate[m_cbxBaudRate.GetCurSel()];//COMPORT_BAUDRATE_115K;


	saveBaudRate = comPortCfg.baudRate ;

	result=TOOL_OpenComPort(&comPortCfg,NOPARITY);
	if (result!=RESULT_OK)
	{
		nCon_Result=CON_COMM_ERROR;
			goto _cleanup;		

	}

	// handshaking usbbootloader
	p=USB_START_SIGNAL;

	result=TOOL_WriteComPortWithTimeout( &comPortCfg, &p,1,TIMEOUT_SEC );
	

	result=TOOL_ReadComPortWithTimeout( &comPortCfg, &c,1,TIMEOUT_SEC );
	

	if( c!=USB_START_ACK_SIGNAL)
	{
		ShowStatus(" Fail\n",4);
		goto _cleanup;	
	}

	sa.start_addr=LOADER_SRAM_ADDRESS;
	is.image_size=hFlashloaderSize[0];
	
	totblks = is.image_size/BLOCK_LENGTH;
	totblks++;
	g_nDownloadedSector=totblks;
	lastblklength = is.image_size%BLOCK_LENGTH;


	// send the name of Flashloader to USB bootloader
	for (i=0;i<64;i++)
		TOOL_WriteComPortWithTimeout( &comPortCfg, &tName[i],1, TIMEOUT_SEC );

	// send the start address to USB bootloader
	c=sa.start_addr >> 24 & 0xFF;
	TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1, TIMEOUT_SEC );
	c=sa.start_addr >> 16 & 0xFF;
    TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1, TIMEOUT_SEC );
	c=sa.start_addr >> 8 & 0xFF;
    TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1, TIMEOUT_SEC );
	c=sa.start_addr & 0xFF;
    TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1, TIMEOUT_SEC );
	// send the size of loader to USB bootloader
	c=is.image_size >> 24 & 0xFF;
    TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1, TIMEOUT_SEC );
	c=is.image_size >> 16 & 0xFF;
    TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1, TIMEOUT_SEC );
	c=is.image_size >> 8 & 0xFF;
    TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1, TIMEOUT_SEC );
	c=is.image_size & 0xFF;
    TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1, TIMEOUT_SEC );
	//0-CRC off   1-CRC on     2-Checksum
	c=0;
	crcon=c;

	TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1, TIMEOUT_SEC );

	fileBuffer = (UInt8*)calloc(1,hFlashloaderSize[0]) ;
	memcpy((void *)fileBuffer,(void *)hFlashloader[0],hFlashloaderSize[0]);
	g_nProgressCounter=0;
	
	
	ShowStatus("\n      Send USB Flashloader image\t\t\t");
	for(i=0; i<totblks; i++)
	{
		if( i == (totblks-1) )
			blklength = lastblklength;
		else
			blklength = BLOCK_LENGTH;

		memcpy(block_buff,fileBuffer+i*BLOCK_LENGTH,blklength);
		
		if( crcon == 1 )
			crc16_blk = GetCRC16(block_buff, blklength, 0x0000, 0x11021);

		block_pattern = block_buff[0];
		for(k=0; k<blklength; k++)
		{
			if(block_buff[k] != block_pattern)
			{
				block_pattern = 0x80;
				break;
			}
		}

		k = 0;
		ch = 0xff;
		do
		{
			if(k ++)
				Sleep(100); //printf("R");
			do
			{
				result=TOOL_ReadComPortWithTimeout(&comPortCfg,&ch,1,TIMEOUT_SEC);
			} while( ch != FP_StartReq);
			
			c=FP_StartOK;
			TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1,TIMEOUT_SEC );
			c=blklength>>8;
			TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1,TIMEOUT_SEC );
			c=blklength&0xFF;
			TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1,TIMEOUT_SEC );

			if(blklength == 0)
			{
				AfxMessageBox("\n\rblklength=0");
				break;
			}

			TOOL_WriteComPortWithTimeout( &comPortCfg, &block_pattern,1,TIMEOUT_SEC );
			if(block_pattern == 0x80)
			{
				UInt32 nWrite;
				if( crcon == 2 )
					crc16_blk = 0;

				for(j=0; j<blklength; j++)
				{
					if( crcon == 2 )
						crc16_blk += block_buff[j];
				}
				
				TOOL_WriteComPortWithTimeout(&comPortCfg,block_buff,blklength,TIMEOUT_SEC);
				ShowStatus(">",3);
				g_nProgressCounter+=blklength;
				m_nMainPercent = (g_nProgressCounter * 100) / hFlashloaderSize[0];
				m_progressMain.SetPos(m_nMainPercent);

				if( crcon >= 1 )
				{
					c=crc16_blk>>8;
					TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1,TIMEOUT_SEC  );
					c=crc16_blk&0xFF;
					TOOL_WriteComPortWithTimeout( &comPortCfg, &c,1,TIMEOUT_SEC  );
				}
			}

			result=TOOL_ReadComPortWithTimeout(&comPortCfg,&ch,1,TIMEOUT_SEC);
			if (ch != FP_ImageOK )
			{
				ShowStatus(" Fail\r",4);
				AfxMessageBox("USB Flashloader send fail!");
				goto _cleanup;
			}

		}while( ch != FP_ImageOK );

	}

	while(RESULT_OK==TOOL_ReadComPortWithTimeout(&comPortCfg,&ch,1,TIMEOUT_SEC))
	{
		if (ch!=FP_Finished)
			Sleep(10);
	}

	ShowStatus(" OK\n",3);
	// ID Check

	ShowStatus("\n      Check NOR Flash ID & Initialize flash\t\t> > >");
	result=TOOL_FlashIDCheck(&comPortCfg,0);
	result=TOOL_ReadComPortWithTimeout(&comPortCfg, &ch, 1, TIMEOUT_SEC );
	if (!FlashCheck(ch))
	{
		str.Format(" FAIL\n",4);
		ShowStatus(str,4);
		str.Format("\n  Turn On/Off the target phone!!!\n");
		ShowStatus(str,4);
		TOOL_CloseComPort( &comPortCfg ) ;
		InitControls();
		return false;
	}
	ShowStatus(" OK\n",3);

	ShowStatus("      Check NAND Flash ID & Initialize flash\t\t> > >");
	result=TOOL_FlashIDCheck(&comPortCfg,1);
	result=TOOL_ReadComPortWithTimeout(&comPortCfg, &ch, 1, TIMEOUT_SEC );
	if (!FlashCheck(ch))
	{
		str.Format(" FAIL\n",4);
		ShowStatus(str,4);
		str.Format("\n  Turn On/Off the target phone!!!\n");
		ShowStatus(str,4);
		TOOL_CloseComPort( &comPortCfg ) ;
		InitControls();
		return false;
	}
	ShowStatus(" OK\n",3);

	ShowStatus("\r      Download mode -> ");

	return nCon_Result;

_cleanup:
	

	ReadyControls();
	TOOL_CloseComPort( &comPortCfg ) ;
	return nCon_Result;

}

void CCabrio_downloaderv01Dlg::OnButtonDisconnect() 
{
	// TODO: Add your control notification handler code here
	CString str;
	Result_t result;
	
	bConnect=false;
	str.Format("\0");
	m_ctrlNFlash.SetWindowText("Disconnected");
	m_ctrlConnect.SetWindowText("Disconnected");
	cDriverStatus=CURRENT_WITHOUT_DRIVER;

	if (nConnectMode==USB_MODE)
	{
		result=TOOL_CloseComPort(&comPortCfg);
		if (result!=RESULT_OK)
			AfxMessageBox("Close comport error");
		Sleep(1000);
	}
	ReadyControls();
}


void CCabrio_downloaderv01Dlg::OnButtonDlbootloader() 
{
	// TODO: Add your control notification handler code here

	CBootloaderDlg hDialog;
	
	if(hDialog.DoModal() == IDCANCEL)
	{
		return;
	}

	LockControls();
	
	UpdateData(true);
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		goto init;

	pThread=AfxBeginThread(DlbootloaderThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST  );


init:
;
//	InitControls();
	
}

void CCabrio_downloaderv01Dlg::OnButtonCabrio() 
{
	// TODO: Add your control notification handler code here
	
}

#define INFO_LENGTH	235

void CCabrio_downloaderv01Dlg::OnButtonInfo() 
{
	// TODO: Add your control notification handler code here

	CFile File;
	CString str;
	char * ps = new char[INFO_LENGTH];
	unsigned char * v_code = new unsigned char[4];
	unsigned long startAddr,imageSize;

	if (!m_strImageFileName.Compare("\0"))
	{
		AfxMessageBox("imgset file not selected");
		return;
	}


	if(!File.Open(m_strImageFileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
	{
		AfxMessageBox("Image File open Error");
		return;
	}

	File.Read(&startAddr,4);
	File.Read(&imageSize,4);
	File.Seek(imageSize,CFile::current);

	File.Seek(132,CFile::current);
	File.Read(v_code,4);
	if (v_code[0]==0xcc && v_code[1]==0xae && v_code[2]==0xce && v_code[3]==0xaa)
	{
	
	//	File.Seek(4,CFile::current);
		File.Read(ps,INFO_LENGTH);
	


		str.Format("%s",ps);
	//	ShowStatus(ps,4);
		MessageBox(ps,"Build Information",MB_OK);

		
	}
	else
	{
		AfxMessageBox("Invalid imgset file");
	}
	delete v_code;
	delete ps;
}

void CCabrio_downloaderv01Dlg::OnButtonBchk() 
{
	// TODO: Add your control notification handler code here
	LockControls();
	UpdateData(true);
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		goto init;


	
	if (cDriverStatus==CURRENT_NOR_DRIVER)
	{
		DisconnectMS();
		cDriverStatus=CURRENT_WITHOUT_DRIVER;
	}


	pThread=AfxBeginThread(BadBlkCheckThreadFunc, (LPVOID)this, THREAD_PRIORITY_HIGHEST  );

	
	init:
	;
	
}

void CCabrio_downloaderv01Dlg::OnButtonNandEntireFlash() 
{
	// TODO: Add your control notification handler code here
	// TODO: Add your control notification handler code here
	char szFilter[] = "*.dmp File(*.dmp)|*.dmp|*.*|*.*||";
	CFile File;
	unsigned long fsize=0;
	CFileDialog dlg(TRUE, NULL, m_strEntireFlashFileName, OFN_HIDEREADONLY,szFilter);
	
	if(dlg.DoModal() == IDOK)
	{
		m_strEntireFlashFileName = dlg.GetPathName();	
		if(File.Open(m_strEntireFlashFileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
		{
			 
			fsize=File.GetLength(); 
			if (fsize!=ENTIRE_FLASH_SIZE)
			{
				AfxMessageBox("File size must be 62.75MB");
				File.Close();
				return;
			}
			else
			{
				m_editEntireFlashPath.SetWindowText((LPCTSTR) dlg.GetPathName());
				File.Close();
			}
		}
		else
		{
			AfxMessageBox("File open failed");
			return;
		}

		AfxGetApp()->WriteProfileString("CabrioDL", "m_strEntireFlashFileName",m_strEntireFlashFileName);
	}
}

void CCabrio_downloaderv01Dlg::OnButtonBootloaderErase() 
{
	// TODO: Add your control notification handler code here
	COKDialog hDialog;
	

	if (cActionType!=DWL_ALL)
	{
		if(hDialog.DoModal() == IDCANCEL)
		{
			InitControls();
			return;
		}
	}
	
	LockControls();
	UpdateData(true);
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		goto init;
	
	cActionType=OP_ERASE_BOOTLOADER;

	if (cDriverStatus==CURRENT_NAND_DRIVER)
	{
		DisconnectMS();
		cDriverStatus=CURRENT_WITHOUT_DRIVER;
	}
	


	pThread=AfxBeginThread(NorEraseThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST  );
init:
	;
	
}

void CCabrio_downloaderv01Dlg::OnButtonNorAllerase() 
{
	// TODO: Add your control notification handler code here
	COKDialog hDialog;
	

	if (cActionType!=DWL_ALL)
	{
		if(hDialog.DoModal() == IDCANCEL)
		{
			InitControls();
			return;
		}
	}
	
	LockControls();
	UpdateData(true);
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		goto init;
	
	cActionType=OP_NOR_ERASE;

	if (cDriverStatus==CURRENT_NAND_DRIVER)
	{
		DisconnectMS();
		cDriverStatus=CURRENT_WITHOUT_DRIVER;
	}
	


	pThread=AfxBeginThread(NorEraseThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST  );
init:
	;
	
}

void CCabrio_downloaderv01Dlg::OnButtonNorDump() 
{
	// TODO: Add your control notification handler code here
	LockControls();
	UpdateData(true);
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		goto init;
	
	cActionType=OP_NOR_DUMP;

	
	


	pThread=AfxBeginThread(NorDumpThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST  );
init:
	;
}

void CCabrio_downloaderv01Dlg::OnButtonNandDump() 
{
	// TODO: Add your control notification handler code here
	LockControls();
	UpdateData(true);
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		goto init;
	
	cActionType=OP_NAND_DUMP;
	


	pThread=AfxBeginThread(NandDumpThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST  );
init:
	;
}



bool CCabrio_downloaderv01Dlg::NorDump(UInt8 cActionType)
{
	
	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2,dname;
	Result_t result;
	bool rslt;
	char * arg_device;
	unsigned long startAddr,length;

	CNorDumpDialog hDialog;
	
	if(hDialog.DoModal() == IDCANCEL)
	{
		InitControls();
		return false;
	}
	else
	{

		if (!(hDialog.m_fAddress>=0 && hDialog.m_fAddress<=0x1FFFFFE
			&& hDialog.m_fAddress<hDialog.m_tAddress 
			&& hDialog.m_tAddress>=1 && hDialog.m_tAddress<=0x1FFFFFF))
		{
			MessageBox("Dump range invalid","Error");
			InitControls();
			return false;
		}

		g_nDownloadedSector=GetSectorNum(hDialog.m_fAddress,hDialog.m_tAddress-hDialog.m_fAddress);
		startAddr=hDialog.m_fAddress;
		length=hDialog.m_tAddress-hDialog.m_fAddress;
		temp_nfrom=startAddr;
		all_size=0;
		used_size=0;
	}

	str.Format("nordump0x%lx_0x%lx.dmp",startAddr,startAddr+length);
	CFileDialog fdialog(FALSE, str, str, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
									  "All Files (*.*)|*.*|All Files (*.*)|*.*||" );
						
	if (IDOK==fdialog.DoModal())
	{
		dname = fdialog.GetPathName();
		m_editFileName.SetWindowText(str);
	}
	else
	{
		MessageBox("File select canceled","Error");
		InitControls();
		return false;
	}

	rslt = m_DumpFile.Open( dname, CFile::modeCreate | CFile::modeWrite );
	if ( rslt == FALSE )
	{
		AfxMessageBox("Internal Error! (file creation)");
		return false;
	}

	if (cDriverStatus==CURRENT_NAND_DRIVER)
	{
		DisconnectMS();
		cDriverStatus=CURRENT_WITHOUT_DRIVER;
	}
	


	str.Format("COM%d",m_ComPort+1);
	arg_device=LPSTR(LPCTSTR(str));
	if (nConnectMode==UART_MODE)
	{
		if ( (cDriverStatus==CURRENT_WITHOUT_DRIVER) || (cDriverStatus==CURRENT_NAND_DRIVER))
		{
			rslt=NorDriverDownload(&comPortCfg,1);
			if (rslt==false)
				goto _cleanup;
		}
	}


	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	str2.Format("\n  * NOR Flash DUMP");
	ShowStatus(str2,4);




	
	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");
		rslt=false;
		goto _cleanup;
	}

	if (nConnectMode==UART_MODE)
	{
		str2.Format("\n    Open Comport\t\t\t\t> > > ");
		ShowStatus(str2);	

	//	Sleep(1000*1);
		comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

		if (comPort==0)
		{
			str2.Format("FAIL");
			ShowStatus(str,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

	//	Sleep(1000*3);
		if( initBaudRate != dnldBaudRate ) 
		{
			str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
			ShowStatus(str2);

			result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
			if( RESULT_OK != result )
			{
				str2.Format("FAIL\n");
				ShowStatus(str2,4);
				rslt=false;
				goto _cleanup;	
			}
			else
			{
				str2.Format("OK");
				ShowStatus(str2,3);
			}

			TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
		}
	}

	Sleep(1000*1);

	
	
	str.Format("\n    Now DUMP start!!\n");
	ShowStatus(str);
	str2.Format("-----------------------------------------------------------------------------------------------\n");
	ShowStatus(str2);
	
	
	
	
	if (nConnectMode==UART_MODE)
	{
		result = TOOL_CaptureImage( (UInt8*)dname.GetBuffer(MYBUFF_SIZE)
			,comPort,startAddr,length,FLASHLOADER_CMD_NOR_CAPTURE_IMAGE,ToolProgressCbDump,ToolFileHandleCb);
	}
	else
	{
		result = TOOL_CaptureImage( (UInt8*)dname.GetBuffer(MYBUFF_SIZE)
			,&comPortCfg,startAddr,length,FLASHLOADER_CMD_NOR_CAPTURE_IMAGE,ToolProgressCbDump,ToolFileHandleCb);
	}
	if( RESULT_OK != result ) 
	{
		str.Format("\r\n\r\n -  Fail!!!!!!!!");
		ShowStatus(str,4);
		str.Format( "Error flashing erase : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		
		goto _cleanup;
	}
		
	if (nConnectMode==UART_MODE)
	{
		//flashdrv_nandimg downloading successfully..
		if( initBaudRate != dnldBaudRate ) 
		{
			result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
			if( RESULT_OK != result ) 
			{
				str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
				AfxMessageBox(str);	
				rslt=false;
				goto _cleanup;
			}

			TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
		}
	}
	ShowStatus("\n\n      DUMP");

	str.Format("  Completed!!!\n");
	ShowStatus(str,3);

	rslt=true;
	cDriverStatus=CURRENT_NOR_DRIVER;
_cleanup:
	if (nConnectMode==UART_MODE)
		TOOL_CloseDnldPort( comPort );
	
	if (result==RESULT_OK)
		MessageBox("DUMP complete","NOTICE");
	InitControls();
	m_ctrCN.EnableWindow(true);
	return rslt;
}

bool CCabrio_downloaderv01Dlg::NandDump(UInt8 cActionType)
{
	
	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2,dname;
	Result_t result;
	bool rslt,nErase,IsTmpFile;
	char * arg_device;
	unsigned long startAddr,length;

	CNandDump hDialog;
	
	if(hDialog.DoModal() == IDCANCEL)
	{
		InitControls();
		return false;
	}
	else
	{

		if (!(hDialog.m_fAddress>=0 && hDialog.m_fAddress<=0x3FFFFFE
			&& hDialog.m_fAddress<hDialog.m_tAddress 
			&& hDialog.m_tAddress>=1 && hDialog.m_tAddress<=0x3FFFFFF))
		{
			MessageBox("Dump range invalid","Error");
			InitControls();
			return false;
		}

		g_nDownloadedSector=GetSectorNum2(hDialog.m_fAddress,hDialog.m_tAddress-hDialog.m_fAddress);
		startAddr=hDialog.m_fAddress;
		length=hDialog.m_tAddress-hDialog.m_fAddress+1;
		temp_nfrom=startAddr;
		all_size=0;
		used_size=0;

		// Erase  ƴ üũ 
		if (hDialog.m_boolErase==TRUE)
			nErase=TRUE;
		else
			nErase=FALSE;
	}
	
	if (startAddr==TFS_START_ADDR)
	{
		str.Format("tfs_area_dump.dmp");
	}
	else
	{
		str.Format("nanddump0x%lx_0x%lx.dmp",startAddr,startAddr+length);
	}
	CFileDialog fdialog(FALSE, str, str, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
									  "All Files (*.*)|*.*|All Files (*.*)|*.*||" );
						
	if (IDOK==fdialog.DoModal())
	{
		dname = fdialog.GetPathName();
		m_editFileName.SetWindowText(str);
	}
	else
	{
		MessageBox("File select canceled","Error");
		InitControls();
		return false;
	}
	
	if (nErase==FALSE)
	{
		IsTmpFile = m_DumpFile.Open( dname, CFile::modeCreate | CFile::modeWrite );
		if ( IsTmpFile == FALSE )
		{
			AfxMessageBox("Internal Error! (file creation)");
			return false;
		}
	}

	if (cDriverStatus==CURRENT_NOR_DRIVER)
	{
		DisconnectMS();
		cDriverStatus=CURRENT_WITHOUT_DRIVER;
	}

	str.Format("COM%d",m_ComPort+1);
	arg_device=LPSTR(LPCTSTR(str));

	if (nConnectMode==UART_MODE)
	{
		if ( (cDriverStatus==CURRENT_WITHOUT_DRIVER) || (cDriverStatus==CURRENT_NOR_DRIVER))
		{
			rslt=NandDriverDownload(&comPortCfg,1);
			if (rslt==false)
				goto _cleanup;
		}
	}

	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	if (nErase==FALSE)
	{
		str2.Format("\n  * NAND Flash DUMP");
		ShowStatus(str2,4);
	}
	else
	{
		str2.Format("\n  * NAND Flash partial erase");
		ShowStatus(str2,4);
	}




	
	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");
		rslt=false;
		goto _cleanup;
	}


	if (nConnectMode==UART_MODE)
	{
		str2.Format("\n    Open Comport\t\t\t\t> > > ");
		ShowStatus(str2);

	//	Sleep(1000*1);
		comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

		if (comPort==0)
		{
			str2.Format("FAIL");
			ShowStatus(str,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

	//	Sleep(1000*3);
		if( initBaudRate != dnldBaudRate ) 
		{
			str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
			ShowStatus(str2);

			result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
			if( RESULT_OK != result )
			{
				str2.Format("FAIL\n");
				ShowStatus(str2,4);
				rslt=false;
				goto _cleanup;	
			}
			else
			{
				str2.Format("OK");
				ShowStatus(str2,3);
			}

			TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
		}
	}


	Sleep(1000*1);



	if (nErase==FALSE)
	{
		str.Format("\n    Now DUMP start!!\n");
		ShowStatus(str);
	}
	else
	{
		str.Format("\n    Now Partial erase start!!\n");
		ShowStatus(str);
	}
	str2.Format("-----------------------------------------------------------------------------------------------\n");
	ShowStatus(str2);

	if (nConnectMode==UART_MODE)
	{
		if (nErase==FALSE)
		{
			result = TOOL_CaptureImage( (UInt8*)dname.GetBuffer(MYBUFF_SIZE)
			,comPort,startAddr,length,FLASHLOADER_CMD_NAND_CAPTURE_IMAGE,ToolProgressCbDump,ToolFileHandleCb);
		}
		else
		{
			result = TOOL_PartialErase(comPort,startAddr,length,ToolProgressCbDump);
		}
	}
	else
	{
		if (nErase==FALSE)
		{
			result = TOOL_CaptureImage( (UInt8*)dname.GetBuffer(MYBUFF_SIZE)
			,&comPortCfg,startAddr,length,FLASHLOADER_CMD_NAND_CAPTURE_IMAGE,ToolProgressCbDump,ToolFileHandleCb);
		}
		else
		{
			result = TOOL_PartialErase(&comPortCfg,startAddr,length,ToolProgressCbDump);
		}
	}

	
	
	if( RESULT_OK != result ) 
	{
		str.Format("\r\n\r\n -  Fail!!!!!!!!");
		ShowStatus(str,4);
		str.Format( "Error flashing erase : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		
		goto _cleanup;
	}
	
	if (nConnectMode==UART_MODE)
	{

		Sleep(1000*2);
		//flashdrv_nandimg downloading successfully..
		if( initBaudRate != dnldBaudRate ) 
		{
			result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
			if( RESULT_OK != result ) 
			{
				str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
				AfxMessageBox(str);	
				rslt=false;
				goto _cleanup;
			}

			TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
		}
	}
	ShowStatus("\n\n      DUMP");

	str.Format("  Completed!!!\n");
	ShowStatus(str,3);
	
	m_DumpFile.Close();
	rslt=true;
	cDriverStatus=CURRENT_NAND_DRIVER;
_cleanup:
	if (nConnectMode==UART_MODE)
		TOOL_CloseDnldPort( comPort );
	
	if (result==RESULT_OK)
		MessageBox("DUMP Complete","NOTICE");
	InitControls();
	m_ctrCN.EnableWindow(true);
	return rslt;
}

void CCabrio_downloaderv01Dlg::TfsExplorer(UInt8 cActionType) 
{
	// TODO: Add your control notification handler code here
	void * comPort;
	UInt8 initBaudRate,dnldBaudRate;
	CString str,str2;
	Result_t result;
	bool rslt;
	char * arg_device;
	unsigned long startAddr,length;
//	CTfsExplorer hDialog;
	
	if (cDriverStatus==CURRENT_NOR_DRIVER)
	{
		DisconnectMS();
		cDriverStatus=CURRENT_WITHOUT_DRIVER;
	}

	str.Format("COM%d",m_ComPort+1);
	arg_device=LPSTR(LPCTSTR(str));

	if ( (cDriverStatus==CURRENT_WITHOUT_DRIVER) || (cDriverStatus==CURRENT_NOR_DRIVER))
	{
		rslt=NandDriverDownload(&comPortCfg,1);
		if (rslt==false)
			goto _cleanup;
	}


	initBaudRate=g_BaudRate[0];
	dnldBaudRate=g_BaudRate[m_cbxBaudRate.GetCurSel()];

	str2.Format("\n  * TFS Explorer");
	ShowStatus(str2,4);


	if( (!initBaudRate ) || (!dnldBaudRate ))
	{
		AfxMessageBox("BaudRate Error");
		rslt=false;
		goto _cleanup;
	}

	str2.Format("\n    Open Comport\t\t\t\t> > > ");
	ShowStatus(str2);

	

//	Sleep(1000*1);
	comPort = TOOL_OpenDnldPort( (UInt8*)arg_device , initBaudRate ) ;

	if (comPort==0)
	{
		str2.Format("FAIL");
		ShowStatus(str,4);
		rslt=false;
		goto _cleanup;	
	}
	else
	{
		str2.Format("OK");
		ShowStatus(str2,3);
	}

//	Sleep(1000*3);
	if( initBaudRate != dnldBaudRate ) 
	{
		str2.Format("\n    Set Target Phone BaudRate\t\t> > > ");
		ShowStatus(str2);

		result = TOOL_SetTargetBaudRate( comPort, dnldBaudRate,0) ;
		if( RESULT_OK != result )
		{
			str2.Format("FAIL\n");
			ShowStatus(str2,4);
			rslt=false;
			goto _cleanup;	
		}
		else
		{
			str2.Format("OK");
			ShowStatus(str2,3);
		}

		TOOL_ChangeComPortBaudRate( comPort, dnldBaudRate ) ;
	}


	Sleep(1000*1);



	str.Format("\n    Now Explorer start!!\n");
	ShowStatus(str);
	str2.Format("-----------------------------------------------------------------------------------------------\n");
	ShowStatus(str2);

	result = TOOL_TfsExplorer(comPort,0x0);
	
	if( RESULT_OK != result ) 
	{
		str.Format("\r\n\r\n -  Fail!!!!!!!!");
		ShowStatus(str,4);
		str.Format( "Error flashing erase : %s\n",TOOL_GetResultStr( result ));
		AfxMessageBox(str);
		rslt=false;
		
		goto _cleanup;
	}
	
	
	
/*	hDialog.SetComport(comPort);

	if(hDialog.DoModal() == IDCANCEL)
	{
	//	InitControls();
	//	return false;
	}*/


	//flashdrv_nandimg downloading successfully..
	if( initBaudRate != dnldBaudRate ) 
	{
		result = TOOL_SetTargetBaudRate( comPort, initBaudRate,0 ) ;
		if( RESULT_OK != result ) 
		{
			str.Format( "Error  changing target baud rate : %s\n",TOOL_GetResultStr( result ));
			AfxMessageBox(str);	
			rslt=false;
			goto _cleanup;
		}

		TOOL_ChangeComPortBaudRate( comPort, initBaudRate ) ;
	}
	
	ShowStatus("\n\n      DUMP");

	str.Format("  Completed!!!\n");
	ShowStatus(str,3);

	rslt=true;
	cDriverStatus=CURRENT_NAND_DRIVER;
_cleanup:
	TOOL_CloseDnldPort( comPort );
	
	if (result==RESULT_OK)
		MessageBox("DUMP Complete","NOTICE");
	InitControls();
	m_ctrCN.EnableWindow(true);
//	return rslt;
	
}
/*
void CCabrio_downloaderv01Dlg::OnButtonTfsExplorer() 
{
	// TODO: Add your control notification handler code here
	LockControls();
	UpdateData(true);
	if (m_ComPort==-1 && m_cbxBaudRate.GetCurSel()==NULL)
		goto init;
	
	cActionType=OP_NAND_DUMP;

	
	


	pThread=AfxBeginThread(TfsExplorerThreadFunc,(LPVOID)this, THREAD_PRIORITY_HIGHEST  );
init:
	;
}
*/


void CCabrio_downloaderv01Dlg::OnChangeEditManual() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	// TODO: Add your control notification handler code here
		UpdateData(true);



	CString str,str2;	
	int tempBlock,tempPagenum,tempOffset;
	static bool bFirstAccess=FALSE;

//	str.GetLength
	GetDlgItemText(IDC_EDIT_MANUAL,str);

	//Է¹߿ 16   ð üũ
	if (!IsHex(str))
	{
		MessageBox("Wrong value","WARNING");
		SetDlgItemText(IDC_EDIT_MANUAL,"0");
		UpdateData(true);
		return;
	}

	//Է¹ 16(ڿ) 16()· ȯ
	m_fAddress=ConvHex(str);
	
	//Է¹   Ѿ MAX ڵ 
	//MAX 1   1byte ĸİ ʿ2
	
/*	if (m_fAddress<0xfff)
	{
		m_fAddress=0x1000;
		SetDlgItemText(IDC_EDIT_MANUAL,"1000");
		UpdateData(true);
		return;
	}*/


	if (m_fAddress>0x1FFFFFE)
	{
		m_fAddress=0x1FE0000;
		SetDlgItemText(IDC_EDIT_MANUAL,"1FE0000");
		UpdateData(true);
		return;
	}

	
	
}


int CCabrio_downloaderv01Dlg::ConvHex(const CString & str)
{
	int total=0;
	int len=str.GetLength();
	int len2=len-1;

	char * ss=LPSTR(LPCTSTR(str));

	for (int i=0;i<len;i++)
	{
		if (ss[i]=='a' || ss[i]=='A')
		{
			total+=10*pow(16,len2);
			len2--;
			continue;
		}
		if (ss[i]=='b' || ss[i]=='B')
		{
			total+=11*pow(16,len2);
			len2--;
			continue;
		}
		if (ss[i]=='c' || ss[i]=='C')
		{
			total+=12*pow(16,len2);
			len2--;
			continue;
		}
		if (ss[i]=='d' || ss[i]=='D')
		{
			total+=13*pow(16,len2);
			len2--;
			continue;
		}
		if (ss[i]=='e' || ss[i]=='E')
		{
			total+=14*pow(16,len2);
			len2--;
			continue;
		}
		if (ss[i]=='f' || ss[i]=='F')
		{
			total+=15*pow(16,len2);
			len2--;
			continue;
		}
	
		total+=(ss[i]-48)*pow(16,len2);
		len2--;

	}
	return total;
}

int CCabrio_downloaderv01Dlg::IsHex(const CString &st)
{
	int total=0;
	int len=st.GetLength();
	int len2=len-1;

		char * ss=LPSTR(LPCTSTR(st));

	
	
	for (int i=0;i<len;i++)
	{
		if (ss[i]>='0' && ss[i]<='9')
			continue;
		if (ss[i]=='a' || ss[i]=='A')
			continue;
		if (ss[i]=='b' || ss[i]=='B')
			continue;
		if (ss[i]=='c' || ss[i]=='C')
			continue;
		if (ss[i]=='d' || ss[i]=='D')
			continue;
		if (ss[i]=='e' || ss[i]=='E')
			continue;
		if (ss[i]=='f' || ss[i]=='F')
			continue;
		return 0;
	}
	return 1;

}

void CCabrio_downloaderv01Dlg::OnButtonManualImage() 
{
	// TODO: Add your control notification handler code here

	
	char szFilter[] = "?.img File(*.img)|*.img|*.*|*.*||";
	CFile File;

	CFileDialog dlg(TRUE, NULL, m_strManualImage, OFN_HIDEREADONLY,szFilter);
		
	if(dlg.DoModal() == IDOK)
	{
		m_strManualImage = dlg.GetPathName();
		if(File.Open(m_strManualImage,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
		{	
			m_editManualImagePath.SetWindowText((LPCTSTR) dlg.GetPathName());
			File.Close();
		}
		else
		{
			AfxMessageBox("Image File Size Error");
		}

		AfxGetApp()->WriteProfileString("CabrioDL", "m_strManualImage",m_strManualImage);
	}

}

void CCabrio_downloaderv01Dlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	
	CString str,str_month,str_day,str_year,month,day;
	CDialog::OnTimer(nIDEvent);
	CTime nTime=CTime::GetCurrentTime();
	char * cMonth;  //ð ´.
	char * cDay;
	int nMonth=0;
	str.Format("%d.%d.%d   %d:%d:%d", nTime.GetYear(), nTime.GetMonth(), nTime.GetDay(),nTime.GetHour(),nTime.GetMinute(),nTime.GetSecond());
	m_editTime.SetWindowText(str);

	month=nTime.GetMonth();
	if (month<0xa)
		str_month.Format("0%d",nTime.GetMonth());
	else
		str_month.Format("%d",nTime.GetMonth());

	day=nTime.GetDay();
	if (day<0xa)
		str_day.Format("0%d",nTime.GetDay());
	else
		str_day.Format("%d",nTime.GetDay());

	cMonth=LPSTR(LPCTSTR(str_month));
	cDay=LPSTR(LPCTSTR(str_day));
	str_year.Format("%d",nTime.GetYear());

//	str_time.Format("%d%d%d",nTime.GetYear(),cMonth,cDay);
	str_time=str_year+str_month+str_day;
//	UpdateData(FALSE); 
}

void CCabrio_downloaderv01Dlg::OnButtonManualNandImage() 
{
	// TODO: Add your control notification handler code here
	char szFilter[] = "?.img File(*.img)|*.img|*.*|*.*||";
	CFile File;

	CFileDialog dlg(TRUE, NULL, m_strManualNandImage, OFN_HIDEREADONLY,szFilter);
		
	if(dlg.DoModal() == IDOK)
	{
		m_strManualNandImage = dlg.GetPathName();
		if(File.Open(m_strManualNandImage,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
		{	
			m_editManualNandImagePath.SetWindowText((LPCTSTR) dlg.GetPathName());
			File.Close();
		}
		else
		{
			AfxMessageBox("Image File Size Error");
		}

		AfxGetApp()->WriteProfileString("CabrioDL", "m_strManualNandImage",m_strManualNandImage);
	}
	
}

void CCabrio_downloaderv01Dlg::OnChangeEditManualNand() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(true);



	CString str,str2;	
	int tempBlock,tempPagenum,tempOffset;
	static bool bFirstAccess=FALSE;

//	str.GetLength
	GetDlgItemText(IDC_EDIT_MANUAL_NAND,str);

	//Է¹߿ 16   ð üũ
	if (!IsHex(str))
	{
		MessageBox("Wrong value","WARNING");
		SetDlgItemText(IDC_EDIT_MANUAL_NAND,"0");
		UpdateData(true);
		return;
	}

	//Է¹ 16(ڿ) 16()· ȯ
	m_fAddress=ConvHex(str);
	
	//Է¹   Ѿ MAX ڵ 
	//MAX 1   1byte ĸİ ʿ2
	
/*	if (m_fAddress<0xfff)
	{
		m_fAddress=0x1000;
		SetDlgItemText(IDC_EDIT_MANUAL,"1000");
		UpdateData(true);
		return;
	}*/


	if (m_fAddress>0x3E60000)
	{
		m_fAddress=0x3E40000;
		SetDlgItemText(IDC_EDIT_MANUAL_NAND,"3E40000");
		UpdateData(true);
		return;
	}
}

void CCabrio_downloaderv01Dlg::OnRadioUart() 
{
	// TODO: Add your control notification handler code here
	
}

void CCabrio_downloaderv01Dlg::OnRadioUsb() 
{
	// TODO: Add your control notification handler code here
	
}

void CCabrio_downloaderv01Dlg::OnButtonCalInfo() 
{
	// TODO: Add your control notification handler code here
	// TODO: Add your control notification handler code here
	CFile File;
	CString str;
	DWORD Checksum = 0;
	BYTE * buffer;

	unsigned long fileSize;

	if (!m_strParamDepFileName.Compare("\0"))
	{
		AfxMessageBox("Calset file not selected");
		return;
	}


	if(!File.Open(m_strParamDepFileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
	{
		AfxMessageBox("Calset File open Error");
		return;
	}

		fileSize=File.GetLength();

		buffer = new BYTE[fileSize];
		File.ReadHuge(buffer,fileSize);
		File.Close();
		for( int i=0; i < fileSize; i++ )
		{
			
			Checksum += buffer[i];
		}
		
		str.Format("File size : %d byte\r\nChecksum : 0x%x",fileSize,Checksum);

		MessageBox(str,"Calset Information",MB_OK);

	
	delete buffer;
}

void CCabrio_downloaderv01Dlg::OnButtonRsrcInfo() 
{
	// TODO: Add your control notification handler code here
	CFile File;
	CString str;
	DWORD Checksum = 0;
	BYTE * buffer;

	unsigned long fileSize;

	if (!m_strRscrFileName.Compare("\0"))
	{
		AfxMessageBox("Rsrc file not selected");
		return;
	}


	if(!File.Open(m_strRscrFileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
	{
		AfxMessageBox("Rsrc File open Error");
		return;
	}

		fileSize=File.GetLength();

		buffer = new BYTE[fileSize];
		File.ReadHuge(buffer,fileSize);
		File.Close();
		for( int i=0; i < fileSize; i++ )
		{
			
			Checksum += buffer[i];
		}
		
		str.Format("File size : %d byte\r\nChecksum : 0x%x",fileSize,Checksum);

		MessageBox(str,"Rsrc Information",MB_OK);

	
	delete buffer;
	
}

void CCabrio_downloaderv01Dlg::OnButtonRsrc2Info() 
{
	// TODO: Add your control notification handler code here
	CFile File;
	CString str;
	DWORD Checksum = 0;
	BYTE * buffer;

	unsigned long fileSize;

	if (!m_strRscr2FileName.Compare("\0"))
	{
		AfxMessageBox("Rsrc2 file not selected");
		return;
	}


	if(!File.Open(m_strRscr2FileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
	{
		AfxMessageBox("Rsrc2 File open Error");
		return;
	}

		fileSize=File.GetLength();

		buffer = new BYTE[fileSize];
		File.ReadHuge(buffer,fileSize);
		File.Close();
		for( int i=0; i < fileSize; i++ )
		{
			
			Checksum += buffer[i];
		}
		
		str.Format("File size : %d byte\r\nChecksum : 0x%x",fileSize,Checksum);

		MessageBox(str,"Rsrc2 Information",MB_OK);

	
	delete buffer;
}

void CCabrio_downloaderv01Dlg::OnButtonFacInfo() 
{
	// TODO: Add your control notification handler code here
	CFile File;
	CString str;
	DWORD Checksum = 0;
	BYTE * buffer;

	unsigned long fileSize;

	if (!m_strFactoryFSFileName.Compare("\0"))
	{
		AfxMessageBox("FactoryFS file not selected");
		return;
	}


	if(!File.Open(m_strFactoryFSFileName,CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone))
	{
		AfxMessageBox("FactoryFS File open Error");
		return;
	}

		fileSize=File.GetLength();

		buffer = new BYTE[fileSize];
		File.ReadHuge(buffer,fileSize);
		File.Close();
		for( int i=0; i < fileSize; i++ )
		{
			
			Checksum += buffer[i];
		}
		
		str.Format("File size : %d byte\r\nChecksum : 0x%x",fileSize,Checksum);

		MessageBox(str,"FactoryFS Information",MB_OK);

	
	delete buffer;
}
