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

#include <vcl.h>
#pragma hdrstop

#include "CameraTest_Form.h"
#include "MultiLanguage.h"
#include "Environment.h"
#include "StudySpeedControl_Form.h"
#include "Waiting_Form.h"
#include "math.h"
#include <inifiles.hpp>

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TntExtCtrls"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"
TCameraTestForm *CameraTestForm;
//---------------------------------------------------------------------------
__fastcall TCameraTestForm::TCameraTestForm(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();

  AbnormalSW = false;
  AnsiString studyFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".stu";
	if (FileExists(studyFileName))
	{
		if (!LoadStudyData(studyFileName, lastStudyResultData))
    {
      AbnormalSW = true;
    }
  }
  else
  {
    AbnormalSW = true;
  }

  if (!ReadSetupData(&TabletSetupData))
  {
    AbnormalSW = true;
  }

  if (!Read3DSetupData(&Tablet3DSetupData))
  {
    AbnormalSW = true;
  }

  MakeTabletCharacterData(&ProductData, &TabletCharacter, &MachineParams);

  // CPB Data Initial
  CPBCommonVariableInitial();
  SideFaceSetUpDataTransForm_For_PCSIM(tempSideData);
}
//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::FormCreate(TObject *Sender)
{
  MeasuringResultGroupBox->DoubleBuffered = true;
  MeasuringResultGroupBox->Visible = false;

  StopButton->Enabled = false;
  bStop = false;

  if(ProductData.SubSamplingMode == IMAGE_SUBSAMPLING_MODE)
  {
    ImageWidth[0] = SYSTEM_CAMERA_WIDTH;
    ImageHeight[0] = SYSTEM_CAMERA_HEIGHT;

    ImageWidth[1] = SYSTEM_CAMERA_WIDTH;
    ImageHeight[1] = SYSTEM_CAMERA_HEIGHT;
  }
  else
  {
    ImageWidth[0] = SYSTEM_CAMERA_HD_WIDTH;
    ImageHeight[0] = SYSTEM_CAMERA_HD_HEIGHT;

    ImageWidth[1] = SYSTEM_CAMERA_WIDTH;
    ImageHeight[1] = SYSTEM_CAMERA_HEIGHT;
  }

  ReadCameraTestOptions();
  InitComponent();
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::InitComponent()
{
  HideCameraComponent();
  SetCameraID();
  SetCameraParams();
  SetStudyResultColor();
  SetMeasuredResultComponent();
  SetProgressBar();
}

//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::SetCameraID()
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    AnsiString ConvertString;
    if(SystemLinkCameraInfo[globalCameraIndex] != 0)
    {
      TTntPanel *CameraComponent;
      ConvertString = ConvertCameraIndex(globalCameraIndex);

      if(CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
      {
        ConvertString += "(3D)";
      }

      CameraComponent = (TTntPanel *) FindComponent("CameraNamePanel" + IntToStr(globalCameraIndex+1));
      if(CameraComponent)
      {
        CameraComponent->Caption = ConvertString;
      }

      CameraComponent = (TTntPanel *) FindComponent("StudyTabletColorPanel" + IntToStr(globalCameraIndex+1));
      if(CameraComponent)
      {
        CameraComponent->Caption = ConvertString;
      }

      CameraComponent = (TTntPanel *) FindComponent("CameraProgressLabel" + IntToStr(globalCameraIndex+1));
      if(CameraComponent)
      {
        CameraComponent->Caption = ConvertString;
      }

      CameraComponent = (TTntPanel *) FindComponent("ResultPanel" + IntToStr(globalCameraIndex+1));
      if(CameraComponent)
      {
        CameraComponent->Caption = ConvertString;
      }
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::HideCameraComponent()
{
  if(GlobalProgramID == PROGRAM_ID_150P)
  {
    for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if(SystemLinkCameraInfo[globalCameraIndex] == 0)
      {
        TTntPanel *CameraComponent;
        TProgressBar *CameraProgressBar;

        CameraComponent = (TTntPanel *) FindComponent("CameraNamePanel" + IntToStr(globalCameraIndex+1));
        if(CameraComponent)
        {
          CameraComponent->Visible = false;
        }

        CameraComponent = (TTntPanel *) FindComponent("CameraStatusPanel" + IntToStr(globalCameraIndex+1));
        if(CameraComponent)
        {
          CameraComponent->Visible = false;
        }

        CameraComponent = (TTntPanel *) FindComponent("CameraShutterSpeedPanel" + IntToStr(globalCameraIndex+1));
        if(CameraComponent)
        {
          CameraComponent->Visible = false;
        }

        CameraComponent = (TTntPanel *) FindComponent("CameraGainPanel" + IntToStr(globalCameraIndex+1));
        if(CameraComponent)
        {
          CameraComponent->Visible = false;
        }

        CameraComponent = (TTntPanel *) FindComponent("CurrentCameraShutterSpeedPanel" + IntToStr(globalCameraIndex+1));
        if(CameraComponent)
        {
          CameraComponent->Visible = false;
        }

        CameraComponent = (TTntPanel *) FindComponent("CurrentCameraGainPanel" + IntToStr(globalCameraIndex+1));
        if(CameraComponent)
        {
          CameraComponent->Visible = false;
        }

        CameraComponent = (TTntPanel *) FindComponent("StudyTabletColorPanel" + IntToStr(globalCameraIndex+1));
        if(CameraComponent)
        {
          CameraComponent->Visible = false;
        }

        CameraComponent = (TTntPanel *) FindComponent("CameraProgressLabel" + IntToStr(globalCameraIndex+1));
        if(CameraComponent)
        {
          CameraComponent->Visible = false;
        }

        CameraComponent = (TTntPanel *) FindComponent("ResultPanel" + IntToStr(globalCameraIndex+1));
        if(CameraComponent)
        {
          CameraComponent->Visible = false;
        }

        CameraProgressBar = (TProgressBar *) FindComponent("CameraProgressBar" + IntToStr(globalCameraIndex+1));
        if(CameraProgressBar)
        {
          CameraProgressBar->Visible = false;
        }
      }
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::ExitButtonClick(TObject *Sender)
{
  Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP);
  Machine.MachineStop();

  ModalResult = mrOk;
  this->Close();
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::SetCameraParams()
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    TTntPanel *CameraComponent;

    int StudyParams[2];
    int CurrentParams[2];

    StudyParams[0] = ProductData.StudyShutterSpeed[globalCameraIndex];
    StudyParams[1] = ProductData.StudyGainV[globalCameraIndex];

    if(CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
    {
      if(globalCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
      {
        if(ProductData.ExposureTime3D[0] != -1)
        {
          CurrentParams[0] = ProductData.ExposureTime3D[0];
          CurrentParams[1] = ProductData.AnalogGain3D[0];
        }
        else
        {
          CurrentParams[0] = ThreeDCameraDefaultInformation[globalCameraIndex].ExposureTime;
          CurrentParams[1] = ThreeDCameraDefaultInformation[globalCameraIndex].AnalogCameraGain;
        }
      }
      else
      {
        if(ProductData.ExposureTime3D[1] != -1)
        {
          CurrentParams[0] = ProductData.ExposureTime3D[1];
          CurrentParams[1] = ProductData.AnalogGain3D[1];
        }
        else
        {
          CurrentParams[0] = ThreeDCameraDefaultInformation[globalCameraIndex].ExposureTime;
          CurrentParams[1] = ThreeDCameraDefaultInformation[globalCameraIndex].AnalogCameraGain;
        }
      }
    }
    else
    {
      CurrentParams[0] = ProductData.ShutterSpeed[globalCameraIndex];
      CurrentParams[1] = ProductData.DigitalGainV[globalCameraIndex];
    }

    CameraComponent = (TTntPanel *) FindComponent("CameraShutterSpeedPanel" + IntToStr(globalCameraIndex+1));
    if(CameraComponent)
    {
      CameraComponent->Caption = IntToStr(StudyParams[0]);
    }

    CameraComponent = (TTntPanel *) FindComponent("CameraGainPanel" + IntToStr(globalCameraIndex+1));
    if(CameraComponent)
    {
      CameraComponent->Caption = IntToStr(StudyParams[1]);
    }

    CameraComponent = (TTntPanel *) FindComponent("CurrentCameraShutterSpeedPanel" + IntToStr(globalCameraIndex+1));
    if(CameraComponent)
    {
      CameraComponent->Caption = IntToStr(CurrentParams[0]);
    }

    CameraComponent = (TTntPanel *) FindComponent("CurrentCameraGainPanel" + IntToStr(globalCameraIndex+1));
    if(CameraComponent)
    {
      CameraComponent->Caption = IntToStr(CurrentParams[1]);
    }

    CameraComponent = (TTntPanel *) FindComponent("CameraStatusPanel" + IntToStr(globalCameraIndex+1));
    if(CameraComponent)
    {
      if((CurrentParams[0] != StudyParams[0]) || (CurrentParams[1] != StudyParams[1]))
      {
        CameraComponent->Font->Color = clRed;
        CameraComponent->Caption = "X";
      }
      else
      {
        CameraComponent->Font->Color = clLime;
        CameraComponent->Caption = "O";
      }
    }
  }
}

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

void __fastcall TCameraTestForm::SetStudyResultColor()
{
  int averageColor[3];
  int tempCount;
  memset(averageColor, 0, sizeof(int) * 3);
  tempCount = 0;

  memset(CameraStudyLevel, 0, sizeof(int) * SYSTEM_TOTAL_CAMERA_COUNT * 3);

  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    TColor studyResult;
    if(globalCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
    {                                            
      studyResult = (TColor)((lastStudyResultData.tabletMaxThickForFirstDisk << 16) +
			                        (lastStudyResultData.tabletMaxThickForFirstDisk << 8) +
                              lastStudyResultData.tabletMaxThickForFirstDisk);

      CameraStudyLevel[globalCameraIndex][0] = lastStudyResultData.tabletMaxThickForFirstDisk;
      CameraStudyLevel[globalCameraIndex][1] = lastStudyResultData.tabletMaxThickForFirstDisk;
      CameraStudyLevel[globalCameraIndex][2] = lastStudyResultData.tabletMaxThickForFirstDisk;
    }
    else if(globalCameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX - 1)
    {
      studyResult = (TColor)((lastStudyResultData.tabletMaxThickForSecondDisk << 16) +
			                        (lastStudyResultData.tabletMaxThickForSecondDisk << 8) +
                              lastStudyResultData.tabletMaxThickForSecondDisk);

      CameraStudyLevel[globalCameraIndex][0] = lastStudyResultData.tabletMaxThickForSecondDisk;
      CameraStudyLevel[globalCameraIndex][1] = lastStudyResultData.tabletMaxThickForSecondDisk;
      CameraStudyLevel[globalCameraIndex][2] = lastStudyResultData.tabletMaxThickForSecondDisk;
    }
    else if(globalCameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX - 1)
    {                                            
      studyResult = (TColor)((lastStudyResultData.tabletColorB_ForCamera1 << 16) +
			                        (lastStudyResultData.tabletColorG_ForCamera1 << 8) +
                              lastStudyResultData.tabletColorR_ForCamera1);

      averageColor[0] += lastStudyResultData.tabletColorB_ForCamera1;
      averageColor[1] += lastStudyResultData.tabletColorG_ForCamera1;
      averageColor[2] += lastStudyResultData.tabletColorR_ForCamera1;
      tempCount++;

      CameraStudyLevel[globalCameraIndex][0] = lastStudyResultData.tabletColorB_ForCamera1;
      CameraStudyLevel[globalCameraIndex][1] = lastStudyResultData.tabletColorG_ForCamera1;
      CameraStudyLevel[globalCameraIndex][2] = lastStudyResultData.tabletColorR_ForCamera1;
    }
    else if(globalCameraIndex == SD2_2D_FRONT_FACE_CAMERA_INDEX - 1)
    {                                            
      studyResult = (TColor)((lastStudyResultData.tabletColorB_ForCamera9 << 16) +
			                        (lastStudyResultData.tabletColorG_ForCamera9 << 8) +
                              lastStudyResultData.tabletColorR_ForCamera9);

      averageColor[0] += lastStudyResultData.tabletColorB_ForCamera9;
      averageColor[1] += lastStudyResultData.tabletColorG_ForCamera9;
      averageColor[2] += lastStudyResultData.tabletColorR_ForCamera9;
      tempCount++;

      CameraStudyLevel[globalCameraIndex][0] = lastStudyResultData.tabletColorB_ForCamera9;
      CameraStudyLevel[globalCameraIndex][1] = lastStudyResultData.tabletColorG_ForCamera9;
      CameraStudyLevel[globalCameraIndex][2] = lastStudyResultData.tabletColorR_ForCamera9;
    }
    else
    {
      studyResult = (TColor)((lastStudyResultData.SideFaceTabletBColor[globalCameraIndex] << 16) +
			                        (lastStudyResultData.SideFaceTabletGColor[globalCameraIndex] << 8) +
                              lastStudyResultData.SideFaceTabletRColor[globalCameraIndex]);

      averageColor[0] += lastStudyResultData.SideFaceTabletBColor[globalCameraIndex];
      averageColor[1] += lastStudyResultData.SideFaceTabletGColor[globalCameraIndex];
      averageColor[2] += lastStudyResultData.SideFaceTabletRColor[globalCameraIndex];
      tempCount++;

      CameraStudyLevel[globalCameraIndex][0] = lastStudyResultData.SideFaceTabletBColor[globalCameraIndex];
      CameraStudyLevel[globalCameraIndex][1] = lastStudyResultData.SideFaceTabletGColor[globalCameraIndex];
      CameraStudyLevel[globalCameraIndex][2] = lastStudyResultData.SideFaceTabletRColor[globalCameraIndex];
    }

    TTntPanel *CameraComponent;

    CameraComponent = (TTntPanel *) FindComponent("StudyTabletColorPanel" + IntToStr(globalCameraIndex+1));
    if(CameraComponent)
    {
      CameraComponent->Color = studyResult;
    }
  }

  if(tempCount)
  {
    averageColor[0] /= tempCount;
    averageColor[1] /= tempCount;
    averageColor[2] /= tempCount;

    averageColor[0] = (averageColor[0] | 0x80) & 0xFF;
    averageColor[1] = (averageColor[1] | 0x80) & 0xFF;
    averageColor[2] = (averageColor[2] | 0x80) & 0xFF;
  }
  
  TColor FontColor;

  FontColor = (TColor)((averageColor[0] << 16) +
                        (averageColor[1] << 8) +
                        averageColor[2]);

  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    if(CameraMapInfo[globalCameraIndex].CameraInspectPosition != CAMERA_POSITION_3D)
    {
      TTntPanel *CameraComponent;

      CameraComponent = (TTntPanel *) FindComponent("StudyTabletColorPanel" + IntToStr(globalCameraIndex+1));
      if(CameraComponent)
      {
        CameraComponent->Font->Color = FontColor;
      }
    }
  }
}

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

void __fastcall TCameraTestForm::SetMeasuredResultComponent()
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    TTntPanel *CameraComponent;

    CameraComponent = (TTntPanel *) FindComponent("ResultPanel" + IntToStr(globalCameraIndex+1));
    if(CameraComponent)
    {
      CameraComponent->Color = clDkGray;
      CameraComponent->Enabled = false;
    }
  }
}

//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::SetProgressBar()
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    TProgressBar *CameraComponent;

    CameraComponent = (TProgressBar *) FindComponent("CameraProgressBar" + IntToStr(globalCameraIndex+1));
    if(CameraComponent)
    {
      CameraComponent->Max = CameraCheckOption.CheckingCount;
      CameraComponent->Position = 0;
    }
  }
}

//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::InitImageComponent(TTntImage *srcImage, int width, int height)
{
  srcImage->Picture->Bitmap->Width = width;
  srcImage->Picture->Bitmap->Height = height;
  srcImage->Picture->Bitmap->PixelFormat = pf24bit;

  srcImage->Canvas->Brush->Color = clBlue;
	srcImage->Canvas->Brush->Style = bsSolid;
	srcImage->Canvas->FillRect(Rect(0, 0, srcImage->Picture->Bitmap->Width, srcImage->Picture->Bitmap->Height));
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::SpeedControlButtonClick(TObject *Sender)
{
  TStudySpeedControlForm *studyspeedControlForm = new TStudySpeedControlForm(this);
	studyspeedControlForm->ShowModal();
	delete studyspeedControlForm;  
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::OptionButtonClick(TObject *Sender)
{
  MainMenuPanel->Visible = false;
  CameraDataPanel->Visible = false;
  CameraCheckingPanel->Visible = false;
  CameraResultPanel->Visible = false;

  TestCountEdit->Text = IntToStr(CameraCheckOption.CheckingCount);
  AllowableRangeEdit->Text = IntToStr(CameraCheckOption.AllowableLevel);
  ErrorRateEdit->Text = IntToStr(CameraCheckOption.ErrorRate);
  FailCountEdit->Text = IntToStr(CameraCheckOption.AllowableFailCount);

  OptionSettingPanel->Visible = true;
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::ReadCameraTestOptions()
{
  AnsiString filename = ProgramPath.Env + "\\CameraTestOption.ini";
  if (FileExists(filename))
  {
    TIniFile *iniFile = new TIniFile(filename);
    CameraCheckOption.ErrorRate = iniFile->ReadInteger("Options", "Error Rate", 15);
    CameraCheckOption.AllowableLevel = iniFile->ReadInteger("Options", "Level", 20);
    CameraCheckOption.CheckingCount = iniFile->ReadInteger("Options", "Test Count", 10);
    CameraCheckOption.AllowableFailCount = iniFile->ReadInteger("Options", "Fail Count", 20);

    delete iniFile;
  }
  else
  {
    CameraCheckOption.ErrorRate = 15;
    CameraCheckOption.AllowableLevel = 20;
    CameraCheckOption.CheckingCount = 10;
    CameraCheckOption.AllowableFailCount = 20;

    WriteCameraTestOptions();
  }
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::WriteCameraTestOptions()
{
  AnsiString filename = ProgramPath.Env + "\\CameraTestOption.ini";

  TIniFile *iniFile = new TIniFile(filename);
  iniFile->WriteInteger("Options", "Error Rate", CameraCheckOption.ErrorRate);
  iniFile->WriteInteger("Options", "Level", CameraCheckOption.AllowableLevel);
  iniFile->WriteInteger("Options", "Test Count", CameraCheckOption.CheckingCount);
  iniFile->WriteInteger("Options", "Fail Count", CameraCheckOption.AllowableFailCount);

  delete iniFile;
}
//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::SetupButtonClick(TObject *Sender)
{
  CameraCheckOption.CheckingCount = StrToInt(TestCountEdit->Text);
  CameraCheckOption.AllowableLevel = StrToInt(AllowableRangeEdit->Text);
  CameraCheckOption.ErrorRate = StrToInt(ErrorRateEdit->Text);
  CameraCheckOption.AllowableFailCount = StrToInt(FailCountEdit->Text);

  WriteCameraTestOptions();

  OptionSettingPanel->Visible = false;

  CameraDataPanel->Visible = true;
  CameraCheckingPanel->Visible = true;
  CameraResultPanel->Visible = true;
  MainMenuPanel->Visible = true;
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::TestCountEditKeyPress(TObject *Sender,
      char &Key)
{
  Key = NULL;  
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::TestCountEditClick(TObject *Sender)
{
  TTntEdit *theEdit = (TTntEdit *)Sender;
	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeypad() == mrOk)
	{
    try
    {
      int tempValue = StrToInt(KeyboardForm->Text);

      if(tempValue < 10 || tempValue > 50)
      {
        throw(0);
      }

      theEdit->Text = IntToStr(tempValue);
    }
    catch(...)
    {
      MessageDlgFA(CAMERATEST_FORM_TEXT_24, mtConfirmation, TMsgDlgButtons() << mbOK);
    }
	}
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::AllowableRangeEditClick(TObject *Sender)
{
  TTntEdit *theEdit = (TTntEdit *)Sender;
	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeypad() == mrOk)
	{
    try
    {
      int tempValue = StrToInt(KeyboardForm->Text);

      if(tempValue < 10 || tempValue > 40)
      {
        throw(0);
      }

      theEdit->Text = IntToStr(tempValue);
    }
    catch(...)
    {
      MessageDlgFA(CAMERATEST_FORM_TEXT_24, mtConfirmation, TMsgDlgButtons() << mbOK);
    }
	}
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::ErrorRateEditClick(TObject *Sender)
{
  TTntEdit *theEdit = (TTntEdit *)Sender;
	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeypad() == mrOk)
	{
    try
    {
      int tempValue = StrToInt(KeyboardForm->Text);

      if(tempValue < 0 || tempValue > 30)
      {
        throw(0);
      }

      theEdit->Text = IntToStr(tempValue);
    }
    catch(...)
    {
      MessageDlgFA(CAMERATEST_FORM_TEXT_24, mtConfirmation, TMsgDlgButtons() << mbOK);
    }
	}
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::FailCountEditClick(TObject *Sender)
{
  TTntEdit *theEdit = (TTntEdit *)Sender;
	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeypad() == mrOk)
	{
    try
    {
      int tempValue = StrToInt(KeyboardForm->Text);

      if(tempValue < 0 || tempValue > 50)
      {
        throw(0);
      }

      theEdit->Text = IntToStr(tempValue);
    }
    catch(...)
    {
      MessageDlgFA(CAMERATEST_FORM_TEXT_24, mtConfirmation, TMsgDlgButtons() << mbOK);
    }
	}
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::StartButtonClick(TObject *Sender)
{
  if(!CheckCameraParams())
  {
    if (MessageDlgFA(CAMERATEST_FORM_TEXT_25, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) != mrOk)
    {
      MessageDlgFA(CAMERATEST_FORM_TEXT_26, mtConfirmation, TMsgDlgButtons() << mbOK);
      return;
    }
  }


  bool setupSW = false;
  setupSW = CaptureSetup();

  if(SimulationCheckBox->Checked)
  {
    setupSW = true;
  }

  for(int globalCameraIndex = 1; globalCameraIndex <= SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    if(CameraMapInfo[globalCameraIndex - 1].CameraInspectPosition != CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[globalCameraIndex - 1] != 0)
    {
      CurrentTargetCameraIndex = globalCameraIndex;
      break;
    }
  }

  if(setupSW)
  {
    StartButton->Enabled = false;
    StopButton->Enabled = true;
    SpeedControlButton->Enabled = false;
    OptionButton->Enabled = false;
    ExitButton->Enabled = false;
    TntGroupBox3->Enabled = false;

    bStop = false;

    SetProgressBar();
    SetMeasuredResultComponent();

    memset(CameraTestResultData, 0, sizeof(TCameraTestResultData) * SYSTEM_TOTAL_CAMERA_COUNT);
    memset(StudyResultData, 0, sizeof(int) * SYSTEM_TOTAL_CAMERA_COUNT * 3 * 256);
    TimerCheckingCameraIndex = -1;
    MeasuringTimer->Enabled = true;
  }
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::SetGaugeRange(int cameraIndex)
{
  Graphics::TBitmap *tempImage = new Graphics::TBitmap;
  tempImage->Width = 255;
  tempImage->Height = 70;
  tempImage->PixelFormat = pf24bit;

  int x, y;
  int value[3];
  int minRange, maxRange;
  value[0] = CameraStudyLevel[cameraIndex][0];
  value[1] = CameraStudyLevel[cameraIndex][1];
  value[2] = CameraStudyLevel[cameraIndex][2];

  if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1 || cameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX - 1)
  {
    GaugePanel1->Visible = true;
    GaugeImage1->Visible = true;

    GaugePanel2->Visible = false;
    GaugeImage2->Visible = false;

    GaugePanel3->Visible = false;
    GaugeImage3->Visible = false;

    minRange = max(0, value[1] - CameraCheckOption.AllowableLevel);
    maxRange = min(255 - 1, value[1] + CameraCheckOption.AllowableLevel);
    
    for(y = 0; y < 70; y++)
    {
      Byte *ptr = (Byte*)tempImage->ScanLine[y];
      for(x = 0; x < 255; x++)
      {
        int input;
        int shift;
        if(x > minRange && x < maxRange)
        {
          input = CameraCheckOption.AllowableLevel + 10;
          shift = 192 - input;
        }
        else
        {
          input = 128;
          shift = 0;
        }

        int distance = abs(x - value[1]);
        if(distance > input) distance = input;

        float sinV = distance / (float)input;
        float angle = asin(sinV);

        int tempValue = input * cos(angle);
        tempValue += shift;
        if(tempValue < 0) tempValue = 0;
        if(tempValue > 192) tempValue = 192;

        ptr[3 * x + 0] = tempValue;
        ptr[3 * x + 1] = tempValue;
        ptr[3 * x + 2] = tempValue;
      }
    }

    GaugeImage1->Picture->Bitmap->Assign(tempImage);
    GaugeImage1->Refresh();
    GaugePanel1->Caption = "H";
  }
  else
  {
    GaugePanel1->Visible = true;
    GaugeImage1->Visible = true;

    GaugePanel2->Visible = true;
    GaugeImage2->Visible = true;

    GaugePanel3->Visible = true;
    GaugeImage3->Visible = true;

    minRange = max(0, value[0] - CameraCheckOption.AllowableLevel);
    maxRange = min(255 - 1, value[0] + CameraCheckOption.AllowableLevel);

    for(y = 0; y < 70; y++)
    {
      Byte *ptr = (Byte*)tempImage->ScanLine[y];
      for(x = 0; x < 255; x++)
      {
        int input;
        int shift;
        if(x > minRange && x < maxRange)
        {
          input = CameraCheckOption.AllowableLevel + 10;
          shift = 255 - input;
        }
        else
        {
          input = 128;
          shift = 0;
        }

        int distance = abs(x - value[0]);
        if(distance > input) distance = input;

        float sinV = distance / (float)input;
        float angle = asin(sinV);

        int tempValue = input * cos(angle);
        tempValue += shift;
        if(tempValue < 0) tempValue = 0;
        if(tempValue > 255) tempValue = 255;

        ptr[3 * x + 0] = min(255, tempValue + 20);
        ptr[3 * x + 1] = 20;
        ptr[3 * x + 2] = 20;
      }
    }

    GaugeImage1->Picture->Bitmap->Assign(tempImage);
    GaugeImage1->Refresh();
    GaugePanel1->Caption = "B";

    minRange = max(0, value[1] - CameraCheckOption.AllowableLevel);
    maxRange = min(255 - 1, value[1] + CameraCheckOption.AllowableLevel);

    for(y = 0; y < 70; y++)
    {
      Byte *ptr = (Byte*)tempImage->ScanLine[y];
      for(x = 0; x < 255; x++)
      {
        int input;
        int shift;
        if(x > minRange && x < maxRange)
        {
          input = CameraCheckOption.AllowableLevel + 10;
          shift = 255 - input;
        }
        else
        {
          input = 128;
          shift = 0;
        }

        int distance = abs(x - value[1]);
        if(distance > input) distance = input;

        float sinV = distance / (float)input;
        float angle = asin(sinV);

        int tempValue = input * cos(angle);
        tempValue += shift;
        if(tempValue < 0) tempValue = 0;
        if(tempValue > 255) tempValue = 255;

        ptr[3 * x + 0] = 20;
        ptr[3 * x + 1] = min(255, tempValue + 20);
        ptr[3 * x + 2] = 20;
      }
    }

    GaugeImage2->Picture->Bitmap->Assign(tempImage);
    GaugeImage2->Refresh();

    minRange = max(0, value[2] - CameraCheckOption.AllowableLevel);
    maxRange = min(255 - 1, value[2] + CameraCheckOption.AllowableLevel);

    for(y = 0; y < 70; y++)
    {
      Byte *ptr = (Byte*)tempImage->ScanLine[y];
      for(x = 0; x < 255; x++)
      {
        int input;
        int shift;
        if(x > minRange && x < maxRange)
        {
          input = CameraCheckOption.AllowableLevel + 10;
          shift = 255 - input;
        }
        else
        {
          input = 128;
          shift = 0;
        }

        int distance = abs(x - value[2]);
        if(distance > input) distance = input;

        float sinV = distance / (float)input;
        float angle = asin(sinV);

        int tempValue = input * cos(angle);
        tempValue += shift;
        if(tempValue < 0) tempValue = 0;
        if(tempValue > 255) tempValue = 255;

        ptr[3 * x + 0] = 20;
        ptr[3 * x + 1] = 20;
        ptr[3 * x + 2] = min(255, tempValue + 20);
      }
    }

    GaugeImage3->Picture->Bitmap->Assign(tempImage);
    GaugeImage3->Refresh();
  }

  delete tempImage;
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::InitMeasureValue()
{
  CurrentFailCountPanel->Caption = "0";
  CurrentCameraBrightnessPanel->Caption = "N/A";
  CurrentCameraBrightnessPanel->Color = clGray;
  CurrentCameraMinDiffBrightnessPanel->Caption = "N/A";
  CurrentCameraMinDiffBrightnessPanel->Color = clGray;
  CurrentCameraMaxDiffBrightnessPanel->Caption = "N/A";
  CurrentCameraMaxDiffBrightnessPanel->Color = clGray;
  CurrentErrorRatePanel->Caption = "0%";
  CurrentStatusPanel->Caption = CAMERATEST_FORM_TEXT_27;
}

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

bool __fastcall TCameraTestForm::CaptureSetup()
{
  // check machine interlock
  if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE1)
  {
    if (MachineSetupData.InterlockInfo.ACdomesticMode)
    {
      if (!Machine.InterlockCheck())
      {
        ShowMessageFA(Machine.GetInterlockMessage());
        return false;
      }
    }
    else
    {
      if (!Machine.InterlockCheck())
      {
        ShowMessageFA(Machine.GetInterlockMessage());
        return false;
      }
    }
  }
  else
  {
    if (MachineSetupData.InterlockInfo.DoorInterlockEnabled)
    {
      if (!Machine.InterlockCheck())
      {
        ShowMessageFA(Machine.GetInterlockMessage());
        return false;
      }
    }
  }

	if (!Machine.CanCaptureStart(ProductData.LampKind))
	{
		ShowMessageFA(Machine.GetCaptureStartFailMessage(ProductData.LampKind));
		return false;
	}

  if (Machine.Status.OperationState != MACHINE_STATE_STOP &&
			Machine.Status.OperationState != MACHINE_STATE_CLEANING &&
			Machine.Status.OperationState != MACHINE_STATE_ATTACHING &&
			Machine.Status.OperationState != MACHINE_STATE_DETACHING)
  {
    Machine.MachineStop();
    ShowMessageFA(INSPECTIONFORM_MSG_23);
    return false;
  }

  unsigned int camMask = 0;
	for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
	{
    if ((CameraMapInfo[globalCameraIndex].CameraInspectPosition < CAMERA_POSITION_DISCONNECT) && (SystemLinkCameraInfo[globalCameraIndex] != 0))
    {
      camMask |= (0x0001 << globalCameraIndex);
    }
  }

	try
	{
    float tabletHalfLength = ProductData.TabletLength / 2;

    // Camera Shutter Speed 갱신
    for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
	  {
      int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
      if (!Comm_IsConnected(COMM_SPB + spbIndex)) continue;

      if (CameraMapInfo[globalCameraIndex].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[globalCameraIndex] != 0)
      {
        RefreshCameraInfo(globalCameraIndex, 1.0);
        Application->ProcessMessages();
        this->Refresh();
      }
    }
    
    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);
      }
    }

    // capture
    SendSPBCaptureSetup_Multi(&ProductData, camMask, tabletHalfLength, ProductData.ShutterSpeed,
			                        ProductData.StudyMotorSpeedList[SD1_MOTOR_INDEX][0], MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed,
			                        ProductData.StudyMotorSpeedList[SD2_MOTOR_INDEX][0], MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed,
                              ProductData.SubSamplingMode, false);

		TMachineCaptureSetupData machineCaptureSetupData;
		memcpy(machineCaptureSetupData.IlluminatorMask, MachineSetupData.MachineCaptureInfo.IlluminatorMask, SYSTEM_MACHINE_CAPTURE_COUNT * sizeof(int));
		machineCaptureSetupData.CaptureOption = 0;
		machineCaptureSetupData.TabletLength = ProductData.TabletLength;
		machineCaptureSetupData.TabletSideThick = ProductData.TabletSideThick*10;
		machineCaptureSetupData.SuctionDiskSpeed = ProductData.StudyMotorSpeedList[0][0]; /// studyspeed khs
		machineCaptureSetupData.StudiedTabletSensorLength = ProductData.StudiedSensor1Length;
		if (!Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE, &machineCaptureSetupData, sizeof(TMachineCaptureSetupData),
			NULL, 0))
		{
			throw Exception("");
		}

		int motorSpeedList[MAX_SERVO_MOTOR_COUNT];
		for (int motorIndex = 0; motorIndex < MAX_SERVO_MOTOR_COUNT; motorIndex++)
		{
			motorSpeedList[motorIndex] = ProductData.StudyMotorSpeedList[motorIndex][0]; // studyspeed khs
		}

		if (!Machine.MachineRun(PROCEDURE_MODE_CAPTURE, &ProductData.MachineRunOption,
			ProductData.NCMotorPos, motorSpeedList))
		{
			throw Exception("");
		}
	}
	catch (...)
	{
    return false;
	}

  return true;
}

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

void __fastcall TCameraTestForm::RefreshCameraInfo(int camIndex, float m)
{
	int ShutterSpeed = 0;
	int Threshold = 0;
	int WriteMask = 0;

	// Shutter 정보
	ShutterSpeed = ProductData.ShutterSpeed[camIndex] * m;

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

	// Threshold는 3D 카메라에만 적용
	if (CameraMapInfo[camIndex].CameraInspectPosition == CAMERA_POSITION_3D)
	{
		Threshold = ProductData.ThresholdFor3D[camIndex];
		WriteMask |= CAMERA_WRITE_MASK_TH;
	}

	TROIInfo DefaultROIInfo, ApplyROIInfo;
	AnsiString filePath;
	int DiskBaseHeight;
	int tempStartY, tempEndY, tempRowCount;
	filePath = ProgramPath.Env + "\\NFACameraInformation.ini";
	DefaultROIInfo = ReadCameraInformation(filePath, camIndex);

	if (CameraMapInfo[camIndex].CameraInspectPosition != CAMERA_POSITION_3D)
	{
		memcpy(&ApplyROIInfo, &DefaultROIInfo, sizeof(TROIInfo));
    WriteMask |= CAMERA_WRITE_MASK_2D_ROI;
	}
	else
	{
		ApplyROIInfo = SetThreeDCameraROI(DefaultROIInfo, &ProductData);
    WriteMask |= CAMERA_WRITE_MASK_3D_ROI;
	}

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

  if (CameraMapInfo[camIndex].CameraInspectPosition != CAMERA_POSITION_3D)
  {
    SetCameraInformation(ApplyROIInfo, ShutterSpeed, Threshold,ProductData.SubSamplingMode, camIndex, WriteMask);
    SetCameraGain(camIndex + 1, SYSTEM_DEFAULT_ANLOG_GAIN, ProductData.DigitalGainV[camIndex], 0);
  }
  else
  {
    WriteMask |= CAMERA_WRITE_MASK_3D_SH;

    int ThreedCameraIndex = 0;
    if(camIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX-1) ThreedCameraIndex = 0;
    else ThreedCameraIndex = 1;

    if(ProductData.ExposureTime3D[ThreedCameraIndex] != -1)
    {
      Set3DCamera_CaptureParameter(camIndex,ProductData.AnalogGain3D[ThreedCameraIndex],ProductData.ExposureTime3D[ThreedCameraIndex]);
    }
    else
    {
      Set3DCamera_CaptureParameter(camIndex,ThreeDCameraDefaultInformation[camIndex].AnalogCameraGain,ThreeDCameraDefaultInformation[camIndex].ExposureTime);
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::MeasuringTimerTimer(TObject *Sender)
{
  bool timerEnabled = MeasuringTimer->Enabled;
  MeasuringTimer->Enabled = false;
  
  if(TimerCheckingCameraIndex != CurrentTargetCameraIndex)
  {
    // checking camera가 다른 경우 발생되는 이벤트, component 초기화
    TimerCheckingCameraIndex = CurrentTargetCameraIndex;

    Setup(TimerCheckingCameraIndex);
    
    if(CameraMapInfo[TimerCheckingCameraIndex - 1].CameraInspectPosition == CAMERA_POSITION_3D)
    {
      InitImageComponent(CurrentImage, ImageWidth[1], ImageHeight[1]);
      InitImageComponent(MinBrightnessResultImage, ImageWidth[1], ImageHeight[1]);
      InitImageComponent(MaxBrightnessResultImage, ImageWidth[1], ImageHeight[1]);
    }
    else
    {
      InitImageComponent(CurrentImage, ImageWidth[0], ImageHeight[0]);
      InitImageComponent(MinBrightnessResultImage, ImageWidth[0], ImageHeight[0]);
      InitImageComponent(MaxBrightnessResultImage, ImageWidth[0], ImageHeight[0]);
    }

    InitMeasureValue();
    SetGaugeRange(TimerCheckingCameraIndex - 1);

    globalCameraFailCount = 0;
    globalCameraCheckingCount = 0;
    Sim_ImageIndex = 1;

    memset(AccColor, 0, sizeof(int) * 3);
    memset(MinDiffColor, 0, sizeof(int) * 3);
    memset(MaxDiffColor, 0, sizeof(int) * 3);
    MinDiffLevel = 0x0FFFFFFF;
    MaxDiffLevel = 0;

    AnsiString ConvertString = ConvertCameraIndex(TimerCheckingCameraIndex - 1);
    MeasuringResultGroupBox->Caption = CAMERATEST_FORM_TEXT_10 + "(" + ConvertString + ")";
  }

  MeasuringResultGroupBox->Visible = true;

  WideString stopMsg;
  unsigned int data[2];
	unsigned int receivedData[2];
  bool bCaptureExist = false; 

  int spbIndex = CameraMapInfo[TimerCheckingCameraIndex - 1].SPBIndex;
  int camIndex = CameraMapInfo[TimerCheckingCameraIndex - 1].CamIndex;
  data[0] = camIndex;

  if (SimulationCheckBox->Checked)
  {
    bCaptureExist = true;
    ExtractBayerImage(BayerImage, Sim_ImageIndex, TimerCheckingCameraIndex);
  }
  else
  {
    if (Comm_IsConnected(COMM_SPB + spbIndex))
    {
      try
      {
        if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_EXIST, data, sizeof(unsigned int),
          receivedData, sizeof(unsigned int) * 2))
        {
          throw Exception("");
        }

        if (receivedData[0])
        {
          bCaptureExist = true;
        }
        else
        {
          bCaptureExist = false;
        }

        if (bCaptureExist)
        {
          if (CameraMapInfo[TimerCheckingCameraIndex - 1].CameraInspectPosition == CAMERA_POSITION_3D)
          {
            data[1] = ImageWidth[1] * ImageHeight[1];
          }
          else
          {
            data[1] = ImageWidth[0] * ImageHeight[0];
          }

          Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_UPLOAD, data, 2 * sizeof(unsigned int), CaptureData, data[1]);
        }
      }
      catch (Exception &ec)
      {
        timerEnabled = false;
        stopMsg = CAMERATEST_FORM_TEXT_28;
      }
    }
  }

  if(bCaptureExist)
  {
    DoProcessing(TimerCheckingCameraIndex);

    Sim_ImageIndex++;

    if(DefectSW >= 2)
    {
      globalCameraFailCount++;
    }
    else
    {
      globalCameraCheckingCount++;
    }
  }

  LoadRealtimeResult(TimerCheckingCameraIndex);

  if(globalCameraCheckingCount >= CameraCheckOption.CheckingCount)
  {
    bool existNextCamera = false;
    for(int globalCameraIndex = TimerCheckingCameraIndex + 1; globalCameraIndex <= SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if(CameraMapInfo[globalCameraIndex - 1].CameraInspectPosition != CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[globalCameraIndex - 1] != 0)
      {
        CurrentTargetCameraIndex = globalCameraIndex;
        existNextCamera = true;
        break;
      }
    }

    TTntPanel *CameraComponent = (TTntPanel *) FindComponent("ResultPanel" + IntToStr(TimerCheckingCameraIndex));

    if(CameraTestResultData[TimerCheckingCameraIndex - 1].AverageErrorRate > CameraCheckOption.ErrorRate)
    {
      CurrentStatusPanel->Caption = CAMERATEST_FORM_TEXT_29;

      if(CameraComponent)
      {
        CameraComponent->Color = clRed;
        CameraComponent->Enabled = true;
      }
    }
    else
    {
      CurrentStatusPanel->Caption = CAMERATEST_FORM_TEXT_30;

      if(CameraComponent)
      {
        CameraComponent->Color = clLime;
        CameraComponent->Enabled = true;
      }
    }

    CameraTestResultData[TimerCheckingCameraIndex - 1].CheckSW = 1;

    Application->ProcessMessages();
    Sleep(500);

    if(existNextCamera == false)
    {
      timerEnabled = false;
      stopMsg = CAMERATEST_FORM_TEXT_31;
    }
  }
  else if(globalCameraFailCount >= CameraCheckOption.AllowableFailCount)
  {
    timerEnabled = false;
    stopMsg = CAMERATEST_FORM_TEXT_32;
  }

  if(bStop)
  {
    timerEnabled = false;
    stopMsg = "";
  }

  if(timerEnabled == false)
  {
    Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP);

    if (Machine.MachineStop())
    {
      WaitingForm->WaitingMachineStop();
    }

    if(!stopMsg.IsEmpty())
    {
      MessageDlgFA(stopMsg, mtConfirmation, TMsgDlgButtons() << mbOK);
    }

    StartButton->Enabled = true;
    StopButton->Enabled = false;
    SpeedControlButton->Enabled = true;
    OptionButton->Enabled = true;
    ExitButton->Enabled = true;
    TntGroupBox3->Enabled = true;

    bStop = false;
  }

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

bool __fastcall TCameraTestForm::ReadSetupData(TTabletSetupData *tabletSetupData)
{
  AnsiString setupDataFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".sdt";
  if (FileExists(setupDataFileName))
  {
    TFileStream *fileStream  = new TFileStream(setupDataFileName, fmOpenRead);
    if (fileStream)
    {
      fileStream->Read(tabletSetupData, sizeof(TTabletSetupData));
      delete fileStream;
      return true;
    }
    else
    {
      return false;
    }
  }
  else
  {
    return false;
  }
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::DoProcessing(int cameraIndex)
{
  int InspectionOrStudy = STUDY_MODE;
  int InspectionKind;
  int width;
  int height;

  width = ImageWidth[0];
  height = ImageHeight[0];

  switch(cameraIndex)
  {
    case SD1_2D_FRONT_FACE_CAMERA_INDEX:
    case SD2_2D_FRONT_FACE_CAMERA_INDEX:
      InspectionKind = FRONT_FACE;
      ProcessingStartForFrontFace(InspectionOrStudy, cameraIndex, 0);
      break;
    case SD1_3D_FRONT_FACE_CAMERA_INDEX:
    case SD2_3D_FRONT_FACE_CAMERA_INDEX:
      InspectionKind = FRONT_FACE_SPECIAL;
      ProcessingStartForFrontFace_3D(InspectionOrStudy, cameraIndex, 0x01);

      width = ImageWidth[1];
      height = ImageHeight[1];
      break;
    case SD1_2D_SIDE_FACE_P45_CAMERA_INDEX:
    case SD2_2D_SIDE_FACE_P45_CAMERA_INDEX:
    case SD1_2D_OTHER_SIDE_FACE_P45_CAMERA_INDEX:
    case SD2_2D_OTHER_SIDE_FACE_P45_CAMERA_INDEX:
			InspectionKind = SIDE_FACE_P45;
      ProcessingStartForSideFace_P45(InspectionOrStudy, cameraIndex, 0);
			break;
    case SD1_2D_SIDE_FACE_00_CAMERA_INDEX:
    case SD2_2D_SIDE_FACE_00_CAMERA_INDEX:
    case SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX:
    case SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX:
			InspectionKind = SIDE_FACE_0;
      ProcessingStartForSideFace_0(InspectionOrStudy, cameraIndex, 0);
			break;
		case SD1_2D_SIDE_FACE_M45_CAMERA_INDEX:
    case SD2_2D_SIDE_FACE_M45_CAMERA_INDEX:
    case SD1_2D_OTHER_SIDE_FACE_M45_CAMERA_INDEX:
    case SD2_2D_OTHER_SIDE_FACE_M45_CAMERA_INDEX:
			InspectionKind = SIDE_FACE_M45;
      ProcessingStartForSideFace_M45(InspectionOrStudy, cameraIndex, 0);
			break;
  }

  int x, y;
  Graphics::TBitmap *img1;
  img1 = new Graphics::TBitmap();
  img1->Width = width;
  img1->Height = height;
  img1->PixelFormat = pf24bit;
                              
  Byte *ptr;
  for(y = 0 ; y < height; y++)
  {
    ptr = (byte*) img1->ScanLine[y];
    for(x = 0; x < width; x++)
    {
      int tempAddress = width * y + x;

      if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX || cameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX)
      {
        ptr[3*x+0] = ThreeD_Image[tempAddress];
        ptr[3*x+1] = ThreeD_Image[tempAddress];
        ptr[3*x+2] = ThreeD_Image[tempAddress];
      }
      else
      {
        ptr[3*x+0] = ColorSourceImage[tempAddress * 3 + 0];
        ptr[3*x+1] = ColorSourceImage[tempAddress * 3 + 1];
        ptr[3*x+2] = ColorSourceImage[tempAddress * 3 + 2];
      }
    }
  }
  
  CurrentImage->Picture->Bitmap->Assign(img1);
  CurrentImage->Refresh();
  delete(img1);
}

//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::Setup(int cameraIndex)
{  
  int InspectionOrStudy = STUDY_MODE;
  int InspectionKind;

  ReadSetupData(&TabletSetupData);
  Read3DSetupData(&Tablet3DSetupData);

  switch(cameraIndex)
  {
    case SD1_2D_FRONT_FACE_CAMERA_INDEX:
    case SD2_2D_FRONT_FACE_CAMERA_INDEX:
      InspectionKind = FRONT_FACE;
      break;
    case SD1_3D_FRONT_FACE_CAMERA_INDEX:
    case SD2_3D_FRONT_FACE_CAMERA_INDEX:
      InspectionKind = FRONT_FACE_SPECIAL;
      break;
    case SD1_2D_SIDE_FACE_P45_CAMERA_INDEX:
    case SD2_2D_SIDE_FACE_P45_CAMERA_INDEX:
    case SD1_2D_OTHER_SIDE_FACE_P45_CAMERA_INDEX:
    case SD2_2D_OTHER_SIDE_FACE_P45_CAMERA_INDEX:
			InspectionKind = SIDE_FACE_P45;
			break;
    case SD1_2D_SIDE_FACE_00_CAMERA_INDEX:
    case SD2_2D_SIDE_FACE_00_CAMERA_INDEX:
    case SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX:
    case SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX:
			InspectionKind = SIDE_FACE_0;
			break;
		case SD1_2D_SIDE_FACE_M45_CAMERA_INDEX:
    case SD2_2D_SIDE_FACE_M45_CAMERA_INDEX:
    case SD1_2D_OTHER_SIDE_FACE_M45_CAMERA_INDEX:
    case SD2_2D_OTHER_SIDE_FACE_M45_CAMERA_INDEX:
			InspectionKind = SIDE_FACE_M45;
			break;
  }

  SetSideFaceDataAddress(&tempSideData[0]);

  CPBCommonVariableInitial();

  int SDNum;
  if(cameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX || cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX)
  {
    SDNum = SUCTION_DISK_NUM1;
    FrontFaceSetUpDataTransForm(InspectionKind,SDNum);    
    SetUpDataTransFormForThreeD(InspectionKind,SDNum);
  }
  else if(cameraIndex == SD2_2D_FRONT_FACE_CAMERA_INDEX || cameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX)
  {
    SDNum = SUCTION_DISK_NUM2;
    FrontFaceSetUpDataTransForm(InspectionKind,SDNum);
    SetUpDataTransFormForThreeD(InspectionKind,SDNum);
  }
}
//---------------------------------------------------------------------------

bool __fastcall TCameraTestForm::Read3DSetupData(TTablet3DSetupData *tablet3DSetupData)
{
	AnsiString setupDataFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".sdt_3D";
  if (FileExists(setupDataFileName))
  {
    TFileStream *fileStream  = new TFileStream(setupDataFileName, fmOpenRead);
    if (fileStream)
    {
      fileStream->Read(tablet3DSetupData, sizeof(TTablet3DSetupData));
    	delete fileStream;
      return true;
    }
    else
    {
      return false;
    }
  }
  else
  {
    return false;
  }
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::LoadRealtimeResult(int cameraIndex)
{
  TProgressBar *CameraProgressBar;
  CameraProgressBar = (TProgressBar *) FindComponent("CameraProgressBar" + IntToStr(cameraIndex));
  if(CameraProgressBar)
  {
    CameraProgressBar->Position = globalCameraCheckingCount;
  }

  TTntPanel *selectedPanel = (TTntPanel*)FindComponent("ResultPanel" + IntToStr(cameraIndex));
  selectedPanel->Color = clYellow;

  CurrentFailCountPanel->Caption = IntToStr(globalCameraFailCount);

  if(DefectSW == 0 || DefectSW == 1)
  {
    int tempColor[3];
    if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX)
    {
      tempColor[0] = TabletStudyData.tabletMaxThickForFirstDisk;
      tempColor[1] = TabletStudyData.tabletMaxThickForFirstDisk;
      tempColor[2] = TabletStudyData.tabletMaxThickForFirstDisk;
    }
    else if(cameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX)
    {
      tempColor[0] = TabletStudyData.tabletMaxThickForSecondDisk;
      tempColor[1] = TabletStudyData.tabletMaxThickForSecondDisk;
      tempColor[2] = TabletStudyData.tabletMaxThickForSecondDisk;
    }
    else if(cameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX)
    {
      tempColor[0] = TabletStudyData.tabletColorB_ForCamera1;
      tempColor[1] = TabletStudyData.tabletColorG_ForCamera1;
      tempColor[2] = TabletStudyData.tabletColorR_ForCamera1;
    }
    else if(cameraIndex == SD2_2D_FRONT_FACE_CAMERA_INDEX)
    {
      tempColor[0] = TabletStudyData.tabletColorB_ForCamera9;
      tempColor[1] = TabletStudyData.tabletColorG_ForCamera9;
      tempColor[2] = TabletStudyData.tabletColorR_ForCamera9;
    }
    else
    {
      tempColor[0] = TabletStudyData.SideFaceTabletBColor[cameraIndex - 1];
      tempColor[1] = TabletStudyData.SideFaceTabletGColor[cameraIndex - 1];
      tempColor[2] = TabletStudyData.SideFaceTabletRColor[cameraIndex - 1];
    }

    AccColor[0] += tempColor[0];
    AccColor[1] += tempColor[1];
    AccColor[2] += tempColor[2];

    int errorLevel[3];
    errorLevel[0] = abs(tempColor[0] - CameraStudyLevel[cameraIndex - 1][0]);
    errorLevel[1] = abs(tempColor[1] - CameraStudyLevel[cameraIndex - 1][1]);
    errorLevel[2] = abs(tempColor[2] - CameraStudyLevel[cameraIndex - 1][2]);

    int sum = errorLevel[0] + errorLevel[1] + errorLevel[2];
    if(sum < MinDiffLevel)
    {
      MinDiffLevel = sum;
      MinDiffColor[0] = tempColor[0];
      MinDiffColor[1] = tempColor[1];
      MinDiffColor[2] = tempColor[2];

      MinBrightnessResultImage->Picture->Bitmap->Assign(CurrentImage->Picture->Bitmap);
      MinBrightnessResultImage->Refresh();

      int width, height;
      if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX || cameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX)
      {
        width = ImageWidth[1];
        height = ImageHeight[1];
      }
      else
      {
        width = ImageWidth[0];
        height = ImageHeight[0];
      }

      int x, y;
      for(y = 0 ; y < height; y++)
      {
        for(x = 0; x < width; x++)
        {
          int tempAddress = width * y + x;

          if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX || cameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX)
          {
            minBrightnessImage[cameraIndex - 1][tempAddress * 3 + 0] = ThreeD_Image[tempAddress];
            minBrightnessImage[cameraIndex - 1][tempAddress * 3 + 1] = ThreeD_Image[tempAddress];
            minBrightnessImage[cameraIndex - 1][tempAddress * 3 + 2] = ThreeD_Image[tempAddress];
          }
          else
          {
            minBrightnessImage[cameraIndex - 1][tempAddress * 3 + 0] = ColorSourceImage[tempAddress * 3 + 0];
            minBrightnessImage[cameraIndex - 1][tempAddress * 3 + 1] = ColorSourceImage[tempAddress * 3 + 1];
            minBrightnessImage[cameraIndex - 1][tempAddress * 3 + 2] = ColorSourceImage[tempAddress * 3 + 2];
          }
        }
      }
    }

    if(sum > MaxDiffLevel)
    {
      MaxDiffLevel = sum;
      MaxDiffColor[0] = tempColor[0];
      MaxDiffColor[1] = tempColor[1];
      MaxDiffColor[2] = tempColor[2];

      MaxBrightnessResultImage->Picture->Bitmap->Assign(CurrentImage->Picture->Bitmap);
      MaxBrightnessResultImage->Refresh();

      int width, height;
      if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX || cameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX)
      {
        width = ImageWidth[1];
        height = ImageHeight[1];
      }
      else
      {
        width = ImageWidth[0];
        height = ImageHeight[0];
      }

      int x, y;
      for(y = 0 ; y < height; y++)
      {
        for(x = 0; x < width; x++)
        {
          int tempAddress = width * y + x;

          if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX || cameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX)
          {
            maxBrightnessImage[cameraIndex - 1][tempAddress * 3 + 0] = ThreeD_Image[tempAddress];
            maxBrightnessImage[cameraIndex - 1][tempAddress * 3 + 1] = ThreeD_Image[tempAddress];
            maxBrightnessImage[cameraIndex - 1][tempAddress * 3 + 2] = ThreeD_Image[tempAddress];
          }
          else
          {
            maxBrightnessImage[cameraIndex - 1][tempAddress * 3 + 0] = ColorSourceImage[tempAddress * 3 + 0];
            maxBrightnessImage[cameraIndex - 1][tempAddress * 3 + 1] = ColorSourceImage[tempAddress * 3 + 1];
            maxBrightnessImage[cameraIndex - 1][tempAddress * 3 + 2] = ColorSourceImage[tempAddress * 3 + 2];
          }
        }
      }
    }

    StudyResultData[cameraIndex - 1][0][tempColor[0]]++;
    StudyResultData[cameraIndex - 1][1][tempColor[1]]++;
    StudyResultData[cameraIndex - 1][2][tempColor[2]]++;

    GaugeImage1->Canvas->Pen->Width = 1;
    GaugeImage1->Canvas->Pen->Color = clBlack;

    for(int m = 0; m < 256; m++)
    {
      if(StudyResultData[cameraIndex - 1][0][m])
      {
        int count = StudyResultData[cameraIndex - 1][0][m];
        int pos = max(10, 70 - 10 * count);  

        GaugeImage1->Canvas->MoveTo(m, 70);
        GaugeImage1->Canvas->LineTo(m, pos);
      }
    }

    GaugeImage1->Refresh();

    GaugeImage2->Canvas->Pen->Width = 1;
    GaugeImage2->Canvas->Pen->Color = clBlack;

    for(int m = 0; m < 256; m++)
    {
      if(StudyResultData[cameraIndex - 1][1][m])
      {
        int count = StudyResultData[cameraIndex - 1][1][m];
        int pos = max(10, 70 - 10 * count);

        GaugeImage2->Canvas->MoveTo(m, 70);
        GaugeImage2->Canvas->LineTo(m, pos);
      }
    }

    GaugeImage2->Refresh();

    GaugeImage3->Canvas->Pen->Width = 1;
    GaugeImage3->Canvas->Pen->Color = clBlack;

    for(int m = 0; m < 256; m++)
    {
      if(StudyResultData[cameraIndex - 1][2][m])
      {
        int count = StudyResultData[cameraIndex - 1][2][m];
        int pos = max(10, 70 - 10 * count);

        GaugeImage3->Canvas->MoveTo(m, 70);
        GaugeImage3->Canvas->LineTo(m, pos);
      }
    }

    GaugeImage3->Refresh();
  }

  float ErrorRate;
  int maxErrorSize = 0;
  maxErrorSize += CameraStudyLevel[cameraIndex - 1][0];
  maxErrorSize += CameraStudyLevel[cameraIndex - 1][1];
  maxErrorSize += CameraStudyLevel[cameraIndex - 1][2];

  if(globalCameraCheckingCount)
  {
    int averageColor[3];
    averageColor[0] = AccColor[0] / globalCameraCheckingCount;
    averageColor[1] = AccColor[1] / globalCameraCheckingCount;
    averageColor[2] = AccColor[2] / globalCameraCheckingCount;

    CurrentCameraBrightnessPanel->Color = (TColor)((averageColor[0] << 16) + (averageColor[1] << 8) + averageColor[2]);

    int errorLevel[3];
    errorLevel[0] = abs(averageColor[0] - CameraStudyLevel[cameraIndex - 1][0]);
    errorLevel[1] = abs(averageColor[1] - CameraStudyLevel[cameraIndex - 1][1]);
    errorLevel[2] = abs(averageColor[2] - CameraStudyLevel[cameraIndex - 1][2]);

    if(maxErrorSize)
    {
      ErrorRate = (errorLevel[0] + errorLevel[1] + errorLevel[2]) * 100 / (float)maxErrorSize;
    }
    else
    {
      ErrorRate = 100;
    }

    CurrentErrorRatePanel->Caption = FloatToStrF(ErrorRate, ffFixed, 10, 2) + "%";
    CurrentCameraBrightnessPanel->Caption = FloatToStrF(ErrorRate, ffFixed, 10, 2) + "%";

    CameraTestResultData[cameraIndex - 1].AverageErrorRate = ErrorRate;
    CameraTestResultData[cameraIndex - 1].AverageColor[0] = averageColor[0];
    CameraTestResultData[cameraIndex - 1].AverageColor[1] = averageColor[1];
    CameraTestResultData[cameraIndex - 1].AverageColor[2] = averageColor[2];
  }

  if(MinDiffLevel != 0x0FFFFFFF)
  {
    CurrentCameraMinDiffBrightnessPanel->Color = (TColor)((MinDiffColor[0] << 16) + (MinDiffColor[1] << 8) + MinDiffColor[2]);

    if(maxErrorSize)
    {
      ErrorRate = MinDiffLevel * 100 / (float)maxErrorSize;
    }
    else
    {
      ErrorRate = 100;
    }

    CurrentCameraMinDiffBrightnessPanel->Caption = FloatToStrF(ErrorRate, ffFixed, 10, 2) + "%";

    CameraTestResultData[cameraIndex - 1].MinErrorRate = ErrorRate;
    CameraTestResultData[cameraIndex - 1].MinDiffBrightnessColor[0] = MinDiffColor[0];
    CameraTestResultData[cameraIndex - 1].MinDiffBrightnessColor[1] = MinDiffColor[1];
    CameraTestResultData[cameraIndex - 1].MinDiffBrightnessColor[2] = MinDiffColor[2];
  }

  if(MaxDiffLevel != 0)
  {
    CurrentCameraMaxDiffBrightnessPanel->Color = (TColor)((MaxDiffColor[0] << 16) + (MaxDiffColor[1] << 8) + MaxDiffColor[2]);

    if(maxErrorSize)
    {
      ErrorRate = MaxDiffLevel * 100 / (float)maxErrorSize;
    }
    else
    {
      ErrorRate = 100;
    }

    CurrentCameraMaxDiffBrightnessPanel->Caption = FloatToStrF(ErrorRate, ffFixed, 10, 2) + "%";

    CameraTestResultData[cameraIndex - 1].MaxErrorRate = ErrorRate;
    CameraTestResultData[cameraIndex - 1].MaxDiffBrightnessColor[0] = MaxDiffColor[0];
    CameraTestResultData[cameraIndex - 1].MaxDiffBrightnessColor[1] = MaxDiffColor[1];
    CameraTestResultData[cameraIndex - 1].MaxDiffBrightnessColor[2] = MaxDiffColor[2];
  }

  CameraTestResultData[cameraIndex - 1].FailCount = globalCameraFailCount;
}
//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::ResultPanel9Click(TObject *Sender)
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    TTntPanel *CameraComponent = (TTntPanel *) FindComponent("ResultPanel" + IntToStr(globalCameraIndex + 1));
    if(CameraTestResultData[globalCameraIndex].CheckSW)
    {
      if(CameraTestResultData[globalCameraIndex].AverageErrorRate > CameraCheckOption.ErrorRate)
      {
        if(CameraComponent)
        {
          CameraComponent->Color = clRed;
        }
      }
      else
      {
        if(CameraComponent)
        {
          CameraComponent->Color = clLime;
        }
      }
    }
    else
    {
      if(CameraComponent)
      {
        CameraComponent->Color = clDkGray;
      }
    }
  }

  TTntPanel *selectedPanel = (TTntPanel*)Sender;

  int cameraIndex = selectedPanel->Tag;
  LoadFinalResultData(cameraIndex);
  selectedPanel->Color = clYellow;

  AnsiString ConvertString = ConvertCameraIndex(cameraIndex - 1);
  MeasuringResultGroupBox->Caption = CAMERATEST_FORM_TEXT_10 + "(" + ConvertString + ")";
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::LoadFinalResultData(int cameraIndex)
{
  CurrentFailCountPanel->Caption = IntToStr(CameraTestResultData[cameraIndex - 1].FailCount);

  float ErrorRate;
  int averageColor[3];
  averageColor[0] = CameraTestResultData[cameraIndex - 1].AverageColor[0];
  averageColor[1] = CameraTestResultData[cameraIndex - 1].AverageColor[1];
  averageColor[2] = CameraTestResultData[cameraIndex - 1].AverageColor[2];

  CurrentCameraBrightnessPanel->Color = (TColor)((averageColor[0] << 16) + (averageColor[1] << 8) + averageColor[2]);

  ErrorRate = CameraTestResultData[cameraIndex - 1].AverageErrorRate;

  CurrentErrorRatePanel->Caption = FloatToStrF(ErrorRate, ffFixed, 10, 2) + "%";
  CurrentCameraBrightnessPanel->Caption = FloatToStrF(ErrorRate, ffFixed, 10, 2) + "%";

  if(CameraTestResultData[cameraIndex - 1].AverageErrorRate > CameraCheckOption.ErrorRate)
  {
    CurrentStatusPanel->Caption = CAMERATEST_FORM_TEXT_29;
  }
  else
  {
    CurrentStatusPanel->Caption = CAMERATEST_FORM_TEXT_30;
  }

  MinDiffColor[0] = CameraTestResultData[cameraIndex - 1].MinDiffBrightnessColor[0];
  MinDiffColor[1] = CameraTestResultData[cameraIndex - 1].MinDiffBrightnessColor[1];
  MinDiffColor[2] = CameraTestResultData[cameraIndex - 1].MinDiffBrightnessColor[2];

  CurrentCameraMinDiffBrightnessPanel->Color = (TColor)((MinDiffColor[0] << 16) + (MinDiffColor[1] << 8) + MinDiffColor[2]);

  ErrorRate = CameraTestResultData[cameraIndex - 1].MinErrorRate;
  CurrentCameraMinDiffBrightnessPanel->Caption = FloatToStrF(ErrorRate, ffFixed, 10, 2) + "%";

  MaxDiffColor[0] = CameraTestResultData[cameraIndex - 1].MaxDiffBrightnessColor[0];
  MaxDiffColor[1] = CameraTestResultData[cameraIndex - 1].MaxDiffBrightnessColor[1];
  MaxDiffColor[2] = CameraTestResultData[cameraIndex - 1].MaxDiffBrightnessColor[2];

  CurrentCameraMaxDiffBrightnessPanel->Color = (TColor)((MaxDiffColor[0] << 16) + (MaxDiffColor[1] << 8) + MaxDiffColor[2]);

  ErrorRate = CameraTestResultData[cameraIndex - 1].MaxErrorRate;
  CurrentCameraMaxDiffBrightnessPanel->Caption = FloatToStrF(ErrorRate, ffFixed, 10, 2) + "%";

  SetGaugeRange(cameraIndex - 1);

  if(CameraMapInfo[cameraIndex - 1].CameraInspectPosition == CAMERA_POSITION_3D)
  {
    InitImageComponent(CurrentImage, ImageWidth[1], ImageHeight[1]);
    InitImageComponent(MinBrightnessResultImage, ImageWidth[1], ImageHeight[1]);
    InitImageComponent(MaxBrightnessResultImage, ImageWidth[1], ImageHeight[1]);
  }
  else
  {
    InitImageComponent(CurrentImage, ImageWidth[0], ImageHeight[0]);
    InitImageComponent(MinBrightnessResultImage, ImageWidth[0], ImageHeight[0]);
    InitImageComponent(MaxBrightnessResultImage, ImageWidth[0], ImageHeight[0]);
  }

  GaugeImage1->Canvas->Pen->Width = 1;
  GaugeImage1->Canvas->Pen->Color = clBlack;

  for(int m = 0; m < 256; m++)
  {
    if(StudyResultData[cameraIndex - 1][0][m])
    {
      int count = StudyResultData[cameraIndex - 1][0][m];
      int pos = max(10, 70 - 10 * count);  

      GaugeImage1->Canvas->MoveTo(m, 70);
      GaugeImage1->Canvas->LineTo(m, pos);
    }
  }

  GaugeImage1->Refresh();

  GaugeImage2->Canvas->Pen->Width = 1;
  GaugeImage2->Canvas->Pen->Color = clBlack;

  for(int m = 0; m < 256; m++)
  {
    if(StudyResultData[cameraIndex - 1][1][m])
    {
      int count = StudyResultData[cameraIndex - 1][1][m];
      int pos = max(10, 70 - 10 * count);

      GaugeImage2->Canvas->MoveTo(m, 70);
      GaugeImage2->Canvas->LineTo(m, pos);
    }
  }

  GaugeImage2->Refresh();

  GaugeImage3->Canvas->Pen->Width = 1;
  GaugeImage3->Canvas->Pen->Color = clBlack;

  for(int m = 0; m < 256; m++)
  {
    if(StudyResultData[cameraIndex - 1][2][m])
    {
      int count = StudyResultData[cameraIndex - 1][2][m];
      int pos = max(10, 70 - 10 * count);

      GaugeImage3->Canvas->MoveTo(m, 70);
      GaugeImage3->Canvas->LineTo(m, pos);
    }
  }

  GaugeImage3->Refresh();

  int width, height;
  if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX || cameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX)
  {
    width = ImageWidth[1];
    height = ImageHeight[1];
  }
  else
  {
    width = ImageWidth[0];
    height = ImageHeight[0];
  }
      
  int x, y;
  Graphics::TBitmap *img1;
  img1 = new Graphics::TBitmap();
  img1->Width = width;
  img1->Height = height;
  img1->PixelFormat = pf24bit;

  Byte *ptr;
  for(y = 0 ; y < height; y++)
  {
    ptr = (byte*) img1->ScanLine[y];
    for(x = 0; x < width; x++)
    {
      int tempAddress = width * y + x;

      ptr[3*x+0] = minBrightnessImage[cameraIndex - 1][tempAddress * 3 + 0];
      ptr[3*x+1] = minBrightnessImage[cameraIndex - 1][tempAddress * 3 + 1];
      ptr[3*x+2] = minBrightnessImage[cameraIndex - 1][tempAddress * 3 + 2];
    }
  }

  MinBrightnessResultImage->Picture->Bitmap->Assign(img1);
  MinBrightnessResultImage->Refresh();

  for(y = 0 ; y < height; y++)
  {
    ptr = (byte*) img1->ScanLine[y];
    for(x = 0; x < width; x++)
    {
      int tempAddress = width * y + x;

      ptr[3*x+0] = maxBrightnessImage[cameraIndex - 1][tempAddress * 3 + 0];
      ptr[3*x+1] = maxBrightnessImage[cameraIndex - 1][tempAddress * 3 + 1];
      ptr[3*x+2] = maxBrightnessImage[cameraIndex - 1][tempAddress * 3 + 2];
    }
  }

  MaxBrightnessResultImage->Picture->Bitmap->Assign(img1);
  MaxBrightnessResultImage->Refresh();

  delete(img1);
}
//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::StopButtonClick(TObject *Sender)
{
  bStop = true;
}
//---------------------------------------------------------------------------

bool __fastcall TCameraTestForm::CheckCameraParams()
{
  bool returnValue = true;

  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    if(SystemLinkCameraInfo[globalCameraIndex])
    {
      TTntPanel *CameraComponent;
      CameraComponent = (TTntPanel *) FindComponent("CameraStatusPanel" + IntToStr(globalCameraIndex+1));
      if(CameraComponent)
      {
        if(CameraComponent->Caption == WideString("X"))
        {
          returnValue = false;
          break;
        }
      }
    }
  }

  return returnValue;
}
//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::MinBrightnessResultImageDblClick(
      TObject *Sender)
{
  if(MeasuringTimer->Enabled == false)
  {
    CurrentImage->Picture->Bitmap->Assign(MinBrightnessResultImage->Picture->Bitmap);
    CurrentImage->Refresh();
  }
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::MaxBrightnessResultImageDblClick(
      TObject *Sender)
{
  if(MeasuringTimer->Enabled == false)
  {
    CurrentImage->Picture->Bitmap->Assign(MaxBrightnessResultImage->Picture->Bitmap);
    CurrentImage->Refresh();
  }
}
//---------------------------------------------------------------------------

void __fastcall TCameraTestForm::GetDefaultString()
{
  StartButton->Caption = CAMERATEST_FORM_TEXT_01;
  StopButton->Caption = CAMERATEST_FORM_TEXT_02;
  SpeedControlButton->Caption = CAMERATEST_FORM_TEXT_03;
  OptionButton->Caption = CAMERATEST_FORM_TEXT_04;
  ExitButton->Caption = CAMERATEST_FORM_TEXT_05;
  GroupBox4->Caption = CAMERATEST_FORM_TEXT_06;
  TntGroupBox1->Caption = CAMERATEST_FORM_TEXT_07;
  TntGroupBox2->Caption = CAMERATEST_FORM_TEXT_08;
  TntGroupBox3->Caption = CAMERATEST_FORM_TEXT_09;
  MeasuringResultGroupBox->Caption = CAMERATEST_FORM_TEXT_10;
  Panel1->Caption = CAMERATEST_FORM_TEXT_11;
  Panel2->Caption = CAMERATEST_FORM_TEXT_12;
  Panel3->Caption = CAMERATEST_FORM_TEXT_13;
  Panel4->Caption = CAMERATEST_FORM_TEXT_14;
  TntPanel14->Caption = CAMERATEST_FORM_TEXT_15;
  TntPanel11->Caption = CAMERATEST_FORM_TEXT_16;
  TntPanel12->Caption = CAMERATEST_FORM_TEXT_12;
  TntPanel13->Caption = CAMERATEST_FORM_TEXT_13;
  TntPanel17->Caption = CAMERATEST_FORM_TEXT_17;
  TntPanel19->Caption = CAMERATEST_FORM_TEXT_18;
  TntPanel1->Caption = CAMERATEST_FORM_TEXT_19;
  TntPanel5->Caption = CAMERATEST_FORM_TEXT_20;
  TntPanel9->Caption = CAMERATEST_FORM_TEXT_21;
  TntPanel10->Caption = CAMERATEST_FORM_TEXT_22;
  TntPanel21->Caption = CAMERATEST_FORM_TEXT_23;
  SetupButton->Caption = CAMERATEST_FORM_TEXT_05;
}
//---------------------------------------------------------------------------
void __fastcall TCameraTestForm::FormActivate(TObject *Sender)
{
  SetScreenPosition(this);
}
//---------------------------------------------------------------------------

