

//---------------------------------------------------------------------------

#include <vcl.h>
#include <inifiles.hpp>
#pragma hdrstop

#include "Download_Form.h"
#include "Environment.h"
#include "common.h"
#include "command.h"
#include "Message_Form.h"
#include "SystemSetup.h"
#include "CameraSetting3D_Form.h"
#include "CPBStatus_Form.h"
#include "Waiting_Form.h"
#include "MultiLanguage.h"

#include <windows.h>
#include <process.h>
#include <io.h>
#include <conio.h>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TntButtons"
#pragma link "TntDialogs"
#pragma link "TntExtCtrls"
#pragma link "TntGrids"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"

#define	BLOCKS_PER_DEIVCE	1024
#define FFS_INFO_MAX_COUNT	1024

typedef int TFFID;

typedef struct
{
	TFFID id;
	int startBlock;
	int size;
	int updatedTime;
	int reserved[4];
} TFFInfo;

typedef struct {
	unsigned short fat[BLOCKS_PER_DEIVCE];
	TFFInfo fileInfo[FFS_INFO_MAX_COUNT];
} TFFSystem;

TDownloadForm *DownloadForm;

DWORD ThreadDword = 0;
HANDLE CPBDownloadThreadHandle;

//---------------------------------------------------------------------------
unsigned int WINAPI CPBProgramThread(PVOID pData)
{
 TDownloadForm* DownLoadMainForm = (TDownloadForm*)pData;

 int downloadCount = 0;
 TTntSpeedButton *AllSpeedButton =  DownLoadMainForm->GetSpeedBtnPtr(100);
 for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
  {
    if(DownLoadMainForm->GetbEnabledSPB(spbIndex))
    {
      TTntSpeedButton *spbSpeedButton =  DownLoadMainForm->GetSpeedBtnPtr(spbIndex);

      if (Comm_IsConnected(COMM_SPB + spbIndex) && (AllSpeedButton->Down || spbSpeedButton->Down))
      {
        Comm_SetMaxWaitingTime(COMM_SPB + spbIndex, 60000);

        if (Comm_RequestEx(COMM_SPB + spbIndex, CMD_DOWNLOAD, DownLoadMainForm->cpbData, 2 * sizeof(unsigned int),
          DownLoadMainForm->cpbProgramData, DownLoadMainForm->cpbProgramSize))
        {
          SPBSystemSetupData[spbIndex].DefaultCPBProgramID = DownLoadMainForm->cpbProgramID;
          downloadCount++;
        }

        Comm_SetDefaultMaxWaitingTime(COMM_SPB + spbIndex);
      }
    }

    /*if(AllSpeedButton->Down)
    {
      // echo check
      for (int echoCheckSPBIndex = 0; echoCheckSPBIndex < MachineSetupData.IPB_BoardCount; echoCheckSPBIndex++)
      {
        if(DownLoadMainForm->GetbEnabledSPB(echoCheckSPBIndex))
        {
          if (Comm_IsConnected(COMM_SPB + echoCheckSPBIndex))
          {
            Comm_Request(COMM_SPB + echoCheckSPBIndex, CMD_ECHO, NULL, 0, NULL, 0);
          }
        }
      }

      Sleep(100);
    }*/
  }

	if(TPBSystemInfo.boardExist == TPB_BOARD_EXSIT)
	{
	  if (Comm_IsConnected(COMM_TPB) && (AllSpeedButton->Down || DownLoadMainForm->TPBSpeedButton->Down))
	  {
	    Comm_SetMaxWaitingTime(COMM_TPB, 30000);

	    if (Comm_RequestEx(COMM_TPB, CMD_DOWNLOAD, DownLoadMainForm->cpbData, 2 * sizeof(unsigned int),
	      DownLoadMainForm->cpbProgramData, DownLoadMainForm->cpbProgramSize))
	    {
	      downloadCount++;
	    }

	    Comm_SetDefaultMaxWaitingTime(COMM_TPB);
	  }
  }

  DownLoadMainForm->cpbDownLoadCount = downloadCount;
  DownLoadMainForm->cpbDownLoadFinish = true;
  _endthreadex(0);
}

//---------------------------------------------------------------------------
bool __fastcall TDownloadForm::GetbEnabledSPB(int SPBCOUNT)
{
  return bEnabledSPB[SPBCOUNT];
}
//---------------------------------------------------------------------------
TTntSpeedButton* TDownloadForm::GetSpeedBtnPtr(int Number)
{
  if(Number == 100)
    return  (TTntSpeedButton*)FindComponent("AllSpeedButton" );
  else
    return  (TTntSpeedButton*)FindComponent("SPBSpeedButton" + IntToStr(Number + 1));
}
//---------------------------------------------------------------------------
__fastcall TDownloadForm::TDownloadForm(TComponent* Owner)
	: TTntForm(Owner)
{
	if (DefaultLCID == 1028 || DefaultLCID == 2052 || DefaultLCID == 3076 || DefaultLCID == 4100)
		ComponentSetFontName(this, "SimSun");
	else if (DefaultLCID == 1041)
		ComponentSetFontName(this, "Meiryo UI");
  else if(DefaultLCID == 3082)
  {
    ComponentSetFontName(this, "Segoe UI");
    ComponentSetMultiLine(this);
  }

	GetDefaultString();
	currentCommIndex = 0xFF;
	IsCPBRunning = false;

	CheckTPB_BoardExist();  
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::GetDefaultString()
{
	SPBDownloadButton->Caption = DOWNLOADFORM_BUTTON_CAPTION_01;
	CPBDownloadButton->Caption = DOWNLOADFORM_BUTTON_CAPTION_02;
	WriteMachineNameButton->Caption = DOWNLOADFORM_BUTTON_CAPTION_03;
	SPBResetButton->Caption = DOWNLOADFORM_BUTTON_CAPTION_04;
	ReadMachineNameButton->Caption = DOWNLOADFORM_BUTTON_CAPTION_05;
	GroupBox1->Caption = DOWNLOADFORM_GROUPBOX_CAPTION_01;
	Label1->Caption = DOWNLOADFORM_LABEL_CAPTION_01;
    HCBDownloadButton->Caption = DOWNLOADFORM_BUTTON_CAPTION_06;
    HCBSystemSetupButton->Caption 	= "HCB " + DOWNLOADFORM_BUTTON_CAPTION_07;
    SPBSystemSetupButton->Caption 	= "IPB " + DOWNLOADFORM_BUTTON_CAPTION_07;
    HCBResetButton->Caption			= "HCB " + DOWNLOADFORM_BUTTON_CAPTION_08;
    btnReadFlashInfo->Caption		= DOWNLOADFORM_BUTTON_CAPTION_09;
    ExitButton->Caption 			= DOWNLOADFORM_BUTTON_CAPTION_10;
    AllSpeedButton->Caption			= DOWNLOADFORM_BUTTON_CAPTION_11;

    btnFlashFormat->Caption				= DOWNLOADFORM_BUTTON_CAPTION_12;
    ChangeHCBFileNameButton->Caption	= DOWNLOADFORM_BUTTON_CAPTION_13;
    Button1->Caption					= DOWNLOADFORM_BUTTON_CAPTION_13;
    CPBProgramChangeButton1->Caption	= DOWNLOADFORM_BUTTON_CAPTION_13;
    TPBProgramChangeButton->Caption		= DOWNLOADFORM_BUTTON_CAPTION_13;



}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::FormCreate(TObject *Sender)
{
  if (!ReadSPBSystemSetupData(ProgramPath.Env + "\\SystemInfor.ini", SPBSystemSetupData, CameraMapInfo))
	{
		ShowMessageW(ENVIRONMENT_RETURNSTR_08);
	}

	memset(bEnabledSPB, 0, sizeof(bool) * MachineSetupData.IPB_BoardCount);

	if (Comm_IsConnected(COMM_HCB))
	{
		HCBSpeedButton->Enabled = true;
	}
	else
	{
		HCBSpeedButton->Enabled = false;
	}
	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
		TTntSpeedButton *theSpeedButton = (TTntSpeedButton *)FindComponent("SPBSpeedButton" + IntToStr(spbIndex + 1));
    theSpeedButton->Visible = true;
		if (theSpeedButton)
		{
			if (Comm_IsConnected(COMM_SPB + spbIndex))
			{
				theSpeedButton->Enabled = true;
				bEnabledSPB[spbIndex] = true;
			}
			else
			{
				theSpeedButton->Enabled = false;
				bEnabledSPB[spbIndex] = false;
			}
		}
	}

	// load recent file info
	TIniFile *recentIniFile = new TIniFile(ProgramPath.Env + "\\download.ini");
	if (recentIniFile)
	{
		HCBFilenameEdit->Text = recentIniFile->ReadString("HCB", "File Name", "");
		SPBFilenameEdit->Text = recentIniFile->ReadString("SPB", "Tablet File Name", "");
		CPBFilenameEdit->Text = recentIniFile->ReadString("CPB", "Tablet File Name", "");
    TPBFilenameEdit->Text = recentIniFile->ReadString("TPB", "Tablet File Name", "");
		delete recentIniFile;
	}

	BootingTarget = -1;

  RadioGroup1->ItemIndex = MachineSetupData.CompanyID;
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::btnReadFlashInfoClick(TObject *Sender)
{
	AnsiString errorMsg;
	TFFSystem *fileSystem = new TFFSystem;
	if (currentCommIndex == 0xFF)
	{
		ShowMessageFA(DOWNLOADFORM_MSG_05);
		return;
	}
	if (Comm_Request(currentCommIndex, CMD_FLASH_INFO, NULL, 0, fileSystem, sizeof(TFFSystem)))
	{
		sgFlashInfo->RowCount = FFS_INFO_MAX_COUNT;
		sgFlashInfo->Cells[0][0] = "ID";
		sgFlashInfo->Cells[1][0] = "Start Block";
		sgFlashInfo->Cells[2][0] = "Size";
		sgFlashInfo->Cells[3][0] = "Update Time";
		sgFlashInfo->ColWidths[0] = 128;
		sgFlashInfo->ColWidths[1] = 64;
		sgFlashInfo->ColWidths[2] = 64;
		sgFlashInfo->ColWidths[3] = 256;
		WCHAR TempString[100];

    WideString InputData;
    char charData[5];
    memset(charData, 0, 5);
		for (int row = 0; row < FFS_INFO_MAX_COUNT; row++)
		{
			unsigned int id = fileSystem->fileInfo[row].id;
			wsprintfW(TempString, L"0x%08x", id);

      for(int m = 0; m < 4; m++)
      {
        sprintf(&charData[m], "%c", (id >> 8 * (3 - m)));

        if(charData[m] == '\0')
          charData[m] = '0';
      }

      AnsiString IDInterpret;
      IDInterpret = charData;

      InputData = WideString(TempString) + " ("  + WideString(IDInterpret) + ")";

			sgFlashInfo->Cells[0][row + 1] = InputData;

			sgFlashInfo->Cells[1][row + 1] = IntToStr(fileSystem->fileInfo[row].startBlock);
			sgFlashInfo->Cells[2][row + 1] = IntToStr(fileSystem->fileInfo[row].size);
			if (fileSystem->fileInfo[row].size > 0)
			{
				TDateTime updatedTime;
				if (fileSystem->fileInfo[row].updatedTime)
				{
					try
					{
						sgFlashInfo->Cells[3][row + 1] = updatedTime.FileDateToDateTime(fileSystem->fileInfo[row].updatedTime).DateString() + " " +
							updatedTime.FileDateToDateTime(fileSystem->fileInfo[row].updatedTime).TimeString();
					}
					catch (...)
					{
						sgFlashInfo->Cells[3][row + 1] = "Unknown";
					}
				}
			}
			else
			{
				sgFlashInfo->Cells[3][row + 1] = "";
			}
		}
		delete fileSystem;
	}
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::HCBSpeedButtonClick(TObject *Sender)
{
	currentCommIndex = COMM_HCB;
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::SPBSpeedButtonClick(TObject *Sender)
{
	TTntSpeedButton *theSpeedButton = (TTntSpeedButton *)Sender;
	int spbIndex = theSpeedButton->Tag;
	currentCommIndex = COMM_SPB + spbIndex;
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::AllSpeedButtonClick(TObject *Sender)
{
	currentCommIndex = 0xFF;
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::btnFlashFormatClick(TObject *Sender)
{
	if(AllBoardFomatOptCheckBox->Checked == false)
    {
		if (currentCommIndex == 0xFF)
		{
			ShowMessageW(DOWNLOADFORM_MSG_05);
			return;
		}

		if (IDOK == Application->MessageBox("Format?", "TVM_Application", MB_OKCANCEL))
		{
			AnsiString errorMsg;
        	if (Comm_Request(currentCommIndex, CMD_FLASH_FORMAT))
			{
				ShowMessage(DOWNLOADFORM_MSG_08);
			}
		}
    }
    else
    {
		if (IDOK == Application->MessageBox("All Board Format?", "TVM_Application", MB_OKCANCEL))
		{
    		for(int BoardIndex = 0; BoardIndex < MachineSetupData.IPB_BoardCount + 1; BoardIndex++)
        	{
           		if(Comm_IsConnected(COMM_HCB + BoardIndex))
            	{
	        		Comm_Request(COMM_HCB + BoardIndex, CMD_FLASH_FORMAT);
            	}
			}
        
        	ShowMessage("All Board " + DOWNLOADFORM_MSG_08);
		}	
    }
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::HCBDownloadButtonClick(TObject *Sender)
{
	AnsiString fileName = HCBFilenameEdit->Text;
	AnsiString errorMsg;

	BtnEnableSet(SET);
	if (!FileExists(fileName))
	{
		ShowMessageW(DOWNLOADFORM_MSG_21);
	}
	else
	{
		TFileStream *fileStream = new TFileStream(fileName, fmOpenRead);
		unsigned int programSize = (fileStream->Size + 3) / 4 * 4;
		byte *programData = new byte[programSize];
		memset(programData, 0, programSize);
		fileStream->Read(programData, fileStream->Size);
		unsigned int data[2];
		unsigned int brData[2];
		unsigned int programID;
		int time = Now().FileDate();
		programID = PID_HCB_APPLICATION_TABLET_5;

		memcpy(&data[0], &programID, sizeof(unsigned int));
		memcpy(&data[1], &time, sizeof(int));
		
		TBootRecord br;
		br.BREnabled = 1;
		br.ProgramID = PID_HCB_APPLICATION_TABLET_5;
		programID = PID_BOOT_RECORD;
		memcpy(&brData[1], &time, sizeof(int));
		memcpy(&brData[0], &programID, sizeof(unsigned int));
		
		if (Comm_IsConnected(COMM_HCB))
		{
			if (Comm_RequestEx(COMM_HCB, CMD_DOWNLOAD, data, 2 * sizeof(unsigned int),
				programData, programSize))
			{

				if(Comm_RequestEx(COMM_HCB, CMD_DOWNLOAD, brData, 2 * sizeof(unsigned int), &br, sizeof(TBootRecord)))
				{
					Application->ProcessMessages();
					Sleep(5000);

					TIniFile *recentIniFile = new TIniFile(ProgramPath.Env + "\\download.ini");
					if (recentIniFile)
					{
						recentIniFile->WriteString("HCB", "File Name", fileName);
						delete recentIniFile;
					}
					ShowMessage(DOWNLOADFORM_MSG_07);
				}
			}
		}
		else
		{
			ShowMessageW(DOWNLOADFORM_MSG_06);
		}

		delete[] programData;
		delete fileStream;
	}
	BtnEnableSet(RESTORE);
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::ChangeHCBFileNameButtonClick(
	TObject *Sender)
{
	if (OpenDialog1->Execute())
	{
		HCBFilenameEdit->Text = OpenDialog1->FileName;
	}
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::Button1Click(TObject *Sender)
{
	if (OpenDialog1->Execute())
	{
		SPBFilenameEdit->Text = OpenDialog1->FileName;
	}
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::CPBProgramChangeButtonClick(TObject *Sender)
{
	if (OpenDialog1->Execute())
	{
		CPBFilenameEdit->Text = OpenDialog1->FileName;
	}
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::SPBDownloadButtonClick(TObject *Sender)
{
	AnsiString fileName = SPBFilenameEdit->Text;
	AnsiString errorMsg;

	BtnEnableSet(SET);
	if (!FileExists(fileName))
	{
		ShowMessageW(DOWNLOADFORM_MSG_21);
	}
	else
	{
		TFileStream *fileStream = new TFileStream(fileName, fmOpenRead);
		unsigned int programSize = (fileStream->Size + 3) / 4 * 4;
		byte *programData = new byte[programSize];
		memset(programData, 0, programSize);
		fileStream->Read(programData, fileStream->Size);
		unsigned int data[2];
		unsigned int brData[2];
		unsigned int programID;
		int time = Now().FileDate();
		programID = PID_SPB_TABLET_5;

		memcpy(&data[1], &time, sizeof(int));
		memcpy(&data[0], &programID, sizeof(unsigned int));

		TBootRecord br;
		br.BREnabled = 1;
		br.ProgramID = PID_SPB_TABLET_5;
		programID = PID_BOOT_RECORD;
		memcpy(&brData[1], &time, sizeof(int));
		memcpy(&brData[0], &programID, sizeof(unsigned int));

		int downloadCount = 0;
		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
      if(bEnabledSPB[spbIndex])
      {
        TTntSpeedButton *spbSpeedButton = (TTntSpeedButton *)FindComponent("SPBSpeedButton" + IntToStr(spbIndex + 1));
        if (Comm_IsConnected(COMM_SPB + spbIndex) && (AllSpeedButton->Down || spbSpeedButton->Down))
        {
          Comm_SetMaxWaitingTime(COMM_SPB + spbIndex, 50000);

          if (Comm_RequestEx(COMM_SPB + spbIndex, CMD_DOWNLOAD, data, 2 * sizeof(unsigned int),
            programData, programSize))
          {
            Sleep(1000);
            // write br
            if (Comm_RequestEx(COMM_SPB + spbIndex, CMD_DOWNLOAD, brData, 2 * sizeof(unsigned int),
              &br, sizeof(TBootRecord)))
            {
              Sleep(1000);
              downloadCount++;
            }
          }

          Comm_SetDefaultMaxWaitingTime(COMM_SPB + spbIndex);
        }
      }
		}
		if (downloadCount > 0)
		{
			WCHAR TempString[100];
			wsprintfW(TempString, DOWNLOADFORM_MSG_01, downloadCount);
			ShowMessage(TempString);
		}
		else
		{
			ShowMessageW(DOWNLOADFORM_MSG_06);
		}

		TIniFile *recentIniFile = new TIniFile(ProgramPath.Env + "\\download.ini");
		if (recentIniFile)
		{
			recentIniFile->WriteString("SPB", "Tablet File Name", fileName);
			delete recentIniFile;
		}

		delete[] programData;
		delete fileStream;
	}
	BtnEnableSet(RESTORE);
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::CPBDownloadButtonClick(TObject *Sender)
{
	AnsiString fileName = CPBFilenameEdit->Text;
	AnsiString errorMsg;

	BtnEnableSet(SET);
	if (!FileExists(fileName))
	{
		ShowMessageW(DOWNLOADFORM_MSG_21);
    BtnEnableSet(RESTORE);
	}
	else
	{
    CPBDownloadCheckTimer->Enabled = true;
    Panel6->Visible = true;
    WaitngBar->Position = 0;
    
		TFileStream *fileStream = new TFileStream(fileName, fmOpenRead);

		cpbProgramSize = (fileStream->Size + 3) / 4 * 4;
		cpbProgramData = new byte[cpbProgramSize];
		memset(cpbProgramData, 0, cpbProgramSize);
		fileStream->Read(cpbProgramData, fileStream->Size);
		cpbDownloadTime = Now().FileDate();
		cpbProgramID = PID_CPB_TABLET_5;

		memcpy(&cpbData[0], &cpbProgramID, sizeof(unsigned int));
		memcpy(&cpbData[1], &cpbDownloadTime, sizeof(int));
    cpbDownLoadCount = 0;
    cpbDownLoadFinish = false;

    delete fileStream;
    
    CPBDownloadThreadHandle = (HANDLE)_beginthreadex(NULL, NULL, CPBProgramThread, this, 0, (unsigned int*)&ThreadDword);
  }
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::RunButtonClick(TObject *Sender)
{
	BtnEnableSet(SET);
	AnsiString errorMsg;
	struct
	{
		unsigned int runMode;
		int programID;
	} runData;

	if (IsCPBRunning)
	{
		ShowMessageFA(DOWNLOADFORM_MSG_12);
		return;
	}

	runData.runMode = RUN_MODE_RERUN;
	//    runData.programID = PID_CPB | ((programIndex / 10 + '0') << 8) | (programIndex % 10 + '0');
	runData.programID = PID_CPB_TABLET_5;

	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
    if(bEnabledSPB[spbIndex])
    {
      RunCheck[spbIndex] = true;
      RunCommandCheckData[spbIndex] = spbIndex;
      TTntSpeedButton *spbSpeedButton = (TTntSpeedButton *)FindComponent("SPBSpeedButton" + IntToStr(spbIndex + 1));
      if (Comm_IsConnected(COMM_SPB + spbIndex) && (AllSpeedButton->Down || spbSpeedButton->Down))
      {
        Comm_SetMaxWaitingTime(COMM_SPB + spbIndex, 30000);

        if (Comm_Request(COMM_SPB + spbIndex, CMD_RUN, &runData, sizeof(runData)))
        {
          SPBSystemSetupData[spbIndex].DefaultCPBProgramID = runData.programID;
        }
        Comm_SetDefaultMaxWaitingTime(COMM_SPB + spbIndex);
      }
    }
	}

	WriteSPBSystemSetupData(ProgramPath.Env + "\\SystemInfor.ini", SPBSystemSetupData);
	SendSystemSetupData();
	CPBSetupInfo.StudySetupDataValid = false;
	CPBSetupInfo.InspectionSetupDataValid = false;
	CPBSetupInfo.GradeDataValid = false;
	CheckCPBBootStatus(true,false);
	BtnEnableSet(RESTORE);
	//    ShowMessageW("OK");
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::ExitButtonClick(TObject *Sender)
{
	Close();
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::RunComplete(bool result, TOverlapIOStr *OverlapIOStr)
{
	int spbIndex = *(int *)OverlapIOStr;
	RunCheck[spbIndex] = false;

	bool runComplete = true;
	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
		if (RunCheck[spbIndex] == true)
		{
			runComplete = false;
			break;
		}
	}

	if (runComplete)
	{
		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
			Comm_SetDefaultMaxWaitingTime(COMM_SPB + spbIndex);
		}
		ShowMessageFA("OK");
	}
}
//---------------------------------------------------------------------------


void __fastcall TDownloadForm::HCBSystemSetupButtonClick(TObject *Sender)
{
	BtnEnableSet(SET);
	try
	{
    MachineSetupData.CompanyID = RadioGroup1->ItemIndex;
    WriteMachineSetupData(ProgramPath.Env + "\\SystemInfor.ini", MachineSetupData);
    
		TPortMapInfo PortMapInfo;
		TUserMachineEnv UserMachineEnv;
		if (!ReadUserMachineEnvData(ProgramPath.Env + "\\UserMachineInfor.ini", UserMachineEnv))
		{
			throw Exception("Can Not Open Usermachineinfor.Ini");
		}

		if (!MakePortMapInfo(PortMapInfo, TARGET_MACHINE_REV))
		{
			throw Exception("Can Not Load Port Map.");
		}

		unsigned int data[2];
		unsigned int programID;
		int time;
		/*
		time = Now().FileDate();
		programID = PID_ENVIRONMENT;

		memcpy(&data[0], &programID, sizeof(unsigned int));
		memcpy(&data[1], &time, sizeof(int));

		if (Comm_IsConnected(COMM_HCB))
		{
		if (!Comm_RequestEx(COMM_HCB, CMD_DOWNLOAD, data, 2 * sizeof(unsigned int),
		&HCBSystemSetupInfo, sizeof(HCBSystemSetupInfo)))
		{
		throw Exception("Setup fails");
		}
		}
		else
		{
		throw Exception("HCB is not connected");
		}
		*/
		time = Now().FileDate();
		programID = PID_MACHINE_INFO;

		memcpy(&data[0], &programID, sizeof(unsigned int));
		memcpy(&data[1], &time, sizeof(int));

		if (Comm_IsConnected(COMM_HCB))
		{
			if (!Comm_RequestEx(COMM_HCB, CMD_DOWNLOAD, data, 2 * sizeof(unsigned int),
				&MachineSetupData, sizeof(TMachineSetupData)))
			{
				throw Exception("Setup Fail");
			}

			Sleep(1000);
		}
		else
		{
			throw Exception("HCB Is Not Connected");
		}

		time = Now().FileDate();
		programID = PID_USER_MACHINE_ENV;

		memcpy(&data[0], &programID, sizeof(unsigned int));
		memcpy(&data[1], &time, sizeof(int));

		if (Comm_IsConnected(COMM_HCB))
		{
			if (!Comm_RequestEx(COMM_HCB, CMD_DOWNLOAD, data, 2 * sizeof(unsigned int),
				&UserMachineEnv, sizeof(UserMachineEnv)))
			{
				throw Exception("Setup Fail");
			}

			Sleep(1000);
		}
		else
		{
			throw Exception("HCB Is Not Connected");
		}

		time = Now().FileDate();
		programID = PID_PORT_MAP;

		memcpy(&data[0], &programID, sizeof(unsigned int));
		memcpy(&data[1], &time, sizeof(int));

		if (Comm_IsConnected(COMM_HCB))
		{
			if (!Comm_RequestEx(COMM_HCB, CMD_DOWNLOAD, data, 2 * sizeof(unsigned int),
				&PortMapInfo, sizeof(PortMapInfo)))
			{
				throw Exception("Setup Fail");
			}

			Sleep(1000);
		}
		else
		{
			throw Exception("HCB Is Not Connected");
		}

		time = Now().FileDate();
		programID = PID_HCB_DB_HEADER;

		THCBDBHeader hcbDBHeader;

		hcbDBHeader.DataRev = TARGET_HCB_DATA_REV;

		memcpy(&data[0], &programID, sizeof(unsigned int));
		memcpy(&data[1], &time, sizeof(int));

		if (Comm_IsConnected(COMM_HCB))
		{
			if (!Comm_RequestEx(COMM_HCB, CMD_DOWNLOAD, data, 2 * sizeof(unsigned int),
				&hcbDBHeader, sizeof(THCBDBHeader)))
			{
				throw Exception("Setup Fail");
			}

			Sleep(1000);
		}
		else
		{
			throw Exception("HCB Is Not Connected");
		}

		ShowMessageFA("Complete Setup");
	}
	catch (Exception &ec)
	{
		ShowMessageFA(ec.Message);
	}
	BtnEnableSet(RESTORE);
}
//---------------------------------------------------------------------------
bool __fastcall TDownloadForm::MakePortMapInfo(TPortMapInfo &PortMapInfo, unsigned int machineRev)
{
	TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\MachineInfor.ini");
	TPortMapInfoData OutputPortMapData[MAX_PORT_COUNT];
	TPortMapInfoData InputPortMapData[MAX_PORT_COUNT];

  memset(&OutputPortMapData,0,sizeof(TPortMapInfoData));
  memset(&InputPortMapData,0,sizeof(TPortMapInfoData));

	if (iniFile)
	{
		for (int outputPortIndex = 0; outputPortIndex < MAX_PORT_COUNT; outputPortIndex++)
		{
			OutputPortMapData[outputPortIndex].PortMapValue = iniFile->ReadInteger("Port Mapping", "Output " + IntToStr(outputPortIndex) + " RP", PORT_NOT_EXIST);
		}

		for (int inputPortIndex = 0; inputPortIndex < MAX_PORT_COUNT; inputPortIndex++)
		{
			InputPortMapData[inputPortIndex].PortMapValue = iniFile->ReadInteger("Port Mapping", "Input " + IntToStr(inputPortIndex) + " RP", PORT_NOT_EXIST);
		}
		delete iniFile;


		for (int portIndex = 0; portIndex < MAX_PORT_COUNT; portIndex++)
		{
			if (InputPortMapData[portIndex].PortMapValue > MAX_PORT_COUNT)
			{
				PortMapInfo.VIPMap[portIndex] = PIP_NOT_EXIST;
			}
			else
			{
				PortMapInfo.VIPMap[portIndex] = InputPortMapData[portIndex].PortMapValue;
			}
		}

		for (int portIndex = 0; portIndex < MAX_PORT_COUNT; portIndex++)
		{
			if (OutputPortMapData[portIndex].PortMapValue > MAX_PORT_COUNT)
			{
				PortMapInfo.VOPMap[portIndex] = POP_NOT_EXIST;
			}
			else
			{
				PortMapInfo.VOPMap[portIndex] = OutputPortMapData[portIndex].PortMapValue;
			}
		}

		PortMapInfo.MachineRev = machineRev;
		return true;
	}
	else
	{
		return false;
	}
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::SPBSystemSetupButtonClick(TObject *Sender)
{
	BtnEnableSet(SET);

	unsigned int data[2];
	unsigned int programID;
	int time;

	int setupCount = 0;
	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
		SPBSystemSetupData[spbIndex].DefaultCPBProgramID = PID_CPB_TABLET_5;

		if (bEnabledSPB[spbIndex])
		{
			TTntSpeedButton *spbSpeedButton = (TTntSpeedButton *)FindComponent("SPBSpeedButton" + IntToStr(spbIndex + 1));
			if (!Comm_IsConnected(COMM_SPB + spbIndex) || (!AllSpeedButton->Down && !spbSpeedButton->Down))
			{
				continue;
			}

			time = Now().FileDate();
			programID = PID_ENVIRONMENT;

			memcpy(&data[0], &programID, sizeof(unsigned int));
			memcpy(&data[1], &time, sizeof(int));

			if (Comm_IsConnected(COMM_SPB + spbIndex))
			{
				Comm_SetMaxWaitingTime(COMM_SPB + spbIndex, 30000);
				if (!Comm_RequestEx(COMM_SPB + spbIndex, CMD_DOWNLOAD, data, 2 * sizeof(unsigned int), &SPBSystemSetupData[spbIndex], sizeof(TSPBSystemSetupData)))
				{
					throw Exception("Setup Fail");
				}
				Comm_SetDefaultMaxWaitingTime(COMM_SPB + spbIndex);
			}

			time = Now().FileDate();
			programID = PID_SPB_DB_HEADER;

			TSPBDBHeader spbDBHeader;
			memset(&spbDBHeader, 0, sizeof(TSPBDBHeader));
			spbDBHeader.DataRev = TARGET_SPB_DATA_REV;

			memcpy(&data[0], &programID, sizeof(unsigned int));
			memcpy(&data[1], &time, sizeof(int));

			if (Comm_IsConnected(COMM_SPB + spbIndex))
			{
				Comm_SetMaxWaitingTime(COMM_SPB + spbIndex, 30000);

				if (!Comm_RequestEx(COMM_SPB + spbIndex, CMD_DOWNLOAD, data, 2 * sizeof(unsigned int),
				                    &spbDBHeader, sizeof(TSPBDBHeader)))
				{
					throw Exception("Setup Fail");
				}

				Comm_SetDefaultMaxWaitingTime(COMM_SPB + spbIndex);
			}
			else
			{
				throw Exception("SPB Is Not Connected");
			}

			setupCount++;
		}
	}
	WCHAR TempString[100];
	wsprintfW(TempString, DOWNLOADFORM_MSG_03, setupCount);
	ShowMessageFA(TempString);
	BtnEnableSet(RESTORE);
}


//---------------------------------------------------------------------------

void __fastcall TDownloadForm::EditClick(TObject *Sender)
{
	TTntEdit *theEdit = (TTntEdit *)Sender;
	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeyboard() == mrOk)
	{
		theEdit->Text = KeyboardForm->Text;
	}
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::ReadMachineNameButtonClick(TObject *Sender)
{
	THCBMachineSpecificHeader hcbMachineSpecificHeader;
	Comm_Request(COMM_HCB, CMD_READ_MS_HEADER, NULL, 0, &hcbMachineSpecificHeader, sizeof(THCBMachineSpecificHeader));
	MachineNameEdit->Text = AnsiString(hcbMachineSpecificHeader.MachineName);
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::WriteMachineNameButtonClick(TObject *Sender)
{
	if (MessageDlgFA(DOWNLOADFORM_MSG_19, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
	{
		THCBMachineSpecificHeader hcbMachineSpecificHeader;
		//Comm_Request(COMM_HCB, CMD_SYSTEM_HEADER, NULL, 0, &hcbSystemHeader, sizeof(THCBSystemHeader));

		strncpy(hcbMachineSpecificHeader.MachineName, MachineNameEdit->Text.c_str(), 16 - 1);		// string length overflow 방지
		hcbMachineSpecificHeader.MachineName[16 - 1] = '\0';
		Comm_Request(COMM_HCB, CMD_WRITE_MS_HEADER, &hcbMachineSpecificHeader, sizeof(THCBMachineSpecificHeader));

		PCSystemHeader.TargetMachineName = MachineNameEdit->Text;
		AnsiString fileName = ProgramPath.Env + "\\SystemInfor.ini";
		WritePCSystemHeader(fileName);
	}
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::HCBResetButtonClick(TObject *Sender)
{
	if (MessageDlgFA(DOWNLOADFORM_MSG_10, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
	{
		WaitngBar->Position = 0;
		Panel6->Visible = true;

		bSystemStatusCheckSW = false;
		BootingProcessStep = HCB_BOOT_PROCESS_STANDBY;
		BootingProcessTimeCount = 0;

		BootingTarget = BOARD_TYPE_HCB;

		BootingCheckTimer->Enabled = true;
	}
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::SPBResetButtonClick(TObject *Sender)
{
	globalResetSPBCount = 0;
	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
    if(bEnabledSPB[spbIndex])
    {
      TTntSpeedButton *spbSpeedButton = (TTntSpeedButton *)FindComponent("SPBSpeedButton" + IntToStr(spbIndex + 1));
      if (Comm_IsConnected(COMM_SPB + spbIndex) && (AllSpeedButton->Down || spbSpeedButton->Down))
      {
        globalResetSPBCount++;
      }
    }
	}

	if (globalResetSPBCount == 0)
	{
		ShowMessageW(DOWNLOADFORM_MSG_06);
		return;
	}

	if (MessageDlgFA(DOWNLOADFORM_MSG_14, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
	{
		checkedSPB[0] = 0;
		checkedSPB[1] = 0;
		checkedSPB[2] = 0;
		checkedSPB[3] = 0;

		WaitngBar->Position = 0;
		Panel6->Visible = true;

		bSystemStatusCheckSW = false;
		BootingProcessStep = SPB_BOOT_PROCESS_STANDBY;
		BootingProcessTimeCount = 0;

		BootingTarget = BOARD_TYPE_SPB;

		BootingCheckTimer->Enabled = true;
	}
}
//---------------------------------------------------------------------------
void __fastcall TDownloadForm::BtnEnableSet(int State)
{
	if (State == SET)
	{
		HCBDownloadButton->Enabled = false;
		SPBDownloadButton->Enabled = false;
		CPBDownloadButton->Enabled = false;

		HCBSystemSetupButton->Enabled = false;
		SPBSystemSetupButton->Enabled = false;

		HCBResetButton->Enabled = false;
		SPBResetButton->Enabled = false;
		RunButton->Enabled = false;

		ChangeHCBFileNameButton->Enabled = false;
		Button1->Enabled = false;
		CPBProgramChangeButton1->Enabled = false;

		ReadMachineNameButton->Enabled = false;
		WriteMachineNameButton->Enabled = false;

		btnReadFlashInfo->Enabled = false;
		btnFlashFormat->Enabled = false;

		AllSpeedButton->Enabled = false;
		HCBSpeedButton->Enabled = false;
		SPBSpeedButton1->Enabled = false;
		SPBSpeedButton2->Enabled = false;
		SPBSpeedButton3->Enabled = false;
		SPBSpeedButton4->Enabled = false;
    SPBSpeedButton5->Enabled = false;
    SPBSpeedButton6->Enabled = false;

    ExitButton->Enabled = false;
	}
	else
	{
		HCBDownloadButton->Enabled = true;
		SPBDownloadButton->Enabled = true;
		CPBDownloadButton->Enabled = true;

		HCBSystemSetupButton->Enabled = true;
		SPBSystemSetupButton->Enabled = true;

		HCBResetButton->Enabled = true;
		SPBResetButton->Enabled = true;
		RunButton->Enabled = true;

		ChangeHCBFileNameButton->Enabled = true;
		Button1->Enabled = true;
		CPBProgramChangeButton1->Enabled = true;

		ReadMachineNameButton->Enabled = true;
		WriteMachineNameButton->Enabled = true;

		btnReadFlashInfo->Enabled = true;
		btnFlashFormat->Enabled = true;

		AllSpeedButton->Enabled = true;
		HCBSpeedButton->Enabled = true;
		SPBSpeedButton1->Enabled = true;
		SPBSpeedButton2->Enabled = true;
		SPBSpeedButton3->Enabled = true;
		SPBSpeedButton4->Enabled = true;
    SPBSpeedButton5->Enabled = true;
    SPBSpeedButton6->Enabled = true;

    ExitButton->Enabled = true;
	}
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::BootingCheckTimerTimer(TObject *Sender)
{
	bBootingCheckTimerEnabled = BootingCheckTimer->Enabled;
	BootingCheckTimer->Enabled = false;

	if (BootingTarget == BOARD_TYPE_HCB)
		HCBBootingProcess();
	else if (BootingTarget == BOARD_TYPE_SPB)
		SPBBootingProcess();

	BootingProcessTimeCount++;

	WaitngBar->Position++;
	if (WaitngBar->Position == WaitngBar->Max)
	{
		WaitngBar->Position = WaitngBar->Min;
	}

	BootingCheckTimer->Enabled = bBootingCheckTimerEnabled;
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::SPBBootingProcess()
{
	int resetCount;
	switch (BootingProcessStep)
	{
	case SPB_BOOT_PROCESS_STANDBY:

		BtnEnableSet(SET);
		Application->ProcessMessages();
		Machine.DisableBlackOut();
		BootingProcessStep = SPB_BOOT_PROCESS_SPB_RESET;
		break;

	case SPB_BOOT_PROCESS_SPB_RESET:

		SendSPBResetCommand();
		beforetimecount = BootingProcessTimeCount;
		BootingProcessStep = SPB_BOOT_PROCESS_STABLE_WAITING;
		break;

	case SPB_BOOT_PROCESS_STABLE_WAITING:

		if (BootingProcessTimeCount - beforetimecount > 500) // 5000ms
		{
			BootingProcessStep = SPB_BOOT_PROCESS_SPB_BOOTING;
		}
		break;

	case SPB_BOOT_PROCESS_SPB_BOOTING:

		if (BoardBootingCheckProcess(BOARD_TYPE_SPB))
		{
			BootingProcessStep = SPB_BOOT_PROCESS_SPB_CONNECTION;
		}
		break;

	case SPB_BOOT_PROCESS_SPB_CONNECTION:

		resetCount = 0;
		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
			TTntSpeedButton *spbSpeedButton = (TTntSpeedButton *)FindComponent("SPBSpeedButton" + IntToStr(spbIndex + 1));
			if (AllSpeedButton->Down || spbSpeedButton->Down)
			{
				if (checkedSPB[spbIndex])
				{
					Comm_Connect(COMM_SPB + spbIndex);
					resetCount++;
				}
			}
		}

		Machine.EnableBlackOut();
		WCHAR TempString[100];
		wsprintfW(TempString, DOWNLOADFORM_MSG_02, resetCount);
		ShowMessageW(TempString);

		/*if (!ProductData.ProductName.IsEmpty())
		{
			ShowMessage("[메인화면] - [제품정보입력]에서 제품을 다시 선택하여 주십시오.");
		}*/

		Panel6->Visible = false;
		bBootingCheckTimerEnabled = false;

		CPBSetupInfo.StudySetupDataValid = false;
		CPBSetupInfo.InspectionSetupDataValid = false;
		CPBSetupInfo.GradeDataValid = false;
		CheckCPBBootStatus(true);

		BtnEnableSet(RESTORE);
		bSystemStatusCheckSW = true;
		break;
	}
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::SendSPBResetCommand()
{
	int resetCount = 0;
	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
    if(bEnabledSPB[spbIndex])
    {
      TTntSpeedButton *spbSpeedButton = (TTntSpeedButton *)FindComponent("SPBSpeedButton" + IntToStr(spbIndex + 1));
      if (Comm_IsConnected(COMM_SPB + spbIndex) && (AllSpeedButton->Down || spbSpeedButton->Down))
      {
        if (Comm_Request(COMM_SPB + spbIndex, CMD_RESET))
        {
          resetCount++;
        }
        Comm_Disconnect(COMM_SPB + spbIndex);
      }
    }
	}
}
//---------------------------------------------------------------------------

bool __fastcall TDownloadForm::BoardBootingCheckProcess(int BoardType)
{
	bool returnValue;
	if (BoardType == BOARD_TYPE_SPB)
	{
		// 카메라 부팅 및 Tcp/Ip 연결상태 확인
		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
      if(bEnabledSPB[spbIndex])
      {
        TTntSpeedButton *spbSpeedButton = (TTntSpeedButton *)FindComponent("SPBSpeedButton" + IntToStr(spbIndex + 1));
        if (AllSpeedButton->Down || spbSpeedButton->Down)
        {
          if (!Comm_IsConnected(spbIndex + 1) && !checkedSPB[spbIndex])
          {
            Comm_Connect(COMM_SPB + spbIndex);
          }
        }
      }
		}

		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
      if(bEnabledSPB[spbIndex])
      {
        TTntSpeedButton *spbSpeedButton = (TTntSpeedButton *)FindComponent("SPBSpeedButton" + IntToStr(spbIndex + 1));
        if (Comm_IsConnected(COMM_SPB + spbIndex) && (AllSpeedButton->Down || spbSpeedButton->Down))
        {
          checkedSPB[spbIndex] = 1;
          Comm_Disconnect(COMM_SPB + spbIndex);
        }
      }
		}

		int spbBootCount = 0;
		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
      if(bEnabledSPB[spbIndex])
      {
        TTntSpeedButton *spbSpeedButton = (TTntSpeedButton *)FindComponent("SPBSpeedButton" + IntToStr(spbIndex + 1));
        if (checkedSPB[spbIndex] && (AllSpeedButton->Down || spbSpeedButton->Down))
        {
          spbBootCount++;
        }
      }
		}

		if (spbBootCount == globalResetSPBCount)
		{
			returnValue = true;
		}
		else
		{
			returnValue = false;
		}
	}
	else
	{
		//Tcp/Ip(USB) 연결상태 확인
		if (!Comm_IsConnected(COMM_HCB))
		{
			Comm_Connect(COMM_HCB);

			returnValue = true;
		}
		else
		{
			returnValue = false;
		}
	}

	return returnValue;
}

//---------------------------------------------------------------------------
void __fastcall TDownloadForm::HCBBootingProcess()
{
	THCBProgramHeader hcbProgramHeader;
	switch (BootingProcessStep)
	{
	case HCB_BOOT_PROCESS_STANDBY:

		BtnEnableSet(SET);
		BootingProcessStep = HCB_BOOT_PROCESS_HCB_RESET;
		break;

	case HCB_BOOT_PROCESS_HCB_RESET:

		Comm_Request(COMM_HCB, CMD_RESET);
		Comm_Disconnect(COMM_HCB);
		beforetimecount = BootingProcessTimeCount;
		BootingProcessStep = HCB_BOOT_PROCESS_STABLE_WAITING1;
		break;

	case HCB_BOOT_PROCESS_STABLE_WAITING1:

		if (BootingProcessTimeCount - beforetimecount > 1000) // 10000ms
		{
			BootingProcessStep = HCB_BOOT_PROCESS_HCB_BOOTING;
		}
		break;

	case HCB_BOOT_PROCESS_HCB_BOOTING:

		if (BoardBootingCheckProcess(BOARD_TYPE_HCB))
		{
			beforetimecount = BootingProcessTimeCount;
			BootingProcessStep = HCB_BOOT_PROCESS_STABLE_WAITING2;
		}
		break;

	case HCB_BOOT_PROCESS_STABLE_WAITING2:

		if (BootingProcessTimeCount - beforetimecount > 300) // 3000ms
		{
			BootingProcessStep = HCB_BOOT_PROCESS_FINAL;
		}
		break;

	case HCB_BOOT_PROCESS_FINAL:
		ShowMessageW(DOWNLOADFORM_MSG_20);
		if (Comm_IsConnected(COMM_HCB))
		{
			THCBProgramHeader hcbProgramHeader;
			Comm_Request(COMM_HCB, CMD_READ_PROGRAM_HEADER, NULL, 0, &hcbProgramHeader, sizeof(THCBProgramHeader));
		}
		Machine.NCHomeMove();
		BtnEnableSet(RESTORE);

		Panel6->Visible = false;
		bBootingCheckTimerEnabled = false;
		bSystemStatusCheckSW = true;
		break;
	}
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::Panel8DblClick(TObject *Sender)
{
  if(RadioGroup1->Visible == true)
    RadioGroup1->Visible = false;
  else
    RadioGroup1->Visible = true;
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::CPBDownloadCheckTimerTimer(TObject *Sender)
{
  bool timerEnabled = CPBDownloadCheckTimer->Enabled;
  CPBDownloadCheckTimer->Enabled = false;

  //Application->ProcessMessages();

  if(cpbDownLoadFinish == true)
  {
    timerEnabled = false;
    
    if (cpbDownLoadCount > 0)
		{
			WCHAR TempString[100];
			wsprintfW(TempString, DOWNLOADFORM_MSG_01, cpbDownLoadCount);
			ShowMessage(TempString);
		}
		else
		{
			ShowMessageW(DOWNLOADFORM_MSG_06);
		}
    AnsiString fileName = AnsiString(CPBFilenameEdit->Text);
    
		TIniFile *recentIniFile = new TIniFile(ProgramPath.Env + "\\download.ini");
		if (recentIniFile)
		{
			recentIniFile->WriteString("CPB", "Tablet File Name", fileName);
			delete recentIniFile;
		}

		delete[] cpbProgramData;
    delete[] cpbData;
    
		WriteSPBSystemSetupData(ProgramPath.Env + "\\SystemInfor.ini", SPBSystemSetupData);
		SendSystemSetupData();

	  BtnEnableSet(RESTORE);

    Panel6->Visible = false;
  }
  else
  {
    WaitngBar->Position++;
    if (WaitngBar->Position == WaitngBar->Max)
    {
      WaitngBar->Position = WaitngBar->Min;
    }
  }

  CPBDownloadCheckTimer->Enabled = timerEnabled;
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::TPBSpeedButtonClick(TObject *Sender)
{
  currentCommIndex = COMM_TPB;
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::TPBDownloadButtonClick(TObject *Sender)
{
 //
   AnsiString fileName = TPBFilenameEdit->Text;
  AnsiString errorMsg;

  BtnEnableSet(SET);

  if(!FileExists(fileName))
  {
    ShowMessageW(DOWNLOADFORM_MSG_21);
  }
  else
  {
    TFileStream *fileStream = new TFileStream(fileName, fmOpenRead);
    unsigned int programSize = (fileStream->Size + 3) / 4 * 4;
    byte *programData = new byte[programSize];
    memset(programData, 0, programSize);
    fileStream->Read(programData, fileStream->Size);
    unsigned int data[2];
    unsigned int brData[2];
    unsigned int programID;
    int time = Now().FileDate();
    programID = PID_TPB_TABLET;

    memcpy(&data[1], &time, sizeof(int));
    memcpy(&data[0], &programID, sizeof(unsigned int));

    TBootRecord br;
    br.BREnabled = 1;
    br.ProgramID = PID_TPB_TABLET;
    programID = PID_BOOT_RECORD;
    memcpy(&brData[1], &time, sizeof(int));
		memcpy(&brData[0], &programID, sizeof(unsigned int));

    int downloadCount = 0;
    if(Comm_IsConnected(COMM_TPB) && (AllSpeedButton->Down || TPBSpeedButton->Down))
    {
      Comm_SetMaxWaitingTime(COMM_TPB, 30000);

      if (Comm_RequestEx(COMM_TPB, CMD_DOWNLOAD, data, 2 * sizeof(unsigned int),
        programData, programSize))
      {
        Sleep(1000);
        // write br
        if (Comm_RequestEx(COMM_TPB, CMD_DOWNLOAD, brData, 2 * sizeof(unsigned int),
          &br, sizeof(TBootRecord)))
        {
          Sleep(1000);
          downloadCount++;
        }
      }

      Comm_SetDefaultMaxWaitingTime(COMM_TPB);
    }

    if(downloadCount > 0)
    {
      WCHAR TempString[100];
			wsprintfW(TempString, DOWNLOADFORM_MSG_01, downloadCount);
			ShowMessage(TempString);
    }
    else
    {
      ShowMessageW(DOWNLOADFORM_MSG_06);
    }

    TIniFile *recentIniFile = new TIniFile(ProgramPath.Env + "\\download.ini");
		if (recentIniFile)
		{
			recentIniFile->WriteString("TPB", "Tablet File Name", fileName);
			delete recentIniFile;
		}

		delete[] programData;
		delete fileStream;

  }
  BtnEnableSet(RESTORE);
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::TPBProgramChangeButtonClick(TObject *Sender)
{
  //
  if (OpenDialog1->Execute())
	{
		TPBFilenameEdit->Text = OpenDialog1->FileName;
	}
}
//---------------------------------------------------------------------------

void __fastcall TDownloadForm::CheckTPB_BoardExist(void)
{
	ReadTPB_BoardExistInfo();

  if(TPBSystemInfo.boardExist == TPB_BOARD_EXSIT)
  {
    TPBSpeedButton->Visible = true;
    TPBFilenameEdit->Visible = true;
    TPBProgramChangeButton->Visible = true;
    TPBDownloadButton->Visible = true;
  }
  else
  {
    TPBSpeedButton->Visible = false;
    TPBFilenameEdit->Visible = false;
    TPBProgramChangeButton->Visible = false;
    TPBDownloadButton->Visible = false;
  }  
}
//---------------------------------------------------------------------------


