 //---------------------------------------------------------------------------
// For SELMA200, 20180221, moon, 완료
// 카메라 인덱스, 개수 변경 관련하여 Form Design 변경
// [Camera Setting], [3D Camera Setting] 버튼에 해당하는 기능은 수정 작업 진행하지 않음
// 위 기능은 NFA 카메라 및 이에 대한 메뉴얼 확보 후에 진행해야할 것으로 보여짐
// 추후 NFA 카메라 스펙에 따라 관련 폼 수정사항이 발생
//---------------------------------------------------------------------------

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

#include "Capture_Form.h"
#include "Environment.h"
#include "SystemSetup.h"
#include "Message_Form.h"
#include "VisionSetting_Form.h"
#include "ColorCode_Form.h"
#include "CameraMapping_Form.h"
#include "NFA2DCameraSetting_Form.h"
#include "Keyboard_Form.h"
#include "CameraSetting3D_Form.h"
#include "AdvMachineControl_Form.h"
#include "MultiLanguage.h"
#include "Environment.h"
#include "RealSizeImage_Form.h"
#include "ThreeDLineScanFrequencyStudy_Form.h"
#include "ThreeDSensorStatusCheck_Form.h"
#include "TwoDCalibrationGuide_Form.h"
#include "OffSetImageExtract_Form.h"
#include "TPBCameraSetting_Form.h"


//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "Capture_Frame"
#pragma link "TntButtons"
#pragma link "TntExtCtrls"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"
TCaptureForm *CaptureForm;
//---------------------------------------------------------------------------
__fastcall TCaptureForm::TCaptureForm(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();
  
	bOnCapture = false;
  ImageLoadRadioBtn->ItemIndex = 0 ;
  if(ProductData.SubSamplingMode == 0)
  {
    //ResolutionRadioGroup->ItemIndex = 0;
    CAM_Width = SYSTEM_CAMERA_WIDTH;
    CAM_Height = SYSTEM_CAMERA_HEIGHT;
    for(int i = 0; i < SYSTEM_TOTAL_CAMERA_COUNT; ++i)
    {
      SubsamplingModeList[i] = RESOLUTION_NORMAL_QUALITY;
    }
  }
  else
  {
    //ResolutionRadioGroup->ItemIndex = 1;
    CAM_Width = SYSTEM_CAMERA_HD_WIDTH;
    CAM_Height = SYSTEM_CAMERA_HD_HEIGHT;
    for(int i = 0; i < SYSTEM_TOTAL_CAMERA_COUNT ; ++i)
    {
      if(CameraMapInfo[i].CameraInspectPosition == CAMERA_POSITION_3D)
        SubsamplingModeList[i] = RESOLUTION_NORMAL_QUALITY;
      else
        SubsamplingModeList[i] = RESOLUTION_HIGH_QUALITY;
    }
  }

  CaptureImage->Width = SYSTEM_CAMERA_WIDTH;
  CaptureImage->Height = SYSTEM_CAMERA_HEIGHT;
  CaptureImage->Picture->Bitmap->Width =  CAM_Width;
  CaptureImage->Picture->Bitmap->Height = CAM_Height;
  CaptureImage->Picture->Bitmap->PixelFormat = pf24bit;

	SubCaptureFrame->SetCaptureProperty(CAM_Width, CAM_Height, CaptureImage, pf24bit);

	EnlargeImage->Picture->Bitmap->Width = 50;
  EnlargeImage->Picture->Bitmap->Height = 50;
  EnlargeImage->Picture->Bitmap->PixelFormat = pf24bit;
  ImagePanel->DoubleBuffered = true;
  GroupBox9->DoubleBuffered = true;
  GroupBox10->DoubleBuffered = true;
  GroupBox11->DoubleBuffered = true;


	MousePos.x = CAM_Width / 2;
	MousePos.y = CAM_Height / 2;
	ImageInfoPanel->DoubleBuffered = true;

	if(!ProductData.ProductName.IsEmpty())
	{
		if(ProductData.FatTabletCapture)
		{
			LEDOnMask[0] =  (0x0001 << 0) | (0x0001 << 1) ;
			LEDOnMask[1] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
			LEDOnMask[2] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
			LEDOnMask[3] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
		  	LEDOnMask[4] =  0;
		  	LEDOnMask[5] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
			LEDOnMask[6] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
			LEDOnMask[7] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);

		  	LEDOnMask[8] =  (0x0001 << 6) | (0x0001 << 7) ;
		  	LEDOnMask[9] =  (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
			LEDOnMask[10] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
			LEDOnMask[11] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
			LEDOnMask[12] = 0;
			LEDOnMask[13] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
			LEDOnMask[14] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
			LEDOnMask[15] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);		
		}
		else
		{
			LEDOnMask[0] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
			LEDOnMask[1] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
			LEDOnMask[2] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
			LEDOnMask[3] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
		  	LEDOnMask[4] =  0;
		  	LEDOnMask[5] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
			LEDOnMask[6] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
			LEDOnMask[7] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);

		  	LEDOnMask[8] =  (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
		  	LEDOnMask[9] =  (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
			LEDOnMask[10] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
			LEDOnMask[11] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
			LEDOnMask[12] = 0;
			LEDOnMask[13] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
			LEDOnMask[14] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
			LEDOnMask[15] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);		
		}

	
	}
	else
	{
		LEDOnMask[0] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
		LEDOnMask[1] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
		LEDOnMask[2] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
		LEDOnMask[3] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
	  	LEDOnMask[4] =  0;
	  	LEDOnMask[5] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
		LEDOnMask[6] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);
		LEDOnMask[7] =  (0x0001 << 0) | (0x0001 << 1) | (0x0001 << 2) | (0x0001 << 3) | (0x0001 << 4);

	  	LEDOnMask[8] =  (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
	  	LEDOnMask[9] =  (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
		LEDOnMask[10] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
		LEDOnMask[11] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
		LEDOnMask[12] = 0;
		LEDOnMask[13] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
		LEDOnMask[14] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
		LEDOnMask[15] = (0x0001 << 6) | (0x0001 << 7) | (0x0001 << 8) | (0x0001 << 9) | (0x0001 << 10);
	}

  GlobalCameraIndex = 0;
  ChangeCamera();

  SystemAnalogGainEdit->Text = IntToStr(SYSTEM_DEFAULT_ANLOG_GAIN);
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::GetDefaultString()
{
  SPBCaptureEndButton->Caption = CAPTUREFORM_BUTTON_CAPTION_01;
  AdvMachineControlButton->Caption = CAPTUREFORM_BUTTON_CAPTION_02;
  SaveDefaultShutterSpeedButton->Caption = CAPTUREFORM_BUTTON_CAPTION_03;
  LoadDefaultButton->Caption = CAPTUREFORM_BUTTON_CAPTION_04;
  LoadSystemDefaultButton->Caption = CAPTUREFORM_BUTTON_CAPTION_05;
  SaveColorShutterSpeedButton->Caption = CAPTUREFORM_BUTTON_CAPTION_07;
  SaveProductShutterSpeedButton->Caption = CAPTUREFORM_BUTTON_CAPTION_08;
  
  GroupBox8->Caption = CAPTUREFORM_GROUPBOX_CAPTION_02;
  GroupBox6->Caption = CAPTUREFORM_GROUPBOX_CAPTION_03;
  GroupBox2->Caption = CAPTUREFORM_GROUPBOX_CAPTION_04;
  GroupBox4->Caption = CAPTUREFORM_GROUPBOX_CAPTION_05;
  ImageLoadRadioBtn->Caption = CAPTUREFORM_GROUPBOX_CAPTION_06;
  ImageLoadRadioBtn->Items->Strings[0] =CAPTUREFORM_GROUPBOX_CAPTION_07;
  ImageLoadRadioBtn->Items->Strings[1] =CAPTUREFORM_GROUPBOX_CAPTION_08;
  ResolutionRadioGroup->Caption = CAPTUREFORM_GROUPBOX_CAPTION_09;
  ResolutionRadioGroup->Items->Strings[0] = CAPTUREFORM_GROUPBOX_CAPTION_10;
  ResolutionRadioGroup->Items->Strings[1] = CAPTUREFORM_GROUPBOX_CAPTION_11;
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::ChangeCamera(void)
{
	SubCaptureFrame->SetGlobalCameraIndex(GlobalCameraIndex);
  RefreshLEDCheckBox();
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::FormCreate(TObject *Sender)
{
  bLockRefreshOffsetInfo = false;

  Machine.MachineStop();

	LoadSystemInfor();
  CameraSpeedButton1->OnClick; 
  TabletLengthEdit->Text = FloatToStr(ProductData.TabletLength);

  AnsiString fileName;
  fileName = ProgramPath.Env + "\\WhiteBalanceInfo.ini";
  if(FileExists(fileName))
    ReadCameraWhiteBalanceColorInfo(fileName, GlobalCameraIndex);

  int WhiteBalanceValue[3];

  WhiteBalanceValue[0] = WhiteBalanceInfo[GlobalCameraIndex].BColorInfo;
  WhiteBalanceValue[1] = WhiteBalanceInfo[GlobalCameraIndex].GColorInfo;
  WhiteBalanceValue[2] = WhiteBalanceInfo[GlobalCameraIndex].RColorInfo;

  SubCaptureFrame->SetWhiteBalanceValue(WhiteBalanceValue[0], 0);
  SubCaptureFrame->SetWhiteBalanceValue(WhiteBalanceValue[1], 1);
  SubCaptureFrame->SetWhiteBalanceValue(WhiteBalanceValue[2], 2);

  CameraNumberLabel->Caption = "Camera Number : #" + IntToStr(GlobalCameraIndex + 1);

  WhiteBalanceBValue->Position = WhiteBalanceInfo[GlobalCameraIndex].BColorInfo;
  WhiteBalanceGValue->Position = WhiteBalanceInfo[GlobalCameraIndex].GColorInfo;
  WhiteBalanceRValue->Position = WhiteBalanceInfo[GlobalCameraIndex].RColorInfo;

  WhiteBalanceBValueEdit->Text = IntToStr(WhiteBalanceBValue->Position);
  WhiteBalanceGValueEdit->Text = IntToStr(WhiteBalanceGValue->Position);
  WhiteBalanceRValueEdit->Text = IntToStr(WhiteBalanceRValue->Position);

  SubCaptureFrame->kind = 0;

  measureStartPos = 0;
  measureEndPos = SYSTEM_CAMERA_WIDTH;
  
  ImagePanel->Visible = true;
  SPBImagePanel->Visible = false;

  if(MachineSetupData.LasercomplexerInfo.Laser_complexer_Enable)
  {
    LaserTestGroupBox->Visible = true;
    EnabledDisk1SensorBtn->Visible = false;
    EnabledDisk2SensorBtn->Visible = false;
    TntButton1->Visible = true;
    LaserPositionCalBtn->Visible = true;
    LaserPosCalPanel->Visible = false;
  }
  else
  {
    LaserTestImagePanel->Visible = false;
    EnabledDisk1SensorBtn->Visible = false;
    EnabledDisk2SensorBtn->Visible = false;
    TntButton1->Visible = false;
    LaserPositionCalBtn->Visible = false;
    LaserPosCalPanel->Visible = false;
  }

  LaserTestTimer->Enabled = false;

  LaserCaptureSW = false;

  if(!ProductData.ProductName.IsEmpty())
  {
    AdvMachineControlForm->ApplyProductInfo();
  }
  else
  {
    AdvMachineControlForm->ApplyDefaultParams();
  }

  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++ )
  {
    AnsiString ConvertString;
    if(SystemLinkCameraInfo[globalCameraIndex] != 0)
    {
      TTntSpeedButton *CameraSpeedButton = (TTntSpeedButton *)FindComponent("CameraSpeedButton" + IntToStr(globalCameraIndex+1));
      TTntLabel *ShutterSpeedCLabel = (TTntLabel *)FindComponent("ShutterSpeedCLabel" + IntToStr(globalCameraIndex+1));

      ConvertString = ConvertCameraIndex(globalCameraIndex);
      CameraSpeedButton->Caption = ConvertString;
      ShutterSpeedCLabel->Caption = ConvertString;
    }
  }

  if(GlobalProgramID == PROGRAM_ID_150P)
  {
    // SELMA150P
    int MoveD1 = ComponentReposition(2,ShutterSpeedCLabel3->Left,ShutterSpeedLabel3->Left,ShutterSpeedLabel3->Width);
    for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      AnsiString ConvertString;
      TTntLabel *ShutterSpeedCLabel = (TTntLabel *)FindComponent("ShutterSpeedCLabel" + IntToStr(globalCameraIndex+1));
      TTntEdit *ShutterSpeedEdit = (TTntEdit *)FindComponent("ShutterSpeedEdit" + IntToStr(globalCameraIndex+1));
      TTntEdit *CameraGainEdit = (TTntEdit *)FindComponent("CameraGainEdit" + IntToStr(globalCameraIndex+1));
      TTntLabel *ShutterSpeedLabel = (TTntLabel *)FindComponent("ShutterSpeedLabel" + IntToStr(globalCameraIndex+1));
      if(SystemLinkCameraInfo[globalCameraIndex] == 0)
      {
        TTntSpeedButton *CameraSpeedButton = (TTntSpeedButton *)FindComponent("CameraSpeedButton" + IntToStr(globalCameraIndex+1));


        CameraSpeedButton->Visible = false;
        ShutterSpeedCLabel->Visible = false;
        ShutterSpeedEdit->Visible = false;
        CameraGainEdit->Visible = false;
        ShutterSpeedLabel->Visible = false;

      }
      else
      {
        ShutterSpeedCLabel->Left += MoveD1;
        ShutterSpeedEdit->Left += MoveD1;
        ShutterSpeedLabel->Left += MoveD1;
        if(globalCameraIndex != SD1_3D_FRONT_FACE_CAMERA_INDEX-1 && globalCameraIndex != SD2_3D_FRONT_FACE_CAMERA_INDEX-1 )
        {
          CameraGainEdit->Left += MoveD1;
        }
      }
    }

    Image1->Visible = false;
    Image2->Visible = false;
  }
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::LoadSystemInfor(void)
{
  TIniFile *iniFile = new TIniFile(ProgramPath.Env + "\\SystemInfor.ini");
  float frameTime;
  int ledOnTime;
  float shutterDelay;

  if (iniFile)
  {
    frameTime = iniFile->ReadFloat("Calibration", "Frame Time", 100);
    ledOnTime = 13;//iniFile->ReadInteger("Calibration", "LED On Time", 3);
    shutterDelay = iniFile->ReadFloat("Calibration", "Shutter Delay", 1);

    FrameTimeEdit->Text = FloatToStr(frameTime);
    LedOnTimeEdit->Text = FloatToStr(ledOnTime);
    ShutterDelayEdit->Text = FloatToStr(shutterDelay);

    delete iniFile;
  }
  else
  {
    ShowMessageW(CAPTUREFORM_MSG_01);
  }

  bLockRefreshOffsetInfo = true;
  if(!ProductData.ProductName.IsEmpty())
  {
     for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      ShutterSpeedList[globalCameraIndex] = ProductData.ShutterSpeed[globalCameraIndex];
      DigitalGainList[globalCameraIndex] = ProductData.DigitalGainV[globalCameraIndex];

      TTntEdit *shutterSpeedEdit = (TTntEdit *) FindComponent("ShutterSpeedEdit" + IntToStr(globalCameraIndex + 1));
      shutterSpeedEdit->Text = IntToStr(ShutterSpeedList[globalCameraIndex]);

      if(globalCameraIndex == 4 || globalCameraIndex == 12) continue;
      
      TTntEdit *CameraGainEdit = (TTntEdit *) FindComponent("CameraGainEdit" + IntToStr(globalCameraIndex + 1));
      CameraGainEdit->Text = IntToStr(DigitalGainList[globalCameraIndex]);

    }
  }
  else
  {
     for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      ShutterSpeedList[globalCameraIndex] = InitialValues.ShutterSpeed[globalCameraIndex];
      DigitalGainList[globalCameraIndex] = InitialValues.DigitalGain[globalCameraIndex];

      TTntEdit *shutterSpeedEdit = (TTntEdit *) FindComponent("ShutterSpeedEdit" + IntToStr(globalCameraIndex + 1));
      shutterSpeedEdit->Text = IntToStr(ShutterSpeedList[globalCameraIndex]);

      if(globalCameraIndex == 4 || globalCameraIndex == 12) continue;
      
      TTntEdit *CameraGainEdit = (TTntEdit *) FindComponent("CameraGainEdit" + IntToStr(globalCameraIndex + 1));
      CameraGainEdit->Text = IntToStr(DigitalGainList[globalCameraIndex]);

    }
  }
  bLockRefreshOffsetInfo = false;

  ColorCodeEdit->Text = ProductData.TabletColorCode;
  CaptureTabletColor = GetColorByCode(ProductData.TabletColorCode);
  TabletColorShape->Brush->Color = CaptureTabletColor;
  TabletColorLabelR->Caption = "R = " + IntToStr((CaptureTabletColor >> 0)  & 0xFF);
  TabletColorLabelG->Caption = "G = " + IntToStr((CaptureTabletColor >> 8)  & 0xFF);
  TabletColorLabelB->Caption = "B = " + IntToStr((CaptureTabletColor >> 16) & 0xFF);

  ReadSystemCameraOffsetImage(DigitalGainList);
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::CameraSpeedButton1Click(TObject *Sender)
{
  TTntSpeedButton *theSpeedButton = (TTntSpeedButton *) Sender;
  GlobalCameraIndex = theSpeedButton->Tag;
  ChangeCamera();

  if(GlobalCameraIndex == 4 || GlobalCameraIndex == 12) // 3D Camera
  {
    CameraSetting_3D_Button->Enabled = true;
    SPBCaptureStartButton->Enabled =false;
    SPBCaptureEndButton->Enabled =false;
    GroupBox5->Visible = false;
    ThreeDOptionGroupBox->Visible = true;

    SetApplyThreeDParams(GlobalCameraIndex);
  }
  else
  {
    CameraSetting_3D_Button->Enabled = false;
    //CameraSettingButton->Enabled = true;
    SPBCaptureStartButton->Enabled =true;
    SPBCaptureEndButton->Enabled =true;
    ThreeDOptionGroupBox->Visible = false;

    if(ImageLoadRadioBtn->ItemIndex == 1)
      GroupBox5->Visible = false;
    else
      GroupBox5->Visible = true;

    AnsiString fileName;
    fileName = ProgramPath.Env + "\\WhiteBalanceInfo.ini";
    ReadCameraWhiteBalanceColorInfo(fileName, GlobalCameraIndex);

    int WhiteBalanceValue[3];

    WhiteBalanceValue[0] = WhiteBalanceInfo[GlobalCameraIndex].BColorInfo;
    WhiteBalanceValue[1] = WhiteBalanceInfo[GlobalCameraIndex].GColorInfo;
    WhiteBalanceValue[2] = WhiteBalanceInfo[GlobalCameraIndex].RColorInfo;

    SubCaptureFrame->SetWhiteBalanceValue(WhiteBalanceValue[0], 0);
    SubCaptureFrame->SetWhiteBalanceValue(WhiteBalanceValue[1], 1);
    SubCaptureFrame->SetWhiteBalanceValue(WhiteBalanceValue[2], 2);

    CameraNumberLabel->Caption = "Camera Number : #" + IntToStr(GlobalCameraIndex + 1);

    WhiteBalanceBValue->Position = WhiteBalanceInfo[GlobalCameraIndex].BColorInfo;
    WhiteBalanceGValue->Position = WhiteBalanceInfo[GlobalCameraIndex].GColorInfo;
    WhiteBalanceRValue->Position = WhiteBalanceInfo[GlobalCameraIndex].RColorInfo;

    WhiteBalanceBValueEdit->Text = IntToStr(WhiteBalanceBValue->Position);
    WhiteBalanceGValueEdit->Text = IntToStr(WhiteBalanceGValue->Position);
    WhiteBalanceRValueEdit->Text = IntToStr(WhiteBalanceRValue->Position);
  }
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::ShutterSpeedEditChange(TObject *Sender)
{
	TTntEdit *shutterSpeedEdit = (TTntEdit *) Sender;
  int globalCameraIndex = shutterSpeedEdit->Tag;
	try
  {
    int shutterSpeed = StrToInt(shutterSpeedEdit->Text);
		double shuterSpeedMS = shutterSpeed / 1000.0;
    TTntLabel *shutterSpeedLabel = (TTntLabel *) FindComponent("ShutterSpeedLabel" + IntToStr(globalCameraIndex + 1));
    WCHAR TempString[100];
    wsprintfW(TempString, L"%Sms", FloatToStrF( shuterSpeedMS, ffFixed, 10, 3));
    shutterSpeedLabel->Caption = TempString;
    ShutterSpeedList[globalCameraIndex] = shutterSpeed;
  }
  catch(...)
  {

  }
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::HCBCaptureFrameButtonClick(TObject *Sender)
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
	  int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
	  int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
	  Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));
  }
  
  ImageLoadRadioBtn->ItemIndex = 0;

	if (SendSPBCaptureSetup())
	{
		if (CameraMapInfo[GlobalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D) // 3d camera
		{
			SubCaptureFrame->SetCaptureProperty(IMAGE_WIDTH_3D * 2, IMAGE_HEIGHT_3D, CaptureImage, pf8bit);
		}
		else
		{
			SubCaptureFrame->SetCaptureProperty(CAM_Width, CAM_Height, CaptureImage, pf24bit);
		}
		SubCaptureFrame->CaptureStart(true, false , ResolutionRadioGroup->ItemIndex);
  }

  TCaptureCommandParam_HCB captureCommandParam_HCB;
  try
  {
	  captureCommandParam_HCB.Action = 1;
    captureCommandParam_HCB.FrameTime = 0;
    captureCommandParam_HCB.LEDOnTime[0] = StrToFloat(LedOnTimeEdit->Text) * 20 + 0.5;

		captureCommandParam_HCB.LEDMask[0] = LEDOnMask[GlobalCameraIndex];
		captureCommandParam_HCB.ShutterDelay = StrToFloat(ShutterDelayEdit->Text) * 20 + 0.5;

    if (!Comm_Request(COMM_HCB, CMD_TABLET_CAPTURE, &captureCommandParam_HCB, sizeof(TCaptureCommandParam_HCB), NULL, 0))
    {
      throw Exception("");
    }
	}
  catch (...)
  {
    SubCaptureFrame->CaptureStop();
  }

  LaserTestImagePanel->Visible = false;
  LaserTestTimer->Enabled = false;
}
//---------------------------------------------------------------------------
bool __fastcall TCaptureForm::SendSPBCaptureSetup(void)
{
	bool returnValue = true;

	TCaptureSetupData captureSetupData;

	int spbIndex = CameraMapInfo[GlobalCameraIndex].SPBIndex;

	captureSetupData.CaptureType = CAPTURE_TYPE_SINGLE_CAPTURE;
	captureSetupData.CaptureMode = CAPTURE_MODE_DEFAULT;
	captureSetupData.FrameBufferCount = 3;

  if(ImageLoadRadioBtn->ItemIndex == 0)
  {
    int camIndex = CameraMapInfo[GlobalCameraIndex].CamIndex;

  	captureSetupData.CameraMask = (0x0001 << camIndex);

    RefreshCameraInfo(GlobalCameraIndex);

    captureSetupData.ShutterSpeed[camIndex] = ShutterSpeedList[GlobalCameraIndex];
    captureSetupData.SubsamplingMode[camIndex] = SubsamplingModeList[GlobalCameraIndex];
	  captureSetupData.ShutterDelay[camIndex] = 0;

    int LineScanTime = StrToInt(TriggerFreqEdit->Text);

    if (GlobalCameraIndex + 1 < HALF_INSPECTION_CAMERA_INDEX) // 모듈(SD1, 2) 구분
    {
      if(LineScanTime == 0)
        captureSetupData.TriggerFreq[camIndex] = RANGER_3D_BASE_SHUTTER_SPEED * MachineOperationInfo.ServoMotorSpeed[SD1_MOTOR_INDEX] / MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed; // 3D 이미지 원형 복원 check by moon
      else
        captureSetupData.TriggerFreq[camIndex] = LineScanTime;
    }
    else
    {
      if(LineScanTime == 0)
        captureSetupData.TriggerFreq[camIndex] = RANGER_3D_BASE_SHUTTER_SPEED2 * MachineOperationInfo.ServoMotorSpeed[SD2_MOTOR_INDEX] / MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed;
      else
        captureSetupData.TriggerFreq[camIndex] = LineScanTime;
    }
  }
  else
  {
    captureSetupData.CameraMask = 0;

    int stdSPBIndex = CameraMapInfo[GlobalCameraIndex].SPBIndex;
    for(int allCameraIndex = 0; allCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; allCameraIndex++)
    {
      if(stdSPBIndex == CameraMapInfo[allCameraIndex].SPBIndex && CameraMapInfo[allCameraIndex].CameraInspectPosition != CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[allCameraIndex] != 0)
      {
        int camIndex = CameraMapInfo[allCameraIndex].CamIndex;

        captureSetupData.CameraMask |= (0x0001 << camIndex);

        RefreshCameraInfo(allCameraIndex);

        captureSetupData.ShutterSpeed[camIndex] = ShutterSpeedList[allCameraIndex];
	      captureSetupData.ShutterDelay[camIndex] = 0;

        int LineScanTime = StrToInt(TriggerFreqEdit->Text);

        if (allCameraIndex + 1 < HALF_INSPECTION_CAMERA_INDEX) // 모듈(SD1, 2) 구분
        {
          if(LineScanTime == 0)
            captureSetupData.TriggerFreq[camIndex] = RANGER_3D_BASE_SHUTTER_SPEED * MachineOperationInfo.ServoMotorSpeed[SD1_MOTOR_INDEX] / MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed; // 3D 이미지 원형 복원 check by moon
          else
            captureSetupData.TriggerFreq[camIndex] = LineScanTime;
        }
        else
        {
          if(LineScanTime == 0)
            captureSetupData.TriggerFreq[camIndex] = RANGER_3D_BASE_SHUTTER_SPEED2 * MachineOperationInfo.ServoMotorSpeed[SD2_MOTOR_INDEX] / MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed;
          else
            captureSetupData.TriggerFreq[camIndex] = LineScanTime;
        }

        if(CameraMapInfo[allCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
        {
          captureSetupData.SubsamplingMode[camIndex] = RESOLUTION_NORMAL_QUALITY;
        }
        else
        {
          if(ResolutionRadioGroup->ItemIndex == 0)
            captureSetupData.SubsamplingMode[camIndex] = RESOLUTION_NORMAL_QUALITY;
          else
            captureSetupData.SubsamplingMode[camIndex] = RESOLUTION_HIGH_QUALITY;
        }

      }
    }
  }

	captureSetupData.ContainParams = 1;
	if(!ProductData.ProductName.IsEmpty())
	{
		captureSetupData.TabletType = ProductData.TabletType;
		captureSetupData.SensorLength= ProductData.StudiedSensor1Length;
	}
	else
	{
		captureSetupData.TabletType = 2;
		captureSetupData.SensorLength= 1000;
		
	}
	if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_SETUP, &captureSetupData, sizeof(TCaptureSetupData), NULL, 0))
  {
    returnValue = false;
  }
  return returnValue;
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::HCBCaptureButtonClick(TObject *Sender)
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
	  int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
	  int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
	  Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));
  }
  
	if (!bOnCapture)
	{
		if (SendSPBCaptureSetup())
		{
      if(ImageLoadRadioBtn->ItemIndex == 0)
      {
        if (CameraMapInfo[GlobalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D) // 3d camera
        {
          SubCaptureFrame->SetCaptureProperty(IMAGE_WIDTH_3D * 2, IMAGE_HEIGHT_3D, CaptureImage, pf8bit);
        }
        else
        {
          SubCaptureFrame->SetCaptureProperty(CAM_Width, CAM_Height, CaptureImage, pf24bit);
        }

        SubCaptureFrame->CaptureStart(false, false,ResolutionRadioGroup->ItemIndex);
      }
      else
      {
        ImageLoadProgressBar1->Position = 0;
        ImageLoadProgressBar2->Position = 0;
        ImageLoadProgressBar3->Position = 0;
        ImageLoadProgressBar4->Position = 0;

        SPBImageLoadTimer->Enabled = true;
      }

			TCaptureCommandParam_HCB captureCommandParam_HCB;
			captureCommandParam_HCB.Action = 1;
			captureCommandParam_HCB.FrameTime = StrToFloat(FrameTimeEdit->Text) * 20 + 0.5;
			captureCommandParam_HCB.LEDMask[0] = LEDOnMask[GlobalCameraIndex];
			captureCommandParam_HCB.LEDOnTime[0] = StrToFloat(LedOnTimeEdit->Text) * 20 + 0.5;
			captureCommandParam_HCB.ShutterDelay = StrToFloat(ShutterDelayEdit->Text) * 20 + 0.5;
			if (Comm_Request(COMM_HCB, CMD_TABLET_CAPTURE, &captureCommandParam_HCB, sizeof(TCaptureCommandParam_HCB),
				NULL, 0))
			{
				bOnCapture = true;
				HCBCaptureButton->Caption = "Capture Stop";
			}
			else
			{
				SubCaptureFrame->CaptureStop();
			}
		}
	}
	else
	{
		TCaptureCommandParam_HCB captureCommandParam_HCB;
		int camIndex = CameraMapInfo[GlobalCameraIndex].CamIndex;
		captureCommandParam_HCB.Action = 0;

    for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
      int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
      Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));
    }

		if (Comm_Request(COMM_HCB, CMD_TABLET_CAPTURE, &captureCommandParam_HCB, sizeof(TCaptureCommandParam_HCB),
			NULL, 0))
		{
			SubCaptureFrame->CaptureStop();

			bOnCapture = false;
			HCBCaptureButton->Caption = "Capture Start";
		}

    SPBImageLoadTimer->Enabled = false;
	}

  LaserTestImagePanel->Visible = false;
  LaserTestTimer->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::SensorCaptureStartButtonClick(
	  TObject *Sender)
{
  if (ProductData.ProductCode.IsEmpty())
	{
		ShowMessageFA(ADVMACHINECONTROLFORM_MSG_01);
		return;
	}

  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
	  int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
	  int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
	  Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));
  }

  ImageLoadRadioBtn->ItemIndex = 0;

  RefreshCameraInfo(GlobalCameraIndex);
  
	unsigned int camMask = 0;

	camMask = (0x0001 << GlobalCameraIndex);

	float tabletHalfLength = StrToFloat(TabletLengthEdit->Text) / 2;
	int triggerFreq_3D = StrToInt(TriggerFreqEdit->Text);

  if(0)//MachineSetupData.LasercomplexerInfo.Laser_complexer_Enable)
  {
    if((camMask & (0x0001 << (SD1_3D_FRONT_FACE_CAMERA_INDEX - 1))) == 0)
    {
      Set3DCamera_CaptureParameter(SD1_3D_FRONT_FACE_CAMERA_INDEX - 1, ThreeDCameraDefaultInformation[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].AnalogCameraGain, ThreeDCameraDefaultInformation[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].ExposureTime);
    }

    if((camMask & (0x0001 << (SD2_3D_FRONT_FACE_CAMERA_INDEX - 1))) == 0)
    {
      Set3DCamera_CaptureParameter(SD2_3D_FRONT_FACE_CAMERA_INDEX - 1, ThreeDCameraDefaultInformation[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].AnalogCameraGain, ThreeDCameraDefaultInformation[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].ExposureTime);
    }
  }

	if(LaserPosCalPanel->Visible)
	{
		int data[2];
		data[0] = StrToInt(EditInputX->Text);
		data[1] = StrToInt(EditInputY->Text);	
		for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
		{
			 if(globalCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
			 {
				int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
				Comm_Request(COMM_SPB + spbIndex, CMD_SEND_LASER_CAL_DATA, &data, sizeof(int)*2, NULL, 0);
			 }
		}
		  for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
		  {
		    if(globalCameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX - 1 || globalCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
		    {
		      if(CameraMapInfo[globalCameraIndex].CameraInspectPosition != CAMERA_POSITION_DISCONNECT)
		      {
		        camMask |= (0x0001 << globalCameraIndex);
		        RefreshCameraInfo(globalCameraIndex);
		      }
		    }
		  }

		float tabletHalfLength = StrToFloat(TabletLengthEdit->Text) / 2;
		int triggerFreq_3D = StrToInt(TriggerFreqEdit->Text);

		if (SendSPBCaptureSetup_Multi(&ProductData, camMask, tabletHalfLength, ShutterSpeedList,
			    MachineOperationInfo.ServoMotorSpeed[SD1_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed,
	        MachineOperationInfo.ServoMotorSpeed[SD2_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed,
	        0, true, 3, triggerFreq_3D))
		{
			SubCaptureFrame->SetCaptureProperty(CAM_Width, CAM_Height, CaptureImage, pf24bit);
			SubCaptureFrame->CaptureStart(false, false,ResolutionRadioGroup->ItemIndex);
		}

		TMachineCaptureSetupData machineCaptureSetupData;

		memcpy(machineCaptureSetupData.IlluminatorMask, MachineSetupData.MachineCaptureInfo.IlluminatorMask, SYSTEM_MACHINE_CAPTURE_COUNT * sizeof(int));
		machineCaptureSetupData.TabletLength = ProductData.TabletLength;
		machineCaptureSetupData.TabletSideThick = ProductData.TabletSideThick*10;
		machineCaptureSetupData.SuctionDiskSpeed = MachineOperationInfo.ServoMotorSpeed[SD1_MOTOR_INDEX];
		machineCaptureSetupData.StudiedTabletSensorLength = ProductData.StudiedSensor1Length;
	 	 machineCaptureSetupData.CaptureOption = 0;

		Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE, &machineCaptureSetupData, sizeof(TMachineCaptureSetupData), NULL, 0);	
	}
	else
		{
		if (SendSPBCaptureSetup_Multi(&ProductData, camMask, tabletHalfLength, ShutterSpeedList,
			    MachineOperationInfo.ServoMotorSpeed[SD1_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed,
	        MachineOperationInfo.ServoMotorSpeed[SD2_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed,
	        ResolutionRadioGroup->ItemIndex, true, 3, triggerFreq_3D))
		{
			if (CameraMapInfo[GlobalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D) // 3d camera
			{
				SubCaptureFrame->SetCaptureProperty(IMAGE_WIDTH_3D * 2, IMAGE_HEIGHT_3D, CaptureImage, pf8bit);
			}
			else
			{
				SubCaptureFrame->SetCaptureProperty(CAM_Width, CAM_Height, CaptureImage, pf24bit);
			}
			SubCaptureFrame->CaptureStart(false, false,ResolutionRadioGroup->ItemIndex);
		}

		TMachineCaptureSetupData machineCaptureSetupData;

		memcpy(machineCaptureSetupData.IlluminatorMask, MachineSetupData.MachineCaptureInfo.IlluminatorMask, SYSTEM_MACHINE_CAPTURE_COUNT * sizeof(int));
		machineCaptureSetupData.TabletLength = ProductData.TabletLength;
		machineCaptureSetupData.TabletSideThick = ProductData.TabletSideThick*10;
		machineCaptureSetupData.SuctionDiskSpeed = MachineOperationInfo.ServoMotorSpeed[SD1_MOTOR_INDEX];
		machineCaptureSetupData.StudiedTabletSensorLength = ProductData.StudiedSensor1Length;
	  machineCaptureSetupData.CaptureOption = 2;

		if (!Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE, &machineCaptureSetupData, sizeof(TMachineCaptureSetupData),
			NULL, 0))
		{
			SubCaptureFrame->CaptureStop();
		}
	}

  LaserTestImagePanel->Visible = false;
  LaserTestTimer->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::SensorCaptureStopButtonClick(TObject *Sender)
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
	  int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
	  int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
	  Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));
  }
  
	SubCaptureFrame->CaptureStop();
	SPBImageLoadTimer->Enabled = false;
	Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP);
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::SaveDefaultShutterSpeedButtonClick(
	  TObject *Sender)
{
	for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
	{
		InitialValues.ShutterSpeed[globalCameraIndex] = ShutterSpeedList[globalCameraIndex];
    InitialValues.DigitalGain[globalCameraIndex] = DigitalGainList[globalCameraIndex];
	}
  
	WriteInitialValues(ProgramPath.Env + "\\Initials.ini");
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::SaveProductShutterSpeedButtonClick(
      TObject *Sender)
{
  for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    ProductData.ShutterSpeed[globalCameraIndex] = ShutterSpeedList[globalCameraIndex];
    ProductData.DigitalGainV[globalCameraIndex] = DigitalGainList[globalCameraIndex];
  }

  ProductData.StudyStep = STUDY_STEP_NONE;

  AnsiString fileName = GetProductDataFileName(ProductData.ProductCode);
  if (WriteProductData(fileName, ProductData))
  {
    ShowMessageFA(CAPTUREFORM_MSG_05);
  }
  else
  {
    ShowMessageFA(CAPTUREFORM_MSG_06);
  }
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::CaptureSettingButtonClick(TObject *Sender)
{
	TVisionSettingForm *visionSettingForm = new TVisionSettingForm(this);
  visionSettingForm->SetCaptureInfo(MachineSetupData.MachineCaptureInfo);
  if (visionSettingForm->ShowModal() == mrOk)
  {
    visionSettingForm->GetCaptureInfo(MachineSetupData.MachineCaptureInfo);
    Comm_Request(COMM_HCB, CMD_MACHINE_PARAM_SETUP, &MachineSetupData, sizeof(TMachineSetupData));
    WriteMachineSetupData(ProgramPath.Env + "\\SystemInfor.ini", MachineSetupData);
  }
	delete visionSettingForm;	
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::LEDCheckBoxClick(TObject *Sender)
{
	TTntCheckBox *theCheckBox = (TTntCheckBox *) Sender;
  int ledIndex = theCheckBox->Tag;
  if (theCheckBox->Checked)
	{
		LEDOnMask[GlobalCameraIndex] |= (0x0001 << ledIndex);
	}
	else
	{
		LEDOnMask[GlobalCameraIndex] &= ~(0x0001 << ledIndex);
  }

  SendLEDInfor();
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::RefreshLEDCheckBox(void)
{
	for (int ledIndex = 0; ledIndex < SYSTEM_TOTAL_LED_COUNT; ledIndex++)
	{
		TTntCheckBox *theCheckBox = (TTntCheckBox *) FindComponent("LEDCheckBox" + IntToStr(ledIndex + 1));
		if (theCheckBox)
		{
			if (LEDOnMask[GlobalCameraIndex] & (0x0001 << ledIndex))
			{
				theCheckBox->Checked = true;
			}
			else
			{
				theCheckBox->Checked = false;
			}
		}
	}
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::SendLEDInfor(void)
{
	if (Comm_IsConnected(COMM_HCB))
	{
		Comm_Request(COMM_HCB, CMD_LED_CHANGE, &LEDOnMask[GlobalCameraIndex], sizeof(unsigned int));
	}
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::RefreshPixelInfo(int X, int Y)
{
	TColor color = CaptureImage->Canvas->Pixels[X][Y];
	int redVal = color & 0xFF;
	int greenVal = (color >> 8) & 0xFF;
	int blueVal = (color >> 16) & 0xFF;
	AnsiString redText = IntToStr(redVal);
	AnsiString greenText = IntToStr(greenVal);
	AnsiString blueText = IntToStr(blueVal);
	RedImage->Canvas->Brush->Color = clRed;
	RedImage->Canvas->Font->Color = clWhite;
	RedImage->Canvas->TextRect(Rect(0, 0, redVal, RedImage->Height),
		(RedImage->Width - RedImage->Canvas->TextWidth(redText)) / 2,
		(RedImage->Height - RedImage->Canvas->TextHeight(redText)) / 2, redText);
	RedImage->Canvas->Brush->Color = clWhite;
	RedImage->Canvas->Font->Color = clRed;
	RedImage->Canvas->TextRect(Rect(redVal, 0, RedImage->Width, RedImage->Height),
		(RedImage->Width - RedImage->Canvas->TextWidth(redText)) / 2,
		(RedImage->Height - RedImage->Canvas->TextHeight(redText)) / 2, redText);

	GreenImage->Canvas->Brush->Color = clGreen;
	GreenImage->Canvas->Font->Color = clWhite;
	GreenImage->Canvas->TextRect(Rect(0, 0, greenVal, GreenImage->Height),
		(GreenImage->Width - GreenImage->Canvas->TextWidth(greenText)) / 2,
		(GreenImage->Height - GreenImage->Canvas->TextHeight(greenText)) / 2, greenText);
	GreenImage->Canvas->Brush->Color = clWhite;
	GreenImage->Canvas->Font->Color = clGreen;
	GreenImage->Canvas->TextRect(Rect(greenVal, 0, GreenImage->Width, GreenImage->Height),
		(GreenImage->Width - GreenImage->Canvas->TextWidth(greenText)) / 2,
		(GreenImage->Height - GreenImage->Canvas->TextHeight(greenText)) / 2, greenText);

	BlueImage->Canvas->Brush->Color = clBlue;
	BlueImage->Canvas->Font->Color = clWhite;
	BlueImage->Canvas->TextRect(Rect(0, 0, blueVal, BlueImage->Height),
		(BlueImage->Width - BlueImage->Canvas->TextWidth(blueText)) / 2,
		(BlueImage->Height - BlueImage->Canvas->TextHeight(blueText)) / 2, blueText);
	BlueImage->Canvas->Brush->Color = clWhite;
	BlueImage->Canvas->Font->Color = clBlue;
	BlueImage->Canvas->TextRect(Rect(blueVal, 0, BlueImage->Width, BlueImage->Height),
		(BlueImage->Width - BlueImage->Canvas->TextWidth(blueText)) / 2,
		(BlueImage->Height - BlueImage->Canvas->TextHeight(blueText)) / 2, blueText);
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::CaptureImageMouseMove(TObject *Sender,
	  TShiftState Shift, int X, int Y)
{
	MousePos.x = X;
	MousePos.y = Y;
	RefreshSubImage();
	RefreshPixelInfo(MousePos.x, MousePos.y);
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::RefreshSubImage(void)
{
	EnlargeImage->Canvas->CopyRect(Rect(0, 0, 51, 51), CaptureImage->Canvas, Rect(MousePos.x - 25, MousePos.y - 25, MousePos.x + 26, MousePos.y + 26));
	EnlargeImage->Canvas->Pen->Width = 1;
	EnlargeImage->Canvas->Pen->Mode = pmXor;
	EnlargeImage->Canvas->Pen->Style = psSolid;
	EnlargeImage->Canvas->MoveTo(25, 24);
	EnlargeImage->Canvas->LineTo(25, 26);
	EnlargeImage->Canvas->MoveTo(24, 25);
	EnlargeImage->Canvas->LineTo(26, 25);
}
//---------------------------------------------------------------------------


void __fastcall TCaptureForm::LoadDefaultButtonClick(TObject *Sender)
{
	if (MessageDlgFA(CAPTUREFORM_MSG_08, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
  {
    AnsiString colorCodeName = ColorCodeEdit->Text;
    AnsiString shutterSpeedFileName = ProgramPath.Env + "\\ShutterSpeedInfor.ini";
    AnsiString threeDParameterInfoFileName = ProgramPath.Env + "\\ThreeDParamInfor.ini";

    unsigned int twoDCameraMap = 0;
    unsigned int threeDCameraMap = 0;
    for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if (CameraMapInfo[globalCameraIndex].CameraInspectPosition != CAMERA_POSITION_3D)
      {
        twoDCameraMap |= (0x0001 << globalCameraIndex);
      }
      else
      {
        threeDCameraMap |= (0x0001 << globalCameraIndex);
      }
    }

    AnsiString loadedColorCodeName = LoadShutterSpeedInfo(shutterSpeedFileName, colorCodeName, CaptureTabletColor, ShutterSpeedList, twoDCameraMap, DigitalGainList);

    int ThresholdList[SYSTEM_TOTAL_CAMERA_COUNT];
    Load3DParameterInfo(threeDParameterInfoFileName, colorCodeName, CaptureTabletColor, ShutterSpeedList, ThresholdList, threeDCameraMap);

    if (colorCodeName == loadedColorCodeName)
    {
      ShowMessageFA(CAPTUREFORM_MSG_02);
    }
    else if (loadedColorCodeName == "")
    {
      ShowMessageFA(CAPTUREFORM_MSG_03);
    }
    else
    {
      WCHAR TempString[100];
      wsprintfW(TempString, CAPTUREFORM_MSG_04, loadedColorCodeName);
      ShowMessageFA(TempString);
    }

    bLockRefreshOffsetInfo = true;
    for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      TTntEdit *shutterSpeedEdit = (TTntEdit *) FindComponent("ShutterSpeedEdit" + IntToStr(globalCameraIndex + 1));
      shutterSpeedEdit->Text = IntToStr(ShutterSpeedList[globalCameraIndex]);

	  if(globalCameraIndex == 4 || globalCameraIndex == 12) continue;

      TTntEdit *digitalgainSpeedEdit = (TTntEdit *) FindComponent("CameraGainEdit" + IntToStr(globalCameraIndex + 1));
      digitalgainSpeedEdit->Text = IntToStr(DigitalGainList[globalCameraIndex]);
    }
    bLockRefreshOffsetInfo = false;

    ReadSystemCameraOffsetImage(DigitalGainList);
  }
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::ColorCodeEditClick(TObject *Sender)
{
	TColorCodeForm *colorCodeForm = new TColorCodeForm(this);
	if (colorCodeForm->ShowModal() == mrOk)
  {
    AnsiString colorCodeName = colorCodeForm->GetColorCodeName();
    ColorCodeEdit->Text = colorCodeName;
    CaptureTabletColor = GetColorByCode(colorCodeName);
    TabletColorShape->Brush->Color = CaptureTabletColor;
    TabletColorLabelR->Caption = "R = " + IntToStr((CaptureTabletColor >> 0)  & 0xFF);
    TabletColorLabelG->Caption = "G = " + IntToStr((CaptureTabletColor >> 8)  & 0xFF);
    TabletColorLabelB->Caption = "B = " + IntToStr((CaptureTabletColor >> 16) & 0xFF);
  }
  delete colorCodeForm;
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::SaveColorShutterSpeedButtonClick(
      TObject *Sender)
{
  if (MessageDlgFA(CAPTUREFORM_MSG_07, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
  {
    // save shutter speed info
    AnsiString colorCodeName = ColorCodeEdit->Text;
    AnsiString shutterSpeedFileName = ProgramPath.Env + "\\ShutterSpeedInfor.ini";
    unsigned int twoDCameraMap = 0;
    unsigned int threeDCameraMap = 0;
    for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if (CameraMapInfo[globalCameraIndex].CameraInspectPosition != CAMERA_POSITION_3D)
      {
        twoDCameraMap |= (0x0001 << globalCameraIndex);
      }
      else
      {
        threeDCameraMap |= (0x0001 << globalCameraIndex);
      }
    }

    if (SaveShutterSpeedInfo(shutterSpeedFileName, colorCodeName, CaptureTabletColor, ShutterSpeedList, twoDCameraMap,DigitalGainList))
    {
      ShowMessageFA("Success to Save");
    }
    else
    {
      ShowMessageFA("Fail to Save");
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::LoadSystemDefaultButtonClick(TObject *Sender)
{
	if (MessageDlgFA(CAPTUREFORM_GROUPBOX_CAPTION_01, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
  {
    bLockRefreshOffsetInfo = true;
    for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      ShutterSpeedList[globalCameraIndex] = InitialValues.ShutterSpeed[globalCameraIndex];
      DigitalGainList[globalCameraIndex] = InitialValues.DigitalGain[globalCameraIndex];

      TTntEdit *shutterSpeedEdit = (TTntEdit *) FindComponent("ShutterSpeedEdit" + IntToStr(globalCameraIndex + 1));
      shutterSpeedEdit->Text = IntToStr(ShutterSpeedList[globalCameraIndex]);

		  if(globalCameraIndex == 4 || globalCameraIndex == 12) continue;

      TTntEdit *CameraGainEdit = (TTntEdit *) FindComponent("CameraGainEdit" + IntToStr(globalCameraIndex + 1));
      CameraGainEdit->Text = IntToStr(DigitalGainList[globalCameraIndex]);
    }
    bLockRefreshOffsetInfo = false;

    ReadSystemCameraOffsetImage(DigitalGainList);
  }
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::CameraMappingButtonClick(TObject *Sender)
{
	TCameraMappingForm *cameraMappingForm = new TCameraMappingForm(this);
  cameraMappingForm->ShowModal();
  delete cameraMappingForm;
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::CameraSettingButtonClick(TObject *Sender)
{
	if (NFA2DCameraSettingForm == NULL)
	{
		NFA2DCameraSettingForm = new TNFA2DCameraSettingForm(Application);
	}
	NFA2DCameraSettingForm->SetGlobalCameraIndex(GlobalCameraIndex);
  NFA2DCameraSettingForm->ReadAllButton->Click();
	NFA2DCameraSettingForm->ShowModal();
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::CloseButtonClick(TObject *Sender)
{
  SensorCaptureStopButton->Click();
  Machine.MachineStop();

  DisabledThreeDLaserSensor(SD1_3D_FRONT_FACE_CAMERA_INDEX - 1);
  DisabledThreeDLaserSensor(SD2_3D_FRONT_FACE_CAMERA_INDEX - 1);

  ThreeDSensorActiveStatus = THREED_SENSOR_OFF;

  Disk1ThreeDSensorErrorCode = THREED_SENSOR_ERROR_CODE_GOOD;
  Disk2ThreeDSensorErrorCode = THREED_SENSOR_ERROR_CODE_GOOD;

  RecentDisk1ThreeDCameraLSFValue = -1;
  RecentDisk2ThreeDCameraLSFValue = -1;

  this->Close();
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::NumEditClick(TObject *Sender)
{
	TTntEdit *theEdit = (TTntEdit *) Sender;
	KeyboardForm->Text = theEdit->Text;
  if (KeyboardForm->ShowKeypad() == mrOk)
  {
		theEdit->Text = KeyboardForm->Text;
	}
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::SubCaptureFrameCaptureCheckTimerTimer(
	  TObject *Sender)
{
  try
  {
    SubCaptureFrame->CaptureCheckTimerTimer(Sender);
    RefreshSubImage();
    RefreshPixelInfo(MousePos.x, MousePos.y);

    if (ShowFovGridLineSpeedButton->Down)
    {
      AreaSelectPositionDisplay();

      float x, y;
      float gridSize;
      gridSize = (float)CAM_Width/ StrToFloat(FOVEdit->Text);

      CaptureImage->Canvas->Pen->Color = clDkGray;
      CaptureImage->Canvas->Pen->Width = 1;
      CaptureImage->Canvas->Brush->Style = bsClear;

      int centerX;
      int centerY;

      centerX = CAM_Width / 2;
      centerY = CAM_Height / 2;

      if(CAM_Width == 1280)
      {
        for(y = centerY; y >= 0; y -= (int)gridSize)
        {
          CaptureImage->Canvas->MoveTo(0, y);
          CaptureImage->Canvas->LineTo(CAM_Width, y);

          CaptureImage->Canvas->MoveTo(0, y + 1);
          CaptureImage->Canvas->LineTo(CAM_Width, y + 1);
        }

        for(y = centerY + gridSize; y < CAM_Height; y += (int)gridSize)
        {
          CaptureImage->Canvas->MoveTo(0, y);
          CaptureImage->Canvas->LineTo(CAM_Width, y);

          CaptureImage->Canvas->MoveTo(0, y + 1);
          CaptureImage->Canvas->LineTo(CAM_Width, y + 1);
        }

        for(x = centerX; x >= 0; x -= (int)gridSize)
        {
          CaptureImage->Canvas->MoveTo(x, 0);
          CaptureImage->Canvas->LineTo(x, CAM_Height);

          CaptureImage->Canvas->MoveTo(x + 1, 0);
          CaptureImage->Canvas->LineTo(x + 1, CAM_Height);
        }

        for(x = centerX + gridSize; x < CAM_Width; x += (int)gridSize)
        {
          CaptureImage->Canvas->MoveTo(x, 0);
          CaptureImage->Canvas->LineTo(x, CAM_Height);

          CaptureImage->Canvas->MoveTo(x + 1, 0);
          CaptureImage->Canvas->LineTo(x + 1, CAM_Height);
        }
      }
      else
      {
        for(y = centerY; y >= 0; y -= (int)gridSize)
        {
          CaptureImage->Canvas->MoveTo(0, y);
          CaptureImage->Canvas->LineTo(CAM_Width, y);
        }

        for(y = centerY + gridSize; y < CAM_Height; y += (int)gridSize)
        {
          CaptureImage->Canvas->MoveTo(0, y);
          CaptureImage->Canvas->LineTo(CAM_Width, y);
        }

        for(x = centerX; x >= 0; x -= (int)gridSize)
        {
          CaptureImage->Canvas->MoveTo(x, 0);
          CaptureImage->Canvas->LineTo(x, CAM_Height);
        }

        for(x = centerX + gridSize; x < CAM_Width; x += (int)gridSize)
        {
          CaptureImage->Canvas->MoveTo(x, 0);
          CaptureImage->Canvas->LineTo(x, CAM_Height);
        }
      }

      double halfTabletLength;
      int shiftSize;
      if(TabletLengthEdit->Text != NULL)
      {
        halfTabletLength = StrToFloat(TabletLengthEdit->Text) / 2;

        shiftSize = halfTabletLength * gridSize;

        CaptureImage->Canvas->Pen->Color = clRed;
        CaptureImage->Canvas->Pen->Width = 1;
		    CaptureImage->Canvas->Pen->Style = psSolid;

        if(CAM_Width == 1280)
        {
          CaptureImage->Canvas->MoveTo(CAM_Width / 2 - shiftSize, 0);
          CaptureImage->Canvas->LineTo(CAM_Width / 2 - shiftSize, CAM_Height);

          CaptureImage->Canvas->MoveTo(CAM_Width / 2 - shiftSize + 1, 0);
          CaptureImage->Canvas->LineTo(CAM_Width / 2 - shiftSize + 1, CAM_Height);

          CaptureImage->Canvas->MoveTo(CAM_Width / 2 + shiftSize, 0);
          CaptureImage->Canvas->LineTo(CAM_Width / 2 + shiftSize, CAM_Height);

          CaptureImage->Canvas->MoveTo(CAM_Width / 2 + shiftSize + 1, 0);
          CaptureImage->Canvas->LineTo(CAM_Width / 2 + shiftSize + 1, CAM_Height);
        }
        else
        {
          CaptureImage->Canvas->MoveTo(CAM_Width / 2 - shiftSize, 0);
          CaptureImage->Canvas->LineTo(CAM_Width / 2 - shiftSize, CAM_Height);

          CaptureImage->Canvas->MoveTo(CAM_Width / 2 + shiftSize, 0);
          CaptureImage->Canvas->LineTo(CAM_Width / 2 + shiftSize, CAM_Height);
        }
      }

      CaptureImage->Refresh();
    }
  }
  catch(...)
  {

  }
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::AreaSelectPositionDisplay(void)
{
  CaptureImage->Canvas->Pen->Width = 2;
  int StartPos =measureStartPos;
  int EndPos = measureEndPos;
  int drawPosS =measureStartPos;
  int drawPosE = measureEndPos;
  if(CAM_Width == 1280)
  {
   CaptureImage->Canvas->Pen->Width = 4;
   drawPosS =measureStartPos*2;
   drawPosE = measureEndPos*2;

  }

  CaptureImage->Canvas->Brush->Style = bsClear;
  CaptureImage->Canvas->Pen->Color = clYellow;
  CaptureImage->Canvas->MoveTo(drawPosS, 0);
  CaptureImage->Canvas->LineTo(drawPosS, CAM_Height);

  CaptureImage->Canvas->Brush->Style = bsClear;
  CaptureImage->Canvas->Pen->Color = clYellow;
  CaptureImage->Canvas->MoveTo(drawPosE, 0);
  CaptureImage->Canvas->LineTo(drawPosE, CAM_Height);

  CaptureImage->Canvas->Pen->Width = 1;



  float gridSize = (float)SYSTEM_CAMERA_WIDTH / (float)StrToFloat(FOVEdit->Text);
  int pxDiff = abs(EndPos - StartPos);

  ProductLengthEdit->Text = FloatToStr((float)pxDiff / (float)gridSize);
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::CameraSetting_3D_ButtonClick(TObject *Sender)
{
	TCameraSetting3DForm *cameraSetting3DForm = new TCameraSetting3DForm(this);
	cameraSetting3DForm->ShowModal();
	delete cameraSetting3DForm;
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::SPBCaptureStartButtonClick(TObject *Sender)
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
	  int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
	  int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
	  Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));
  }
  
	int spbIndex = CameraMapInfo[GlobalCameraIndex].SPBIndex;

	TCaptureCommandParam captureCommandParam;
	captureCommandParam.CaptureMode = CAPTURE_MODE_CONTINUOUS;

  if(ImageLoadRadioBtn->ItemIndex == 0)
  {
    int camIndex = CameraMapInfo[GlobalCameraIndex].CamIndex;
    
	  captureCommandParam.CameraMask = 0x01 << camIndex;
    captureCommandParam.ShutterSpeed[camIndex] = ShutterSpeedList[GlobalCameraIndex];
    captureCommandParam.SubsamplingMode[camIndex] = SubsamplingModeList[GlobalCameraIndex];
    RefreshCameraInfo(GlobalCameraIndex);
  }
  else
  {
    captureCommandParam.CameraMask = 0;
    
    int stdSPBIndex = CameraMapInfo[GlobalCameraIndex].SPBIndex;
    for(int allCameraIndex = 0; allCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; allCameraIndex++)
    {
      if(stdSPBIndex == CameraMapInfo[allCameraIndex].SPBIndex && CameraMapInfo[allCameraIndex].CameraInspectPosition != CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[allCameraIndex] != 0)
      {
        int camIndex = CameraMapInfo[allCameraIndex].CamIndex;

        captureCommandParam.CameraMask |= 0x01 << camIndex;
        captureCommandParam.ShutterSpeed[camIndex] = ShutterSpeedList[allCameraIndex];
        captureCommandParam.SubsamplingMode[camIndex] = SubsamplingModeList[allCameraIndex];
        RefreshCameraInfo(allCameraIndex);
      }
    }
  }

	captureCommandParam.FrameBufferCount = StrToInt(SPBFrameCountEdit->Text);
	captureCommandParam.CaptureKind = CAPTURE_KIND_FRAME;

	if (Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_START, &captureCommandParam, sizeof(TCaptureCommandParam)))
	{
    if(ImageLoadRadioBtn->ItemIndex == 0)
    {
      if (CameraMapInfo[GlobalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D) // 3d camera
      {
        SubCaptureFrame->SetCaptureProperty(IMAGE_WIDTH_3D * 2, IMAGE_HEIGHT_3D, CaptureImage, pf8bit);
      }
      else
      {
        SubCaptureFrame->SetCaptureProperty(CAM_Width, CAM_Height, CaptureImage, pf24bit);
      }
		  SubCaptureFrame->CaptureStart(false, false,ResolutionRadioGroup->ItemIndex);
    }
    else
    {
      ImageLoadProgressBar1->Position = 0;
      ImageLoadProgressBar2->Position = 0;
      ImageLoadProgressBar3->Position = 0;
      ImageLoadProgressBar4->Position = 0;

      SPBImageLoadTimer->Enabled = true;
    }
	}

  LaserTestImagePanel->Visible = false;
  LaserTestTimer->Enabled = false;
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::SPBCaptureEndButtonClick(TObject *Sender)
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
	  int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
	  int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
	  Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));
  }

	SubCaptureFrame->CaptureStop();
  SPBImageLoadTimer->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::AdvMachineControlButtonClick(TObject *Sender)
{
  AdvMachineControlForm->ShowModal();
}                                                                                              
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::RefreshCameraInfo(int cameraIndex)
{
  // 사용자가 설정한 ShutterSpeed, Threshold, ROI(는 사실 Default) 를 반영
  int ShutterSpeed = 0;
  int Threshold = 0;
  int WriteMask = 0;
  int cameraGain = 1;

  TTntEdit *shutterSpeedEdit = (TTntEdit *) FindComponent("ShutterSpeedEdit" + IntToStr(cameraIndex + 1));
  TTntEdit *CameraGainEdit = (TTntEdit *) FindComponent("CameraGainEdit" + IntToStr(cameraIndex + 1));
  
  if(shutterSpeedEdit)
    ShutterSpeed = StrToInt(shutterSpeedEdit->Text);

  if(CameraGainEdit)
    cameraGain = StrToInt(CameraGainEdit->Text);


  if(CameraMapInfo[cameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
    WriteMask |= CAMERA_WRITE_MASK_3D_SH;
  else
    WriteMask |= CAMERA_WRITE_MASK_2D_SH;

  if(CameraMapInfo[cameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
  {
    Threshold = ProductData.ThresholdFor3D[cameraIndex];
    WriteMask |= CAMERA_WRITE_MASK_TH;
  }

  TROIInfo DefaultROIInfo, ApplyROIInfo;
  AnsiString filePath;
  filePath = ProgramPath.Env + "\\NFACameraInformation.ini";
  DefaultROIInfo = ReadCameraInformation(filePath, cameraIndex);

  // Calibration 화면에서는 Default 값으로 ROI를 설정한다.
  memcpy(&ApplyROIInfo, &DefaultROIInfo, sizeof(TROIInfo));

  if(CameraMapInfo[cameraIndex].CameraInspectPosition != CAMERA_POSITION_3D)
  {
    WriteMask |= CAMERA_WRITE_MASK_2D_ROI;
  }
  else
  {
    WriteMask |= CAMERA_WRITE_MASK_3D_ROI;
  }

  if(CameraMapInfo[cameraIndex].CameraInspectPosition != CAMERA_POSITION_3D)
  {
    WriteMask |= CAMERA_WRITE_MASK_2D_SUBSAMPLING_MODE;
  }

  SetCameraInformation(ApplyROIInfo, ShutterSpeed, Threshold,ResolutionRadioGroup->ItemIndex, cameraIndex, WriteMask);
  SetCameraGain(cameraIndex + 1, SYSTEM_DEFAULT_ANLOG_GAIN, cameraGain, 0);

  if(CameraMapInfo[cameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
  {
    int AnalogGain;
    int ExposureTime;

    if(LaserCaptureSW)
    {
      int ThreedCameraIndex = 0;
      if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
      {
        ThreedCameraIndex = 0;
      }
      else
      {
        ThreedCameraIndex = 1;
      }

      if(!ProductData.ProductName.IsEmpty())
      {
        if(ProductData.ExposureTime3D[ThreedCameraIndex] != -1)
        {
          AnalogGain = ProductData.AnalogGain3D[ThreedCameraIndex];
          ExposureTime = ProductData.ExposureTime3D[ThreedCameraIndex];
        }
        else
        {
          AnalogGain = ThreeDCameraDefaultInformation[cameraIndex].AnalogCameraGain;
          ExposureTime = ThreeDCameraDefaultInformation[cameraIndex].ExposureTime;
        }
      }
      else
      {
        AnalogGain = ThreeDCameraDefaultInformation[cameraIndex].AnalogCameraGain;
        ExposureTime = ThreeDCameraDefaultInformation[cameraIndex].ExposureTime;
      }
    }
    else
    {
      AnalogGain = StrToInt(ThreeDCameraGainEdit->Text);
      ExposureTime = StrToInt(ThreeDExposureTimeEdit->Text);
    }

    if(ExposureTime)
    {
      Set3DCamera_CaptureParameter(cameraIndex, AnalogGain, ExposureTime);
    }
  }
}

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


void __fastcall TCaptureForm::SubCaptureFrameStopTimerButtonClick(
      TObject *Sender)
{
  SubCaptureFrame->StopTimerButtonClick(Sender);
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::WhiteBalanceBValueChange(TObject *Sender)
{
  int WhiteBalanceValue;

  WhiteBalanceValue = WhiteBalanceBValue->Position;

  WhiteBalanceInfo[GlobalCameraIndex].BColorInfo = WhiteBalanceBValue->Position;

  SubCaptureFrame->SetWhiteBalanceValue(WhiteBalanceValue, 0);

  AnsiString fileName;
  fileName = ProgramPath.Env + "\\WhiteBalanceInfo.ini";
  WriteCameraWhiteBalanceColorInfo(fileName, GlobalCameraIndex, 0);

  WhiteBalanceBValueEdit->Text = IntToStr(WhiteBalanceBValue->Position);
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::WhiteBalanceBValueEditClick(TObject *Sender)
{
  TTntEdit *theEdit = (TTntEdit *) Sender;
	KeyboardForm->Text = theEdit->Text;
  if (KeyboardForm->ShowKeypad() == mrOk)
  {
		theEdit->Text = KeyboardForm->Text;

    if(theEdit->Tag == 0)
    {
      WhiteBalanceBValue->Position = StrToInt(theEdit->Text);
    }
    else if(theEdit->Tag == 1)
    {
      WhiteBalanceGValue->Position = StrToInt(theEdit->Text);
    }
    else if(theEdit->Tag == 2)
    {
      WhiteBalanceRValue->Position = StrToInt(theEdit->Text);
    }
	}
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::WhiteBalanceGValueChange(TObject *Sender)
{
  int WhiteBalanceValue;

  WhiteBalanceValue = WhiteBalanceGValue->Position;

  WhiteBalanceInfo[GlobalCameraIndex].GColorInfo = WhiteBalanceGValue->Position;

  SubCaptureFrame->SetWhiteBalanceValue(WhiteBalanceValue, 1);

  AnsiString fileName;
  fileName = ProgramPath.Env + "\\WhiteBalanceInfo.ini";
  WriteCameraWhiteBalanceColorInfo(fileName, GlobalCameraIndex, 1);

  WhiteBalanceGValueEdit->Text = IntToStr(WhiteBalanceGValue->Position);
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::WhiteBalanceRValueChange(TObject *Sender)
{
  int WhiteBalanceValue;

  WhiteBalanceValue = WhiteBalanceRValue->Position;

  WhiteBalanceInfo[GlobalCameraIndex].RColorInfo = WhiteBalanceRValue->Position;

  SubCaptureFrame->SetWhiteBalanceValue(WhiteBalanceValue, 2);

  AnsiString fileName;
  fileName = ProgramPath.Env + "\\WhiteBalanceInfo.ini";
  WriteCameraWhiteBalanceColorInfo(fileName, GlobalCameraIndex, 2);

  WhiteBalanceRValueEdit->Text = IntToStr(WhiteBalanceRValue->Position);
}
//---------------------------------------------------------------------------


void __fastcall TCaptureForm::Edit1Change(TObject *Sender)
{
  SubCaptureFrame->kind = StrToInt(Edit1->Text);  
}
//---------------------------------------------------------------------------


void __fastcall TCaptureForm::SPBImageLoadTimerTimer(TObject *Sender)
{
  bool bTimerEnabled;
  
  bTimerEnabled = SPBImageLoadTimer->Enabled;

  bool bCaptureExist;

	char cameraIndex;
	unsigned int data[2];
	unsigned int receivedData[2];
  unsigned char CaptureData[SYSTEM_CAMERA_WIDTH * SYSTEM_CAMERA_HEIGHT];
  unsigned char CaptureLargeData[SYSTEM_CAMERA_HD_WIDTH * SYSTEM_CAMERA_HD_HEIGHT];

  int CaptureWidth, CaptureHeight;

  CaptureWidth = CAM_Width;
  CaptureHeight = CAM_Height;

  int stdSPBIndex = CameraMapInfo[GlobalCameraIndex].SPBIndex;
  for(int allCameraIndex = 0; allCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; allCameraIndex++)
  {
    if(stdSPBIndex == CameraMapInfo[allCameraIndex].SPBIndex)
    {
      if (CameraMapInfo[allCameraIndex].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[allCameraIndex] == 0) continue;

      int camIndex = CameraMapInfo[allCameraIndex].CamIndex;

      data[0] = camIndex;
      data[1] = CaptureWidth * CaptureHeight;

      TImage *SPBImage = (TImage *) FindComponent("SPBImage" + IntToStr(camIndex + 1));
      TProgressBar *ImageLoadProgressBar = (TProgressBar *) FindComponent("ImageLoadProgressBar" + IntToStr(camIndex + 1));

      SPBImage->Picture->Bitmap->Width = CaptureWidth;
      SPBImage->Picture->Bitmap->Height = CaptureHeight;
      SPBImage->Picture->Bitmap->PixelFormat = pf24bit;

      try
      {
        if (!Comm_Request(COMM_SPB + stdSPBIndex, CMD_CAPTURE_EXIST, data, sizeof(unsigned int),
          receivedData, sizeof(unsigned int) * 2))
        {
          throw(0);
        }

        if (receivedData[0])
        {
          bCaptureExist = true;
        }
        else
        {
          bCaptureExist = false;
        }
    
        if (bCaptureExist)
        {
          if(ResolutionRadioGroup->ItemIndex)
          {
            if (!Comm_Request(COMM_SPB + stdSPBIndex, CMD_CAPTURE_UPLOAD, data, 2 * sizeof(unsigned int),
            CaptureLargeData, (CaptureWidth) * CaptureHeight))
            {
              throw(0);
            }
          }
          else
          {
            if (!Comm_Request(COMM_SPB + stdSPBIndex, CMD_CAPTURE_UPLOAD, data, 2 * sizeof(unsigned int),
            CaptureData, (CaptureWidth) * CaptureHeight))
            {
              throw(0);
            }
          }


          AnsiString fileName;
          fileName = ProgramPath.Env + "\\WhiteBalanceInfo.ini";
          ReadCameraWhiteBalanceColorInfo(fileName, allCameraIndex);

          if(ResolutionRadioGroup->ItemIndex)
          {
            GetNFACamera2DColorImage(SPBImage->Picture->Bitmap, CaptureLargeData, CaptureWidth, CaptureHeight, allCameraIndex, SystemImageOffsetSWCal[allCameraIndex - 1], SystemOffsetImage[allCameraIndex - 1], ResolutionRadioGroup->ItemIndex);
          }
          else
          {
            GetNFACamera2DColorImage(SPBImage->Picture->Bitmap, CaptureData, CaptureWidth, CaptureHeight, allCameraIndex,SystemImageOffsetSWCal[allCameraIndex - 1], SystemOffsetImage[allCameraIndex - 1], ResolutionRadioGroup->ItemIndex);
          }

          ImageLoadProgressBar->Position++;
          if(ImageLoadProgressBar->Position == ImageLoadProgressBar->Max)
            ImageLoadProgressBar->Position = 0;

          // For SELMA200, 영상 반전 수정 예정
          if (allCameraIndex == SD2_2D_SIDE_FACE_P45_CAMERA_INDEX - 1 ||
              allCameraIndex == SD2_2D_SIDE_FACE_M45_CAMERA_INDEX - 1)
          {
            byte *pTempLine = new byte[SPBImage->Picture->Bitmap->Width * 3];
            for (int y = 0; y < (SPBImage->Picture->Bitmap->Height); y++)
            {
              byte *pBitmap = (byte *)SPBImage->Picture->Bitmap->ScanLine[y];

              for (int x = 0; x < SPBImage->Picture->Bitmap->Width; x++)
              {
                pTempLine[x * 3 + 0] = pBitmap[(SPBImage->Picture->Bitmap->Width - 1 - x) * 3 + 0];
                pTempLine[x * 3 + 1] = pBitmap[(SPBImage->Picture->Bitmap->Width - 1 - x) * 3 + 1];
                pTempLine[x * 3 + 2] = pBitmap[(SPBImage->Picture->Bitmap->Width - 1 - x) * 3 + 2];
              }
              memcpy(pBitmap, pTempLine, SPBImage->Picture->Bitmap->Width * 3);
            }
            delete[] pTempLine;
          }
          else if (allCameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX - 1 ||
                    allCameraIndex == SD2_2D_FRONT_FACE_CAMERA_INDEX - 1 ||
            		    allCameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                 	  allCameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                    allCameraIndex == SD1_2D_SIDE_FACE_P45_CAMERA_INDEX - 1 ||
                    allCameraIndex == SD1_2D_OTHER_SIDE_FACE_P45_CAMERA_INDEX - 1 ||
                    allCameraIndex == SD1_2D_SIDE_FACE_M45_CAMERA_INDEX - 1 ||
                    allCameraIndex == SD1_2D_OTHER_SIDE_FACE_M45_CAMERA_INDEX - 1)
          {
            byte *pTempLineT = new byte[SPBImage->Picture->Bitmap->Width * 3];
            byte *pTempLineB = new byte[SPBImage->Picture->Bitmap->Width * 3];
            for (int y = 0; y < (SPBImage->Picture->Bitmap->Height + 1) / 2; y++)
            {
              byte *pBitmapT = (byte *)SPBImage->Picture->Bitmap->ScanLine[y];
              byte *pBitmapB = (byte *)SPBImage->Picture->Bitmap->ScanLine[SPBImage->Picture->Bitmap->Height - 1 - y];

              memcpy(pTempLineT, pBitmapB, SPBImage->Picture->Bitmap->Width * 3);
              memcpy(pTempLineB, pBitmapT, SPBImage->Picture->Bitmap->Width * 3);
              memcpy(pBitmapT, pTempLineT, SPBImage->Picture->Bitmap->Width * 3);
              memcpy(pBitmapB, pTempLineB, SPBImage->Picture->Bitmap->Width * 3);
            }
            delete[] pTempLineT;
            delete[] pTempLineB;
          }

          SPBImage->Repaint();
        }
      }
      catch (...)
      {
        bTimerEnabled = false;
      }
    }
  }

  SPBImageLoadTimer->Enabled = bTimerEnabled;
}
//---------------------------------------------------------------------------



void __fastcall TCaptureForm::CameraGainEdit1Change(TObject *Sender)
{
  TTntEdit *gainEdit = (TTntEdit *) Sender;
  int globalCameraIndex = gainEdit->Tag;
	try
  {
    int Gain = StrToInt(gainEdit->Text);
    DigitalGainList[globalCameraIndex] = Gain;
  }
  catch(...)
  {

  }

  if(!bLockRefreshOffsetInfo)
  {
    ReadSystemCameraOffsetImage(DigitalGainList);
  }
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::SystemGainSaveBtnClick(TObject *Sender)
{
  SYSTEM_DEFAULT_ANLOG_GAIN = StrToInt(SystemAnalogGainEdit->Text);
  WriteSystem2DCamAnalogGain(ProgramPath.Env + "\\SystemCameraAnalogGain.ini");

  ShowMessage("Complete");  
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::TntFormShow(TObject *Sender)
{
  if(ProductData.SubSamplingMode == 0)
    ResolutionRadioGroup->ItemIndex = 0;
  else
    ResolutionRadioGroup->ItemIndex = 1;

}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::CaptureImageDblClick(TObject *Sender)
{
  if(ResolutionRadioGroup->ItemIndex)
  {
    if(GlobalCameraIndex != 4 && GlobalCameraIndex != 12) // 3D Camera
    {
      TRealSizeImageForm *RealSizeImageForm = new  TRealSizeImageForm(this);
      TTntImage *Image = (TTntImage*)Sender;
      RealSizeImageForm->SetImage(Image);
      RealSizeImageForm->ShowModal();
      delete RealSizeImageForm;
    }
  }
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::FOVEditClick(TObject *Sender)
{
    TTntEdit *theEdit = (TTntEdit *) Sender;
  KeyboardForm->Text = theEdit->Text;
  if (KeyboardForm->ShowKeypad() == mrOk)
    theEdit->Text = KeyboardForm->Text;  
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::CaptureImageMouseDown(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
  if (ShowFovGridLineSpeedButton->Down)
  {
    if(X < SYSTEM_CAMERA_WIDTH / 2)
    {
      measureStartPos = X;
    }
    else
    {
      measureEndPos = X;
    }
  }
}
//---------------------------------------------------------------------------


void __fastcall TCaptureForm::ImageLoadRadioBtnClick(TObject *Sender)
{
  if(ImageLoadRadioBtn->ItemIndex == 0)
  {
    ImagePanel->Visible = true;
    SPBImagePanel->Visible = false;
    LaserTestImagePanel->Visible = false;

    GroupBox5->Visible = true;
  }
  else
  {
    ImagePanel->Visible = false;
    SPBImagePanel->Visible = true;
    LaserTestImagePanel->Visible = false;

    GroupBox5->Visible = false;
  }
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::ResolutionRadioGroupClick(TObject *Sender)
{
  for(int i = 0; i < 16; ++i)       //++
  {
    try
    {
      int spbIndex = CameraMapInfo[i].SPBIndex;
      if (Comm_IsConnected(COMM_SPB + spbIndex))
      {
        if(CameraMapInfo[i].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[i] != 0)
        {
          RefreshCameraInfo(i);
        }
      }
    }
    catch(...)
    {
      break;
    }
  }

  TCaptureCommandParam_HCB captureCommandParam_HCB;
  captureCommandParam_HCB.Action = 0;

  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
    int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
    Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));
  }
  
  if (Comm_Request(COMM_HCB, CMD_TABLET_CAPTURE, &captureCommandParam_HCB, sizeof(TCaptureCommandParam_HCB),
    NULL, 0))
  {
    SubCaptureFrame->CaptureStop();

    bOnCapture = false;
    HCBCaptureButton->Caption = "Capture Start";
  }

  SPBImageLoadTimer->Enabled = false;

  if(ResolutionRadioGroup->ItemIndex == 0)
  {
    CAM_Width = SYSTEM_CAMERA_WIDTH;
    CAM_Height = SYSTEM_CAMERA_HEIGHT;

    CaptureImage->Picture->Bitmap->Width = CAM_Width;
    CaptureImage->Picture->Bitmap->Height = CAM_Height;
    CaptureImage->Picture->Bitmap->PixelFormat = pf24bit;
    for(int i = 0; i < SYSTEM_TOTAL_CAMERA_COUNT ; ++i)
    {
        SubsamplingModeList[i] = RESOLUTION_NORMAL_QUALITY;
    }
  }
  else
  {
    CAM_Width = SYSTEM_CAMERA_HD_WIDTH;
    CAM_Height = SYSTEM_CAMERA_HD_HEIGHT;

    CaptureImage->Picture->Bitmap->Width = CAM_Width;
    CaptureImage->Picture->Bitmap->Height = CAM_Height;
    CaptureImage->Picture->Bitmap->PixelFormat = pf24bit;
    for(int i = 0; i < SYSTEM_TOTAL_CAMERA_COUNT ; ++i)
    {
      if(CameraMapInfo[i].CameraInspectPosition == CAMERA_POSITION_3D)
        SubsamplingModeList[i] = RESOLUTION_NORMAL_QUALITY;
      else
        SubsamplingModeList[i] = RESOLUTION_HIGH_QUALITY;
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::SetApplyThreeDParams(int cameraIndex)
{
  int AnalogGain;
  int ExposureTime;

  int ThreedCameraIndex = 0;
  if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
  {
    ThreedCameraIndex = 0;
  }
  else
  {
    ThreedCameraIndex = 1;
  }

  if(!ProductData.ProductName.IsEmpty())
  {
    if(ProductData.ExposureTime3D[ThreedCameraIndex] != -1)
    {
      AnalogGain = ProductData.AnalogGain3D[ThreedCameraIndex];
      ExposureTime = ProductData.ExposureTime3D[ThreedCameraIndex];
    }
    else
    {
      AnalogGain = ThreeDCameraDefaultInformation[cameraIndex].AnalogCameraGain;
      ExposureTime = ThreeDCameraDefaultInformation[cameraIndex].ExposureTime;
    }
  }
  else
  {
    AnalogGain = ThreeDCameraDefaultInformation[cameraIndex].AnalogCameraGain;
    ExposureTime = ThreeDCameraDefaultInformation[cameraIndex].ExposureTime;
  }

  ThreeDCameraGainEdit->Text = IntToStr(AnalogGain);
  ThreeDExposureTimeEdit->Text = IntToStr(ExposureTime);

  ThreeDOption1CheckBox->Checked = false;
  ThreeDOption2CheckBox->Checked = false;

  ThreeDCameraGainEdit->Enabled = false;
  ThreeDExposureTimeEdit->Enabled = false;

  SubCaptureFrame->threeDOption = 0;
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::ThreeDOption1CheckBoxClick(TObject *Sender)
{
  if(ThreeDOption1CheckBox->Checked)
  {
    ThreeDCameraGainEdit->Enabled = true;
    ThreeDExposureTimeEdit->Enabled = true;
  }
  else
  {
    ThreeDCameraGainEdit->Enabled = false;
    ThreeDExposureTimeEdit->Enabled = false;
  }
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::TriggerFreqEditClick(TObject *Sender)
{
  TTntEdit *theEdit = (TTntEdit *) Sender;
	KeyboardForm->Text = theEdit->Text;
  if (KeyboardForm->ShowKeypad() == mrOk)
  {
		theEdit->Text = KeyboardForm->Text;
	}  
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::ThreeDExposureTimeEditClick(TObject *Sender)
{
  TTntEdit *theEdit = (TTntEdit *) Sender;
	KeyboardForm->Text = theEdit->Text;
  if (KeyboardForm->ShowKeypad() == mrOk)
  {
		theEdit->Text = KeyboardForm->Text;
	}  
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::ThreeDCameraGainEditClick(TObject *Sender)
{
  TTntEdit *theEdit = (TTntEdit *) Sender;
	KeyboardForm->Text = theEdit->Text;
  if (KeyboardForm->ShowKeypad() == mrOk)
  {
		theEdit->Text = KeyboardForm->Text;
	}  
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::ThreeDOption2CheckBoxClick(TObject *Sender)
{
  if(ThreeDOption2CheckBox->Checked)
  {
    SubCaptureFrame->threeDOption = 1;
  }
  else
  {
    SubCaptureFrame->threeDOption = 0;
  }
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::AutoThreeDImageStudyBtnClick(TObject *Sender)
{
  TThreeDLineScanFrequencyStudyForm *pThreeDLineScanFrequencyStudyForm = new TThreeDLineScanFrequencyStudyForm(this);
  pThreeDLineScanFrequencyStudyForm->ShowModal();
  delete pThreeDLineScanFrequencyStudyForm;

  memset(GlobalSD1LSFTable, 0, sizeof(int) * MAX_MOTOR_SPEED);
  memset(GlobalSD2LSFTable, 0, sizeof(int) * MAX_MOTOR_SPEED);
  
  AnsiString fileName = ProgramPath.Env + "\\LSFStudyResultTable.lsf";
  ReadGlobalLSFTable(fileName);
}
//---------------------------------------------------------------------------


void __fastcall TCaptureForm::LaserTestCaptureStartButtonClick(
      TObject *Sender)
{
  if (ProductData.ProductCode.IsEmpty())
	{
		ShowMessageFA(ADVMACHINECONTROLFORM_MSG_01);
		return;
	}

  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
	  int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
	  int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
	  Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));
  }
  
  LaserCaptureSW = true;
  
  Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP);
  SubCaptureFrame->CaptureStop();
  SPBImageLoadTimer->Enabled = false;

  ImageLoadRadioBtn->ItemIndex = 0;

  unsigned int camMask = 0;
  for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    if(globalCameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX - 1 || globalCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
    {
      if(CameraMapInfo[globalCameraIndex].CameraInspectPosition != CAMERA_POSITION_DISCONNECT)
      {
        camMask |= (0x0001 << globalCameraIndex);
        RefreshCameraInfo(globalCameraIndex);
      }
    }
  }

	float tabletHalfLength = StrToFloat(TabletLengthEdit->Text) / 2;
	int triggerFreq_3D = StrToInt(TriggerFreqEdit->Text);

	if (SendSPBCaptureSetup_Multi(&ProductData, camMask, tabletHalfLength, ShutterSpeedList,
		    MachineOperationInfo.ServoMotorSpeed[SD1_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed,
        MachineOperationInfo.ServoMotorSpeed[SD2_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed,
        0, true, 3, triggerFreq_3D))
	{
    LaserTestImagePanel->Visible = true;

    LaserTestProgressBarCamera1->Position = 0;
    LaserTestProgressBarCamera5->Position = 0;

    LaserTestTimer->Enabled = true;
	}

	TMachineCaptureSetupData machineCaptureSetupData;

	memcpy(machineCaptureSetupData.IlluminatorMask, MachineSetupData.MachineCaptureInfo.IlluminatorMask, SYSTEM_MACHINE_CAPTURE_COUNT * sizeof(int));
	machineCaptureSetupData.TabletLength = ProductData.TabletLength;
	machineCaptureSetupData.TabletSideThick = ProductData.TabletSideThick*10;
	machineCaptureSetupData.SuctionDiskSpeed = MachineOperationInfo.ServoMotorSpeed[SD1_MOTOR_INDEX];
	machineCaptureSetupData.StudiedTabletSensorLength = ProductData.StudiedSensor1Length;
  machineCaptureSetupData.CaptureOption = 0;

	Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE, &machineCaptureSetupData, sizeof(TMachineCaptureSetupData), NULL, 0);

  LaserCaptureSW = false;
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::LaserTestCaptureStopButtonClick(
      TObject *Sender)
{
  LaserTestTimer->Enabled = false;
  Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP);
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::LaserTestTimerTimer(TObject *Sender)
{
  bool bTimerEnabled;
  
  bTimerEnabled = LaserTestTimer->Enabled;

  bool bCaptureExist;

	char cameraIndex;
	unsigned int data[2];
	unsigned int receivedData[2];
  unsigned char CaptureData[SYSTEM_CAMERA_WIDTH * SYSTEM_CAMERA_HEIGHT];
  unsigned char CaptureLargeData[SYSTEM_CAMERA_HD_WIDTH * SYSTEM_CAMERA_HD_HEIGHT];

  int CaptureWidth, CaptureHeight;

  CaptureWidth = SYSTEM_CAMERA_WIDTH;
  CaptureHeight = SYSTEM_CAMERA_HEIGHT;

  for(int allCameraIndex = 0; allCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; allCameraIndex++)
  {
    if(allCameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX - 1 || allCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
    {
      if (CameraMapInfo[allCameraIndex].CameraInspectPosition == CAMERA_POSITION_DISCONNECT) continue;

      int camIndex = CameraMapInfo[allCameraIndex].CamIndex;
      int spbIndex = CameraMapInfo[allCameraIndex].SPBIndex;

      data[0] = camIndex;
      data[1] = CaptureWidth * CaptureHeight;

      TImage *LaserTestImage = (TImage *) FindComponent("LaserTestImageCamera" + IntToStr(allCameraIndex + 1));
      TProgressBar *LaserTestProgressBar = (TProgressBar *) FindComponent("LaserTestProgressBarCamera" + IntToStr(allCameraIndex + 1));
      TLabel *LaserTestProgressLabel = (TLabel *) FindComponent("LaserTestProgressLabelCamera" + IntToStr(allCameraIndex + 1));

      try
      {
        if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_EXIST, data, sizeof(unsigned int),
          receivedData, sizeof(unsigned int) * 2))
        {
          throw(0);
        }
    
        if (receivedData[0])
        {
          bCaptureExist = true;
        }
        else
        {
          bCaptureExist = false;
        }
    
        if (bCaptureExist)
        {
          if(ResolutionRadioGroup->ItemIndex)
          {
            if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_UPLOAD, data, 2 * sizeof(unsigned int),
            CaptureLargeData, (CaptureWidth) * CaptureHeight))
            {
              throw(0);
            }
          }
          else
          {
            if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_UPLOAD, data, 2 * sizeof(unsigned int),
            CaptureData, (CaptureWidth) * CaptureHeight))
            {
              throw(0);
            }
          }

          if(allCameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX - 1)
          {
            LaserTestImage->Picture->Bitmap->Width = CaptureWidth;
            LaserTestImage->Picture->Bitmap->Height = CaptureHeight;
            LaserTestImage->Picture->Bitmap->PixelFormat = pf24bit;
      
            AnsiString fileName;
            fileName = ProgramPath.Env + "\\WhiteBalanceInfo.ini";
            ReadCameraWhiteBalanceColorInfo(fileName, allCameraIndex);

             if(ResolutionRadioGroup->ItemIndex)
            {
              GetNFACamera2DColorImage(LaserTestImage->Picture->Bitmap, CaptureLargeData, CaptureWidth, CaptureHeight, allCameraIndex, SystemImageOffsetSWCal[allCameraIndex - 1], SystemOffsetImage[allCameraIndex - 1], ResolutionRadioGroup->ItemIndex);
            }
            else
            {
              GetNFACamera2DColorImage(LaserTestImage->Picture->Bitmap, CaptureData, CaptureWidth, CaptureHeight, allCameraIndex,SystemImageOffsetSWCal[allCameraIndex - 1], SystemOffsetImage[allCameraIndex - 1], ResolutionRadioGroup->ItemIndex);
            }

            // 상하좌우
            byte *pTempLineT = new byte[CaptureWidth * 3];
            byte *pTempLineB = new byte[CaptureWidth * 3];
            for (int y = 0; y < (CaptureHeight + 1) / 2; y++)
            {
              byte *pBitmapT = (byte *)LaserTestImage->Picture->Bitmap->ScanLine[y];
              byte *pBitmapB = (byte *)LaserTestImage->Picture->Bitmap->ScanLine[CaptureHeight - 1 - y];

              for (int x = 0; x < CaptureWidth; x++)
              {
                pTempLineT[x * 3 + 0] = pBitmapB[x * 3 + 0];
                pTempLineB[x * 3 + 0] = pBitmapT[x * 3 + 0];
                pTempLineT[x * 3 + 1] = pBitmapB[x * 3 + 1];
                pTempLineB[x * 3 + 1] = pBitmapT[x * 3 + 1];
                pTempLineT[x * 3 + 2] = pBitmapB[x * 3 + 2];
                pTempLineB[x * 3 + 2] = pBitmapT[x * 3 + 2];
              }
              memcpy(pBitmapT, pTempLineT, CaptureWidth * 3);
              memcpy(pBitmapB, pTempLineB, CaptureWidth * 3);
            }
            delete[] pTempLineT;
            delete[] pTempLineB;
          }
          else
          {
            LaserTestImage->Picture->Bitmap->Width = IMAGE_WIDTH_3D * 2;
            LaserTestImage->Picture->Bitmap->Height = IMAGE_HEIGHT_3D;
            LaserTestImage->Picture->Bitmap->PixelFormat = pf24bit;

            Graphics::TBitmap *tempBitmap = new Graphics::TBitmap;
            tempBitmap->Width = IMAGE_WIDTH_3D;
            tempBitmap->Height = IMAGE_HEIGHT_3D;
            tempBitmap->PixelFormat = pf8bit;

            ImageConversion_3D(tempBitmap, IMAGE_WIDTH_3D, IMAGE_HEIGHT_3D, CaptureData, SYSTEM_CAMERA_WIDTH_3D, SYSTEM_CAMERA_HEIGHT_3D);

            for (int y = 1; y < IMAGE_HEIGHT_3D - 1; y++)
            {
              byte *pBitmap = (byte *)LaserTestImage->Picture->Bitmap->ScanLine[y];
              byte *pSrc = (byte *)tempBitmap->ScanLine[y];

              for (int x = IMAGE_WIDTH_3D * 2 - 1; x >= 0; x--)
              {
                pBitmap[3 * x + 0] = pSrc[x / 2];
                pBitmap[3 * x + 1] = pSrc[x / 2];
                pBitmap[3 * x + 2] = pSrc[x / 2];
              }
            }

            // 상하좌우
            byte *pTempLineT = new byte[CaptureWidth * 3];
            byte *pTempLineB = new byte[CaptureWidth * 3];
            for (int y = 0; y < (CaptureHeight + 1) / 2; y++)
            {
              byte *pBitmapT = (byte *)LaserTestImage->Picture->Bitmap->ScanLine[y];
              byte *pBitmapB = (byte *)LaserTestImage->Picture->Bitmap->ScanLine[CaptureHeight - 1 - y];

              for (int x = 0; x < CaptureWidth; x++)
              {
                pTempLineT[x * 3 + 0] = pBitmapB[x * 3 + 0];
                pTempLineB[x * 3 + 0] = pBitmapT[x * 3 + 0];
                pTempLineT[x * 3 + 1] = pBitmapB[x * 3 + 1];
                pTempLineB[x * 3 + 1] = pBitmapT[x * 3 + 1];
                pTempLineT[x * 3 + 2] = pBitmapB[x * 3 + 2];
                pTempLineB[x * 3 + 2] = pBitmapT[x * 3 + 2];
              }
              memcpy(pBitmapT, pTempLineT, CaptureWidth * 3);
              memcpy(pBitmapB, pTempLineB, CaptureWidth * 3);
            }
            delete[] pTempLineT;
            delete[] pTempLineB;

            delete tempBitmap;
          }

          LaserTestImage->Canvas->Pen->Color = clDkGray;
          LaserTestImage->Canvas->Pen->Width = 2;
          LaserTestImage->Canvas->Brush->Style = bsClear;

          int centerX, centerY;
          centerX = SYSTEM_CAMERA_WIDTH / 2;
          centerY = SYSTEM_CAMERA_HEIGHT / 2;

          LaserTestImage->Canvas->MoveTo(0,                   centerY);
          LaserTestImage->Canvas->LineTo(SYSTEM_CAMERA_WIDTH, centerY);
          LaserTestImage->Canvas->MoveTo(centerX, 0);
          LaserTestImage->Canvas->LineTo(centerX, SYSTEM_CAMERA_HEIGHT);

          LaserTestProgressBar->Position++;
          if(LaserTestProgressBar->Position == LaserTestProgressBar->Max)
            LaserTestProgressBar->Position = 0;

          LaserTestProgressLabel->Caption = IntToStr(LaserTestProgressBar->Position);

          LaserTestImage->Repaint();
        }
      }
      catch (...)
      {
        bTimerEnabled = false;
      }
    }
  }

  LaserTestTimer->Enabled = bTimerEnabled;
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::MachineStatusCheckTimerTimer(TObject *Sender)
{
  if(1)//Machine.Status.OperationState == MACHINE_STATE_RUN)
  {
    Disk1RPMLabel->Caption = IntToStr((int)(MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed * SUCTION_DISK_100P_RPM / AdvMachineControlForm->MachineControlParams.ServoMotorSpeed[SD1_MOTOR_INDEX])) + " rpm (" +
                              IntToStr(MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed * 100 / AdvMachineControlForm->MachineControlParams.ServoMotorSpeed[SD1_MOTOR_INDEX]) + "%)";

    Disk2RPMLabel->Caption = IntToStr((int)(MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed * SUCTION_DISK_100P_RPM / AdvMachineControlForm->MachineControlParams.ServoMotorSpeed[SD2_MOTOR_INDEX])) + " rpm (" +
                              IntToStr(MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed * 100 / AdvMachineControlForm->MachineControlParams.ServoMotorSpeed[SD2_MOTOR_INDEX]) + "%)";
  }
  else
  {
    Disk1RPMLabel->Caption = "N/A";
    Disk2RPMLabel->Caption = "N/A";
  }
}
//---------------------------------------------------------------------------


void __fastcall TCaptureForm::EnabledDisk1SensorBtnClick(TObject *Sender)
{ 
  bool bError;

  int SD1ThreeDCameraSPBIndex;
  SD1ThreeDCameraSPBIndex = CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].SPBIndex;

  Disk1ThreeDSensorErrorCode = THREED_SENSOR_ERROR_CODE_GOOD;

  bError = false;

  if (!Comm_IsConnected(COMM_SPB + SD1ThreeDCameraSPBIndex))
  {
    bError = false;
    Disk1ThreeDSensorErrorCode = THREED_SENSOR_ERROR_CODE_BRD_DISCONNECTED;
  }
  else if (CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition != CAMERA_POSITION_3D)
  {
    bError = true;
    Disk1ThreeDSensorErrorCode = THREED_SENSOR_ERROR_CODE_INVALID_MAPPING;
  }
  else if (CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] == 0)
  {
    bError = true;
    Disk1ThreeDSensorErrorCode = THREED_SENSOR_ERROR_CODE_CAMERA_DISCONNECTED;
  }

  if(!bError)
  {
    Set3DCamera_CaptureParameter(SD1_3D_FRONT_FACE_CAMERA_INDEX - 1,ThreeDCameraDefaultInformation[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].AnalogCameraGain, ThreeDCameraDefaultInformation[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].ExposureTime);
    EnabledThreeDLaserSensor(SD1_3D_FRONT_FACE_CAMERA_INDEX - 1, RANGER_3D_BASE_SHUTTER_SPEED, THREED_SENSOR_NONE_MODE);
    ThreeDSensorActiveStatus = THREED_SENSOR_ON;
  }
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::EnabledDisk2SensorBtnClick(TObject *Sender)
{
  bool bError;

  int SD2ThreeDCameraSPBIndex;
  SD2ThreeDCameraSPBIndex = CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].SPBIndex;

  Disk2ThreeDSensorErrorCode = THREED_SENSOR_ERROR_CODE_GOOD;

  bError = false;

  if (!Comm_IsConnected(COMM_SPB + SD2ThreeDCameraSPBIndex))
  {
    bError = false;
    Disk2ThreeDSensorErrorCode = THREED_SENSOR_ERROR_CODE_BRD_DISCONNECTED;
  }
  else if (CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition != CAMERA_POSITION_3D)
  {
    bError = true;
    Disk2ThreeDSensorErrorCode = THREED_SENSOR_ERROR_CODE_INVALID_MAPPING;
  }
  else if (CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] == 0)
  {
    bError = true;
    Disk2ThreeDSensorErrorCode = THREED_SENSOR_ERROR_CODE_CAMERA_DISCONNECTED;
  }

  if(!bError)
  {
    Set3DCamera_CaptureParameter(SD2_3D_FRONT_FACE_CAMERA_INDEX - 1,ThreeDCameraDefaultInformation[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].AnalogCameraGain, ThreeDCameraDefaultInformation[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].ExposureTime);
    EnabledThreeDLaserSensor(SD2_3D_FRONT_FACE_CAMERA_INDEX - 1, RANGER_3D_BASE_SHUTTER_SPEED2, THREED_SENSOR_NONE_MODE);
    ThreeDSensorActiveStatus = THREED_SENSOR_ON;
  }
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::TntButton1Click(TObject *Sender)
{
  ThreeDSensorStatusCheckForm->Show();  
}
//---------------------------------------------------------------------------


void __fastcall TCaptureForm::TwoDCalibrationGuideButtonClick(
      TObject *Sender)
{
  TTwoDCalibrationGuideForm *TwoDCalibrationGuideForm = new TTwoDCalibrationGuideForm(this);
  TwoDCalibrationGuideForm->ShowModal();
  delete TwoDCalibrationGuideForm;
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::Image5Click(TObject *Sender)
{
  if(TwoDCalibrationGuideButton->Visible == false)
  {
    TwoDCalibrationGuideButton->Visible = true;
  }
  else
  {
    TwoDCalibrationGuideButton->Visible = false;
  }
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::ImageConversionBtnClick(TObject *Sender)
{
  if(CaptureImage->Picture->Bitmap->Width != SYSTEM_CAMERA_HD_WIDTH) return;

  ScaleSumGroupBox->Visible = true;
  ScaleSumGroupBox->BringToFront();

  ImageConversion();
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::Button1Click(TObject *Sender)
{
  ScaleSumGroupBox->Visible = false;
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::ImageConversion()
{
  int x, y;
  int tempAddress;
  int width;
  int height;

  width = CaptureImage->Picture->Bitmap->Width;
  height = CaptureImage->Picture->Bitmap->Height;
  
  memset(ColorImage, 0, SYSTEM_CAMERA_HD_WIDTH * SYSTEM_CAMERA_HD_HEIGHT * 3);

  Byte *ptr, *ptr2, *ptr3;
  for(y = 0; y < height; y++)
  {
    ptr = (Byte *)CaptureImage->Picture->Bitmap->ScanLine[y];
    for(x = 0; x < width; x++)
    {
      tempAddress = width * y + x;
      ColorImage[tempAddress * 3 + 0] = ptr[x * 3 + 0];
      ColorImage[tempAddress * 3 + 1] = ptr[x * 3 + 1];
      ColorImage[tempAddress * 3 + 2] = ptr[x * 3 + 2];
    }
  }

  Graphics::TBitmap *img = new Graphics::TBitmap;
  img->Width = width / 2;
  img->Height = height / 2;
  img->PixelFormat = pf24bit;

  int tempB, tempG, tempR;

  for(y = 0; y < height; y+=2)
  {
    ptr = (Byte *)img->ScanLine[y / 2];
    for(x = 0; x < width; x+=2)
    {
      tempAddress = width * y + x;

      tempB = ColorImage[tempAddress * 3 + 0] + ColorImage[(tempAddress + 1) * 3 + 0] + ColorImage[(tempAddress + width) * 3 + 0] + ColorImage[(tempAddress + 1 + width) * 3 + 0];
      tempG = ColorImage[tempAddress * 3 + 1] + ColorImage[(tempAddress + 1) * 3 + 1] + ColorImage[(tempAddress + width) * 3 + 1] + ColorImage[(tempAddress + 1 + width) * 3 + 1];
      tempR = ColorImage[tempAddress * 3 + 2] + ColorImage[(tempAddress + 1) * 3 + 2] + ColorImage[(tempAddress + width) * 3 + 2] + ColorImage[(tempAddress + 1 + width) * 3 + 2];

      ptr[(x / 2) * 3 + 0] = min(255, tempB);
      ptr[(x / 2) * 3 + 1] = min(255, tempG);
      ptr[(x / 2) * 3 + 2] = min(255, tempR);
    }
  }

  AImage1->Picture->Bitmap->Assign(img);
  AImage1->Refresh();
  
  for(y = 0; y < height; y+=2)
  {
    ptr = (Byte *)img->ScanLine[y / 2];
    for(x = 0; x < width; x+=2)
    {
      tempAddress = width * y + x;

      tempB = ColorImage[tempAddress * 3 + 0] * 4;
      tempG = ColorImage[tempAddress * 3 + 1] * 4;
      tempR = ColorImage[tempAddress * 3 + 2] * 4;

      ptr[(x / 2) * 3 + 0] = min(255, tempB);
      ptr[(x / 2) * 3 + 1] = min(255, tempG);
      ptr[(x / 2) * 3 + 2] = min(255, tempR);
    }
  }

  AImage2->Picture->Bitmap->Assign(img);
  AImage2->Refresh();

  int normalized = TrackBar1->Position;
  int colorDiff[3];
  for(y = 0; y < height; y+=2)
  {
    ptr = (Byte *)img->ScanLine[y / 2];
    ptr2 = (Byte *)AImage1->Picture->Bitmap->ScanLine[y / 2];
    ptr3 = (Byte *)AImage2->Picture->Bitmap->ScanLine[y / 2];
    for(x = 0; x < width; x+=2)
    {
      ptr[(x / 2) * 3 + 0] = 0;
      ptr[(x / 2) * 3 + 1] = 0;
      ptr[(x / 2) * 3 + 2] = 0;

      colorDiff[0] = abs(ptr2[(x / 2) * 3 + 0] - ptr3[(x / 2) * 3 + 0]);
      colorDiff[1] = abs(ptr2[(x / 2) * 3 + 1] - ptr3[(x / 2) * 3 + 1]);
      colorDiff[2] = abs(ptr2[(x / 2) * 3 + 2] - ptr3[(x / 2) * 3 + 2]);

      if(!CheckBox1->Checked)
      {
        if(colorDiff[0] > normalized)
        {
          ptr[(x / 2) * 3 + 0] = min(255, colorDiff[0] * 255 / normalized);
        }

        if(colorDiff[1] > normalized)
        {
          ptr[(x / 2) * 3 + 1] = min(255, colorDiff[1] * 255 / normalized);
        }

        if(colorDiff[2] > normalized)
        {
          ptr[(x / 2) * 3 + 2] = min(255, colorDiff[2] * 255 / normalized);
        }
      }
      else
      {
        if(colorDiff[0] > 0)
        {
          ptr[(x / 2) * 3 + 0] = 255;
        }

        if(colorDiff[1] > 0)
        {
          ptr[(x / 2) * 3 + 1] = 255;
        }

        if(colorDiff[2] > 0)
        {
          ptr[(x / 2) * 3 + 2] = 255;
        }
      }
    }
  }

  AImage3->Picture->Bitmap->Assign(img);
  AImage3->Refresh();

  delete img;
}
//---------------------------------------------------------------------------
void __fastcall TCaptureForm::TrackBar1Change(TObject *Sender)
{
  Edit2->Text = IntToStr(TrackBar1->Position);
  ImageConversion();
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::CheckBox1Click(TObject *Sender)
{
  ImageConversion();
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::TntButton2Click(TObject *Sender)
{
  TOffSetImageExtractForm *OffSetImageExtractForm = new TOffSetImageExtractForm(this);
  OffSetImageExtractForm->ShowModal();
  delete OffSetImageExtractForm;

  ReadSystemCameraOffsetImage(DigitalGainList);
}
/*
void __fastcall TCaptureForm::Button2Click(TObject *Sender)
{

}
*/
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::sLaseronBtnClick(TObject *Sender)
{
	AnsiString filepath = "D:\\Project\\sLaser\\sLaser.exe";
	AnsiString PgmName = "NFA sLaser";
	if(IsExistProcess("sLaser.exe"))
	{
		HWND hWnd = FindWindowA(NULL, PgmName.c_str());
		if(sLaseronBtn->Caption.AnsiCompare("SLaser ON") == 0)
		{
			ShowWindowAsync(hWnd, SW_SHOWNORMAL);
			SetActiveWindow (hWnd);
			SetForegroundWindow(hWnd);
			sLaseronBtn->Caption = "SLaser OFF";
		}
		else
		{
			ShowWindow (hWnd, SW_HIDE);
			sLaseronBtn->Caption = "SLaser ON";
		}
	}
	else
	{
		if(sLaseronBtn->Caption.AnsiCompare("SLaser ON") == 0)
		{
			ShellExecuteA(NULL, "open", filepath.c_str(), NULL, "D:\\Project\\sLaser", SW_SHOW);
			sLaseronBtn->Caption = "SLaser OFF";
		}
		else
		{
			sLaseronBtn->Caption = "SLaser ON";
		}
	}
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::TntFormActivate(TObject *Sender)
{
  SetScreenPosition(this);  
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::TPBCameraSettingButtonClick(TObject *Sender)
{
  TPBCameraSettingForm->ShowModal();
}
//---------------------------------------------------------------------------



void __fastcall TCaptureForm::LaserPositionCalBtnClick(TObject *Sender)
{
    if(LaserPosCalPanel->Visible)
    {
    	LaserPosCalPanel->Visible = false;
    }
    else
    {
    	LaserPosCalPanel->Visible = true;
	if (!ReadSPBSystemSetupData(ProgramPath.Env + "\\SystemInfor.ini", SPBSystemSetupData, CameraMapInfo))
	{
		ShowMessageW("Read Error [SPB Setup Data]");
	}
	EditCalXX->Caption =FloatToStr(SPBSystemSetupData[6].LaserPositionCalData[0]);
	EditCalXY->Caption =FloatToStr(SPBSystemSetupData[6].LaserPositionCalData[1]);
	EditCalYX->Caption =FloatToStr(SPBSystemSetupData[6].LaserPositionCalData[2]);
	EditCalYY->Caption =FloatToStr(SPBSystemSetupData[6].LaserPositionCalData[3]);
    
    }
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::PositionSaveBtnClick(TObject *Sender)
{
	float inputX = 0, inputY = 0;
	float outputXX = 0, outputXY = 0;
	float outputYX = 0, outputYY = 0;
	int TempXX = 0, TempXY = 0;
	int TempYX = 0, TempYY = 0;
	float XCalx = 0, XCaly = 0;
	float YCalx = 0, YCaly = 0;

	if(!(EditInputX->Text))
	{
		inputX  = 0;
		EditInputX->Text = "0";
	}
	else
	{
		inputX = StrToInt(EditInputX->Text);
	}

	if(!(EditInputY->Text))
	{
		inputY  = 0;
		EditInputY->Text ="0";
	}
	else
	{
		inputY = StrToInt(EditInputY->Text);
	}
	
	if(!(EditXoutputX->Text))
	{
		outputXX  = 0;
		EditXoutputX->Text = "0";
	}
	else
	{
		outputXX = StrToInt(EditXoutputX->Text);
	}	

	if(!(EditXoutputY->Text))
	{
		outputXY  = 0;
		EditXoutputY->Text = "0";
	}
	else
	{
		outputXY = StrToInt(EditXoutputY->Text);
	}
	
	if(!(EditYoutputX->Text))
	{
		outputYX  = 0;
		EditYoutputX->Text = "0";
	}
	else
	{
		outputYX = StrToInt(EditYoutputX->Text);
	}
	
	if(!(EditYoutputY->Text))
	{
		outputYY  = 0;
		EditYoutputY->Text = "0";
	}
	else
	{
		outputYY = StrToInt(EditYoutputY->Text);
	}	

	inputX = StrToInt(EditInputX->Text);
	inputY = StrToInt(EditInputY->Text);
	outputXX = StrToInt(EditXoutputX->Text);
	outputXY = StrToInt(EditXoutputY->Text);
	outputYX = StrToInt(EditYoutputX->Text);
	outputYY = StrToInt(EditYoutputY->Text);

	if(inputX ==0 && inputY==0)
	{
		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
			SPBSystemSetupData[spbIndex].LaserPositionCalData[0] = 1;
			SPBSystemSetupData[spbIndex].LaserPositionCalData[1] = 0;
			SPBSystemSetupData[spbIndex].LaserPositionCalData[2] = 0;
			SPBSystemSetupData[spbIndex].LaserPositionCalData[3] = 1;   	
		}
	}
	else
	{
		if(inputX !=0)
		{
			if(outputXX !=0) 
			{
				TempXX = (inputX / outputXX) * inputX;
				XCalx = inputX / outputXX;
			}
			else
			{
				TempXX = 0;
				XCalx = 1;
				ShowMessageFA("ERROR : 장비의 레이저 관련 부품 연결 상태를 확인하세요");
			}

			if(outputXY!=0)
			{
				TempXY = - outputXY/inputX * inputX;
				XCaly = outputXY/inputX;
			}
			else
			{
				TempXY = 0;
				XCaly = 0;				
			}
		}
		else
		{
			XCalx = 1;
			XCaly = 0;
		}


		if(inputY !=0)
		{
			if(outputYX !=0)
			{
				TempYX = - (outputYX / inputY) * inputY;
				YCalx = (outputYX / inputY);
			}
			else
			{
				TempYX = 0;
				YCalx = 0;
			}

			if(outputYY!=0)
			{
				TempYY = inputY/outputYY * inputY;
				YCaly = inputY/outputYY;
			}
			else
			{
				TempYY = 0;
				YCaly = 1;
				ShowMessageFA("ERROR : 장비의 레이저 관련 부품 연결 상태를 확인하세요");			
			}
		}
		else
		{
			YCalx = 0;
			YCaly = 1;
		}

		EditCalXX->Caption = FloatToStr(XCalx);
		EditCalXY->Caption = FloatToStr(XCaly);
		EditCalYX->Caption = FloatToStr(YCalx);
		EditCalYY->Caption = FloatToStr(YCaly);	

		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
			SPBSystemSetupData[spbIndex].LaserPositionCalData[0] = XCalx;
			SPBSystemSetupData[spbIndex].LaserPositionCalData[1] = XCaly;
			SPBSystemSetupData[spbIndex].LaserPositionCalData[2] = YCalx;
			SPBSystemSetupData[spbIndex].LaserPositionCalData[3] = YCaly;
		}
	}	
	WriteSPBSystemSetupData(ProgramPath.Env + "\\SystemInfor.ini", SPBSystemSetupData);
	SendSystemSetupData();
}
//---------------------------------------------------------------------------


void __fastcall TCaptureForm::EditInputXChange(TObject *Sender)
{
	float inputX = 0;

	if(!(EditInputX->Text))
	{
		inputX  = 0;
		EditInputX->Text = "0";
	}
	else
	{
		inputX = StrToInt(EditInputX->Text);
	}
	
	if(inputX!= 0)
	{
		EditXoutputX->Enabled = true;
		EditXoutputY->Enabled = true;
	}
	else
	{
		EditXoutputX->Enabled = false;
		EditXoutputY->Enabled = false;
		EditXoutputX->Text = "0";
		EditXoutputY->Text = "0";	
	}
}
//---------------------------------------------------------------------------


void __fastcall TCaptureForm::EditInputYChange(TObject *Sender)
{
    float inputY = 0;

	if(!(EditInputY->Text))
	{
		inputY  = 0;
		EditInputY->Text = "0";
	}
	else
	{
		inputY = StrToInt(EditInputY->Text);
	}
	
	if(inputY!= 0) 
	{
		EditYoutputX->Enabled = true;
		EditYoutputY->Enabled = true;
	}
	else
	{
		EditYoutputX->Enabled = false;
		EditYoutputY->Enabled = false;
		EditYoutputX->Text = "0";
		EditYoutputY->Text = "0";
	}    
}
//---------------------------------------------------------------------------

void __fastcall TCaptureForm::Button2Click(TObject *Sender)
{
	AnsiString filepath = "D:\\Project\\sLaser\\sLaser.exe";
	AnsiString PgmName = "NFA sLaser";
	if(IsExistProcess("sLaser.exe"))
	{
		HWND hWnd = FindWindowA(NULL, PgmName.c_str());
		if(Button2->Caption.AnsiCompare("SLaser ON") == 0)
		{
			ShowWindowAsync(hWnd, SW_SHOWNORMAL);
			SetActiveWindow (hWnd);
			SetForegroundWindow(hWnd);
			Button2->Caption = "SLaser OFF";
		}
		else
		{
			ShowWindow (hWnd, SW_HIDE);
			Button2->Caption = "SLaser ON";
		}
	}
	else
	{
		if(Button2->Caption.AnsiCompare("SLaser ON") == 0)
		{
			ShellExecuteA(NULL, "open", filepath.c_str(), NULL, "D:\\Project\\sLaser", SW_SHOW);
			Button2->Caption = "SLaser OFF";
		}
		else
		{
			Button2->Caption = "SLaser ON";
		}
	}
}
//---------------------------------------------------------------------------

