//---------------------------------------------------------------------------
// For SELMA200, 20180223, moon, 완료
// CameraIndex 관련 수정 완료
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "cpb_module.h"
#include "Study_Form.h"
#include "Message_Form.h"
#include "Environment.h"
#include "Keyboard_Form.h"
#include "Waiting_Form.h"
#include "Bayer.h"
#include "InputText_Dialog.h"
#include "Setup_Form.h"
#include "MachineControl.h"
#include "MultiLanguage.h"
#include "inifiles.hpp"
#include "Main_Form.h"

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

  NoticePaenl2DCameraColorInfo1->Caption = STUDYFORM_FORM_CAPTION_02;
  NoticePanel3D1->Caption = STUDYFORM_FORM_CAPTION_03;
  NoticePanelDisk1Engrave->Caption = STUDYFORM_FORM_CAPTION_04;
  NoticePanelDisk1Result->Caption = STUDYFORM_FORM_CAPTION_05;
  ColorInfoName1->Caption = STUDYFORM_FORM_CAPTION_06;
  EngraveInfoName1->Caption = STUDYFORM_FORM_CAPTION_07;
  ThicknessInfoName1->Caption = STUDYFORM_FORM_CAPTION_08;

  NoticePaenl2DCameraColorInfo2->Caption = STUDYFORM_FORM_CAPTION_09;
  NoticePanel3D2->Caption = STUDYFORM_FORM_CAPTION_10;
  NoticePanelDisk2Engrave->Caption = STUDYFORM_FORM_CAPTION_11;
  NoticePanelDisk2Result->Caption = STUDYFORM_FORM_CAPTION_12;
  ColorInfoName2->Caption = STUDYFORM_FORM_CAPTION_06;
  EngraveInfoName2->Caption = STUDYFORM_FORM_CAPTION_07;
  ThicknessInfoName2->Caption = STUDYFORM_FORM_CAPTION_08;

  /*
  Panel50->Visible = false;
  Panel53->Visible = false;
  Panel56->Visible = false;
  Panel107->Visible = false;
  Panel111->Visible = false;
  Panel118->Visible = false;
  */

  ColorValuePanel1->Visible = false;
  ColorValuePanel2->Visible = false;

	ThresholdGroupBox1->Visible = false;
	ThresholdGroupBox2->Visible = false;
	ThresholdGroupBox3->Visible = false;
	ThresholdGroupBox4->Visible = false;
	HeightGroupBox1->Visible = false;
	HeightGroupBox2->Visible = false;

	StudyResultPanel->BringToFront();
	CameraTestStatus[TEST_CAMERA_1_INDEX] = CameraTestStatus[TEST_CAMERA_9_INDEX] = ECTS_NONE;
	CameraEvalValue[TEST_CAMERA_1_INDEX] = CameraEvalValue[TEST_CAMERA_9_INDEX] = 0;

	Disk1CaptureGroupBox->DoubleBuffered = true;

	// set current index to camera 1
	CurrentCamGlobalIndex = 0;
	CurrentCamListIndex = TEST_CAMERA_1_INDEX;

	IsBrightnessCheckMode = false;
	Study2MenuPanel->Visible = true;
  TLMenuPanel->Visible = false;

	ImageEvalCount = 0;

  if (ProgramAccessAuthorityData.ProgramAccessAuthorityTable[UserInfo.AccessLevel][ACCESS_PGM_EVT_SEC_STUDY_FORM_ADJUST_VALUE])
	{
		SetDiskBasisValueButton->Visible = true;
		SecretPanel->Enabled = true;
	}
	else
	{
		SetDiskBasisValueButton->Visible = false;
		SecretPanel->Enabled = true;
	}

  if(ProductData.SubSamplingMode == IMAGE_FULL_SCALE_MODE)
  {
    ImageWidth = SYSTEM_CAMERA_HD_WIDTH;
    ImageHeight = SYSTEM_CAMERA_HD_HEIGHT;
  }
  else
  {
    ImageWidth = SYSTEM_CAMERA_WIDTH;
    ImageHeight = SYSTEM_CAMERA_HEIGHT;
  }

	CameraImage->Picture->Bitmap->Width = ImageWidth;
	CameraImage->Picture->Bitmap->Height = ImageHeight;
	CameraImage->Picture->Bitmap->PixelFormat = pf24bit;

  if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE1)
  {
    Label6->Visible =false;
  }
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::GetDefaultString()
{
	SetDiskBasisValueButton->Caption = STUDYFORM_BUTTON_CAPTION_01;
	BrightnessTestButton->Caption = STUDYFORM_BUTTON_CAPTION_02;
	ImageEvalStartButton->Caption = STUDYFORM_BUTTON_CAPTION_03;
	StudyStartButton->Caption = STUDYFORM_BUTTON_CAPTION_04;
	StudyStopButton->Caption = STUDYFORM_BUTTON_CAPTION_05;
	this->Caption = STUDYFORM_FORM_CAPTION_01;
	GroupBox1->Caption = STUDYFORM_GROUPBOX_CAPTION_01;
	Camera9SelectPanel->Caption = STUDYFORM_GROUPBOX_CAPTION_02;

	HeightGroupBox1->Caption = STUDYFORM_GROUPBOX_CAPTION_06;
	HeightGroupBox2->Caption = STUDYFORM_GROUPBOX_CAPTION_06;
	GroupBox6->Caption = STUDYFORM_GROUPBOX_CAPTION_07;
	GroupBox4->Caption = STUDYFORM_GROUPBOX_CAPTION_08;
	GroupBox2->Caption = STUDYFORM_GROUPBOX_CAPTION_09;
	Disk1CaptureGroupBox->Caption = STUDYFORM_GROUPBOX_CAPTION_10;
	Label9->Caption = STUDYFORM_LABEL_CAPTION_01;
	Label10->Caption = STUDYFORM_LABEL_CAPTION_02;
	InformationLabel1->Caption = STUDYFORM_LABEL_CAPTION_03;
	Label7->Caption = STUDYFORM_LABEL_CAPTION_04;
	Label8->Caption = STUDYFORM_LABEL_CAPTION_05;
	InformationLabel2->Caption = STUDYFORM_LABEL_CAPTION_08;
	Label6->Caption = STUDYFORM_LABEL_CAPTION_11;
	HeightThresholdLabel_Disc1->Caption = STUDYFORM_LABEL_CAPTION_13;
	ThresholdLabel_ForCam1_A->Caption = STUDYFORM_LABEL_CAPTION_13;
	ThresholdLabel_ForCam5_A->Caption = STUDYFORM_LABEL_CAPTION_13;
	ThresholdLabel_ForCam1_B->Caption = STUDYFORM_LABEL_CAPTION_13;
	ThresholdLabel_ForCam5_B->Caption = STUDYFORM_LABEL_CAPTION_13;
	ThresholdLabel_ForCam9_A->Caption = STUDYFORM_LABEL_CAPTION_13;
	ThresholdLabel_ForCam13_A->Caption = STUDYFORM_LABEL_CAPTION_13;
	ThresholdLabel_ForCam9_B->Caption = STUDYFORM_LABEL_CAPTION_13;
	ThresholdLabel_ForCam13_B->Caption = STUDYFORM_LABEL_CAPTION_13;
	HeightThresholdLabel_Disc2->Caption = STUDYFORM_LABEL_CAPTION_13;

	Camera1EvalValueLabel->Caption = STUDYFORM_LABEL_CAPTION_14;
	Camera9EvalValueLabel->Caption = STUDYFORM_LABEL_CAPTION_14;
	InstructionLabel1->Caption = STUDYFORM_LABEL_CAPTION_16;
	StudyCountSetLabel->Caption = STUDYFORM_LABEL_CAPTION_18;
	Camera1SelectPanel->Caption = STUDYFORM_PANEL_CAPTION_01;
	Camera9SelectPanel->Caption = STUDYFORM_PANEL_CAPTION_02;

	//add
	ThresholdGroupBox1->Caption = STUDYFORM_ADD_01;
	ThresholdGroupBox3->Caption = STUDYFORM_ADD_01;
	ThresholdGroupBox2->Caption = STUDYFORM_ADD_02;
	ThresholdGroupBox4->Caption = STUDYFORM_ADD_02;

    CloseButton->Caption = STUDYFORM_BUTTON_CAPTION_06;
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::StudyStartButtonClick(TObject *Sender)
{
  // 이미지 영역 확인
  memset(ThreeDParamSetSatus,0,sizeof(int)*2);

  bool bErrorCamera[SYSTEM_TOTAL_CAMERA_COUNT];
  if(checkCameraArea(&ProductData, bErrorCamera))
  {
    AnsiString ErrorString;
    AnsiString nextString;
    ErrorString = "Incorrect Camera Area (CAM No.";

    int errorCameraCount = 0;
    for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if(bErrorCamera[globalCameraIndex]) errorCameraCount++;
    }
    
    for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if(bErrorCamera[globalCameraIndex])
      {
        errorCameraCount--;
        if(errorCameraCount)
        {
          ErrorString += IntToStr(globalCameraIndex + 1) + ", ";
        }
        else
        {
          ErrorString += IntToStr(globalCameraIndex + 1) + ")";
        }
      }
    }

    ShowMessageFA(ErrorString);
    return;
  }
  //// end
  
	float tabletHalfLength = ProductData.TabletLength / 2;

  if (!SimulationInspectionCheckBox->Checked)
  {
    // check machine interlock
    if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE1)
    {
      if(MachineSetupData.InterlockInfo.ACdomesticMode)
      {
        if (MachineSetupData.InterlockInfo.DoorInterlockEnabled)
        {
          if (!Machine.InterlockCheck())
          {
            ShowMessageFA(Machine.GetInterlockMessage());
            return;
          }
        }
      }
      else
      {
        if (!Machine.InterlockCheck())
        {
          ShowMessageFA(Machine.GetInterlockMessage());
          return;
        }
      }
    }
    else
    {
      if (MachineSetupData.InterlockInfo.DoorInterlockEnabled)
      {
        if (!Machine.InterlockCheck())
        {
          ShowMessageFA(Machine.GetInterlockMessage());
          return;
        }
      }
    }

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

  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;
  }
  
	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
		// 2015-10-29 revision by moon
		// 색상 학습 버그 확인. 2차 학습 진행 시 색상 관련 변수 초기화
		Comm_Request(COMM_SPB + spbIndex, CMD_INSPECTION_CLEAR);
	}

	bool cpbRunning = false;
	int spbRunCount = 0;
	int spbRemainCount = 0;
	TCPBRunStatus cpbRunStatus;

  if (!SimulationInspectionCheckBox->Checked)
  {
    for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
    {
      Comm_Request(COMM_SPB + spbIndex, CMD_RUN_INFO, NULL, 0, &cpbRunStatus, sizeof(TCPBRunStatus));
      if (cpbRunStatus.Running)
      {
        spbRunCount += cpbRunStatus.CurrentCPBIndex;
        spbRemainCount += (SYSTEM_CPB_COUNT - cpbRunStatus.CurrentCPBIndex);
        cpbRunning = true;
      }
      else
      {
        if (spbIndex == 0 || spbIndex == 1)
        {
          spbRunCount += 32;
        }
        else
        {
          spbRunCount += 40;
        }
      }
    }

    if (cpbRunning)
    {
      WCHAR TempStr[100];
      wsprintfW(TempStr, STUDYFORM_MSG_05, spbRunCount * 100 / (32 + 32 + 40 + 40));
      ShowMessageFA(TempStr);
      return;
    }
  }

	// White Balance 값 전송
	AnsiString fileName;
	fileName = ProgramPath.Env + "\\WhiteBalanceInfo.ini";
	for (int cameraIndex = 0; cameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; cameraIndex++)
	{
		ReadCameraWhiteBalanceColorInfo(fileName, cameraIndex);
	}

	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
		Comm_Request(COMM_SPB + spbIndex, CMD_SET_CAMERA_WHITE_BALANCE, WhiteBalanceInfo, sizeof(TWhiteBalanceInfo) * SYSTEM_TOTAL_CAMERA_COUNT);
	}
	// White Balance 값 전송 완료

  if (SimulationInspectionCheckBox->Checked)
	{
		SetSPBVirtualInspectionImage();

		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
			Comm_Request(COMM_SPB + spbIndex, CMD_VIRTUAL_DEBUGGING_DATA4);
		}

		int buff;

		buff = 100; // interval 100ms

		Comm_Request(COMM_HCB, CMD_ALARM_RESET);
		Comm_Request(COMM_HCB, CMD_VIRTUAL_INSPECTION_START, &buff, sizeof(int));
	}
  
	if (!SendStudySetupData())
	{
		return;
	}

  // start machine
	int motorSpeedList[MAX_SERVO_MOTOR_COUNT];
	for (int motorIndex = 0; motorIndex < MAX_SERVO_MOTOR_COUNT; motorIndex++)
	{
    // 2019-08-07
    // 기본 세팅 속도로 학습을 진행하는 경우 100% 석션 속도가 아닌 상태로 학습이 진행될 수 가 있는데
    // 이때 3D 영상이 비정상인 경우가 발생 하였음(아젠타)
    // 이경우 기본 석션속도가 80으로 세팅되어있는데 이 상태에서 line scan frq 계산값이 적용되면서 3D 이미지가 정상적이지 않은 경우가 발생함
    // 기본적으로는 line scan frq 계산 방법을 변경해야하나 많은 테스트가 필요함
    // 이미지 촬영 당시 정상적으로 찍혔던 상태인 100% 혹은 학습속도에서 2차학습이 진행되도록 변경함
		motorSpeedList[motorIndex] = ProductData.StudyMotorSpeedList[motorIndex][0];     
	}
  
	SendStudyReadyCommand(motorSpeedList[SD1_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed,
		motorSpeedList[SD2_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed);

	struct
	{
		int SuctionDiskSpeed;
		int StudiedTabletSensor1Length;
		int StudiedTabletSensor2Length;
		int studiedSensorIntervalA;
		int studiedSensorIntervalB;
		int studyOption;
		int TabletSideThick;
	} hcbStudySetupData;

	hcbStudySetupData.SuctionDiskSpeed = motorSpeedList[SD1_MOTOR_INDEX];
	hcbStudySetupData.StudiedTabletSensor1Length = ProductData.StudiedSensor1Length;
	hcbStudySetupData.StudiedTabletSensor2Length = ProductData.StudiedSensor2Length;
	//sjm add 깨진정제 ..
	//hcbStudySetupData.StudiedTabletSensor3Length = ProductData.StudiedSensor3Length;
	hcbStudySetupData.studiedSensorIntervalA = ProductData.StudiedSensorIntervalA;
	hcbStudySetupData.studiedSensorIntervalB = ProductData.StudiedSensorIntervalB;
	hcbStudySetupData.studyOption = 0;
	hcbStudySetupData.TabletSideThick = ProductData.TabletSideThick*10;
	if (!Comm_Request(COMM_HCB, CMD_STUDY_READY, &hcbStudySetupData, sizeof(hcbStudySetupData)))
	{
		//ShowMessageFA(HCBConnection.GetLastErrorMessage());
	}

	Machine.MachineRun(PROCEDURE_MODE_STUDY, &ProductData.MachineRunOption, ProductData.NCMotorPos, motorSpeedList);

  if (SimulationInspectionCheckBox->Checked)
  {
    for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if ((CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_DISCONNECT) || (SystemLinkCameraInfo[globalCameraIndex] == 0))
      {
        StudyComplete[globalCameraIndex] = true;
      }
      else if(ProductData.TabletType == TABLET_TYPE_SUGAR_COATED && (globalCameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                      globalCameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                      globalCameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                      globalCameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1))
      {
        StudyComplete[globalCameraIndex] = true;
      }
      else
      {
        if (Comm_IsConnected(COMM_SPB + CameraMapInfo[globalCameraIndex].SPBIndex))
        {
          StudyComplete[globalCameraIndex] = false;
        }
        else
        {
          StudyComplete[globalCameraIndex] = true;
        }
      }
    }
  }
  else
  {
    for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if ((CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_DISCONNECT) || (SystemLinkCameraInfo[globalCameraIndex] == 0))
      {
        StudyComplete[globalCameraIndex] = true;
      }
      else if(ProductData.TabletType == TABLET_TYPE_SUGAR_COATED && (globalCameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                      globalCameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                      globalCameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                      globalCameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1))
      {
        StudyComplete[globalCameraIndex] = true;
      }
      else
      {
        StudyComplete[globalCameraIndex] = false;
      }
    }
  }

	StudyStartButton->Enabled = false;
	StudyStopButton->Enabled = true;
	StudyResultTimer->Enabled = true;

  /*
	Panel50->Visible = false;
  Panel53->Visible = false;
  Panel56->Visible = false;
  Panel107->Visible = false;
  Panel111->Visible = false;
  Panel118->Visible = false;
  */

  ColorValuePanel1->Visible = false;
  ColorValuePanel2->Visible = false;

	ThresholdGroupBox1->Visible = false;
	ThresholdGroupBox2->Visible = false;
	ThresholdGroupBox3->Visible = false;
	ThresholdGroupBox4->Visible = false;
	HeightGroupBox1->Visible = false;
	HeightGroupBox2->Visible = false;

	StudyProgressBar->Position = 0;
	StudyCountLabel->Caption = "";
	StudyProgressBar->Visible = true;
	StudyCountLabel->Visible = true;

	BrightnessTestButton->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::StudyStopButtonClick(TObject *Sender)
{
	bool bError = false;
	Machine.MachineStop();

	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
		if (!Comm_Request(COMM_SPB + spbIndex, CMD_STUDY_END))
		{
			bError = true;
		}
	}

	if (!Comm_Request(COMM_HCB, CMD_STUDY_END))
	{
		bError = true;
	}

	if (bError)
	{
		//Message
	}

	StudyStartButton->Enabled = true;
	StudyStopButton->Enabled = false;

	StudyResultTimer->Enabled = false;
	BrightnessTestButton->Enabled = true;
}
//---------------------------------------------------------------------------

void __fastcall TStudyForm::StudyResultTimerTimer(TObject *Sender)
{
	TStudyResultData_SPB studyResultData;
	int minStudyCount = StudyCount;
	bool bStudyAllComplete = true;
	for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
	{
		if (StudyComplete[globalCameraIndex])
		{
			continue;
		}
		else
		{
			bStudyAllComplete = false;
		}

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

		if (!Comm_Request(COMM_SPB + spbIndex, CMD_STUDY_RESULT, &camIndex, sizeof(camIndex),
			&studyResultData, sizeof(TStudyResultData_SPB)))
		{

		}
		else
		{
			if (globalCameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX - 1)
			{
				TabletColorChart1->Series[0]->Clear();
				TabletColorChart1->Series[1]->Clear();
				TabletColorChart1->Series[2]->Clear();
				for (int dataIndex = 0; dataIndex < 256; dataIndex++)
				{
					TabletColorChart1->Series[0]->Add(studyResultData.ColorB[dataIndex]);
					TabletColorChart1->Series[1]->Add(studyResultData.ColorG[dataIndex]);
					TabletColorChart1->Series[2]->Add(studyResultData.ColorR[dataIndex]);
				}

				if (IsTwoColor)
				{
					TabletRearColorChart1->Series[0]->Clear();
					TabletRearColorChart1->Series[1]->Clear();
					TabletRearColorChart1->Series[2]->Clear();

					for (int dataIndex = 0; dataIndex < 256; dataIndex++)
					{
						TabletRearColorChart1->Series[0]->Add(studyResultData.RearColorB[dataIndex]);
						TabletRearColorChart1->Series[1]->Add(studyResultData.RearColorG[dataIndex]);
						TabletRearColorChart1->Series[2]->Add(studyResultData.RearColorR[dataIndex]);
					}
				}

				TabletEngraveChart1->Series[0]->Clear();
				TabletEngraveChart1->Series[1]->Clear();
				for (int dataIndex = 0; dataIndex < 3000; dataIndex++)
				{
					TabletEngraveChart1->Series[0]->Add(studyResultData.PrintMatchingValue1[dataIndex]);
					TabletEngraveChart1->Series[1]->Add(studyResultData.PrintMatchingValue2[dataIndex]);
				}
			}
			else if (globalCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
			{
				TabletEngraveChart2->Series[0]->Clear();
				TabletEngraveChart2->Series[1]->Clear();
				for (int dataIndex = 0; dataIndex < 2000; dataIndex++)
				{
					TabletEngraveChart2->Series[0]->Add(studyResultData.PrintMatchingValue1[dataIndex]);
					TabletEngraveChart2->Series[1]->Add(studyResultData.PrintMatchingValue2[dataIndex]);
				}
				TabletHeightChart1->Series[0]->Clear();
				TabletHeightChart1->Series[1]->Clear();
				for (int dataIndex = 0; dataIndex < 256; dataIndex++)
				{
					TabletHeightChart1->Series[0]->Add(studyResultData.ThreeDMaxHeight1[dataIndex]);
				}
			}
			else if (globalCameraIndex == SD2_2D_FRONT_FACE_CAMERA_INDEX - 1)
			{
				TabletColorChart2->Series[0]->Clear();
				TabletColorChart2->Series[1]->Clear();
				TabletColorChart2->Series[2]->Clear();
				for (int dataIndex = 0; dataIndex < 256; dataIndex++)
				{
					TabletColorChart2->Series[0]->Add(studyResultData.ColorB[dataIndex]);
					TabletColorChart2->Series[1]->Add(studyResultData.ColorG[dataIndex]);
					TabletColorChart2->Series[2]->Add(studyResultData.ColorR[dataIndex]);
				}

				if (IsTwoColor)
				{
					TabletRearColorChart2->Series[0]->Clear();
					TabletRearColorChart2->Series[1]->Clear();
					TabletRearColorChart2->Series[2]->Clear();
					for (int dataIndex = 0; dataIndex < 256; dataIndex++)
					{
						TabletRearColorChart2->Series[0]->Add(studyResultData.RearColorB[dataIndex]);
						TabletRearColorChart2->Series[1]->Add(studyResultData.RearColorG[dataIndex]);
						TabletRearColorChart2->Series[2]->Add(studyResultData.RearColorR[dataIndex]);
					}
				}

				TabletEngraveChart3->Series[0]->Clear();
				TabletEngraveChart3->Series[1]->Clear();
				for (int dataIndex = 0; dataIndex < 3000; dataIndex++)
				{
					TabletEngraveChart3->Series[0]->Add(studyResultData.PrintMatchingValue1[dataIndex]);
					TabletEngraveChart3->Series[1]->Add(studyResultData.PrintMatchingValue2[dataIndex]);
				}
			}
			else if (globalCameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX - 1)
			{
				TabletEngraveChart4->Series[0]->Clear();
				TabletEngraveChart4->Series[1]->Clear();
				for (int dataIndex = 0; dataIndex < 2000; dataIndex++)
				{
					TabletEngraveChart4->Series[0]->Add(studyResultData.PrintMatchingValue1[dataIndex]);
					TabletEngraveChart4->Series[1]->Add(studyResultData.PrintMatchingValue2[dataIndex]);
				}
				TabletHeightChart2->Series[0]->Clear();
				TabletHeightChart2->Series[1]->Clear();
				for (int dataIndex = 0; dataIndex < 256; dataIndex++)
				{
					TabletHeightChart2->Series[0]->Add(studyResultData.ThreeDMaxHeight2[dataIndex]);
				}
			}
      else
			{
        // Side Camera
        TChart *SideCameraColorChart;
        SideCameraColorChart = (TChart *)FindComponent("TabletColorChartSideCam" + IntToStr(globalCameraIndex + 1));

        if(SideCameraColorChart)
        {
          SideCameraColorChart->Series[0]->Clear();
          SideCameraColorChart->Series[1]->Clear();
          SideCameraColorChart->Series[2]->Clear();
          for (int dataIndex = 0; dataIndex < 256; dataIndex++)
          {
            SideCameraColorChart->Series[0]->Add(studyResultData.ColorB[dataIndex]);
            SideCameraColorChart->Series[1]->Add(studyResultData.ColorG[dataIndex]);
            SideCameraColorChart->Series[2]->Add(studyResultData.ColorR[dataIndex]);
          }
        }
      }

			if (minStudyCount > studyResultData.DataCount)
			{
				minStudyCount = studyResultData.DataCount;
			}
			if (studyResultData.DataCount >= StudyCount)
			{
				FinalStudyResult[globalCameraIndex] = studyResultData;
				StudyComplete[globalCameraIndex] = true;
			}
		}
	}
	if (bStudyAllComplete)
	{
    if (SimulationInspectionCheckBox->Checked)
		{
			Comm_Request(COMM_HCB, CMD_VIRTUAL_INSPECTION_END, NULL, 0);

			for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
			{
				Comm_Request(COMM_SPB + spbIndex, CMD_VIRTUAL_DEBUGGING_DATA5);
			}
		}

		StudyProgressBar->Position = 100;
		StudyCountLabel->Caption = IntToStr(StudyCount) + " / " + IntToStr(StudyCount);
		StudyResultTimer->Enabled = false;
		StudyStopButton->Click();
		ProcessStudyResult();
		AnsiString studyFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".stu";

		if (ProductData.ProcessingStep < TABLET_PROCESSING_STEP_STUDY_COMPLETE)
		{
			ProductData.ProcessingStep = TABLET_PROCESSING_STEP_STUDY_COMPLETE;
		}

    for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      ProductData.StudyShutterSpeed[globalCameraIndex] = ProductData.ShutterSpeed[globalCameraIndex];
      ProductData.StudyGainV[globalCameraIndex] = ProductData.DigitalGainV[globalCameraIndex];

      if(globalCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
      {
        if(ProductData.ExposureTime3D[0] != -1)
        {
          ProductData.StudyShutterSpeed[globalCameraIndex] = ProductData.ExposureTime3D[0];
          ProductData.StudyGainV[globalCameraIndex] = ProductData.AnalogGain3D[0];
        }
        else
        {
          ProductData.StudyShutterSpeed[globalCameraIndex] = ThreeDCameraDefaultInformation[globalCameraIndex].ExposureTime;
          ProductData.StudyGainV[globalCameraIndex] = ThreeDCameraDefaultInformation[globalCameraIndex].AnalogCameraGain;
        }
      }
      else if(globalCameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX - 1)
      {
        if(ProductData.ExposureTime3D[1] != -1)
        {
          ProductData.StudyShutterSpeed[globalCameraIndex] = ProductData.ExposureTime3D[1];
          ProductData.StudyGainV[globalCameraIndex] = ProductData.AnalogGain3D[1];
        }
        else
        {
          ProductData.StudyShutterSpeed[globalCameraIndex] = ThreeDCameraDefaultInformation[globalCameraIndex].ExposureTime;
          ProductData.StudyGainV[globalCameraIndex] = ThreeDCameraDefaultInformation[globalCameraIndex].AnalogCameraGain;
        }
      }
    }

		AnsiString fileName = GetProductDataFileName(ProductData.ProductCode);
		WriteProductData(fileName, ProductData);
		AddCSVActionLog(ECSV_ACTION_SECOND_STUDY, UserInfo.Name, ProductData.ProductName, NULL, 0);
		CPBSetupInfo.InspectionSetupDataValid = false;
		CPBSetupInfo.GradeDataValid = false;
		ShowMessageFA(STUDYFORM_MSG_08);
	}
	else
	{
		StudyProgressBar->Position = 100 * minStudyCount / StudyCount;
		StudyCountLabel->Caption = IntToStr(minStudyCount) + " / " + IntToStr(StudyCount);
	}
}
//---------------------------------------------------------------------------
bool __fastcall TStudyForm::SendStudySetupData(void)
{
	bool returnValue = true;

	if (!CPBSetupInfo.StudySetupDataValid)
	{
		TSetupForm *setupForm = new TSetupForm(this);
		
		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{

			setupForm->validSPBMask += (0x1<<spbIndex);
		}		
		setupForm->InitSetup(SETUP_MODE_STUDY);
		int modalResult = setupForm->ShowModal();
		delete setupForm;

		if (modalResult == mrOk)
		{
			CPBSetupInfo.StudySetupDataValid = true;
			CPBSetupInfo.InspectionSetupDataValid = false;
		}
		else
		{
			returnValue = false;
		}
	}

	return returnValue;
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::ProcessStudyResult(void)
{
	int maxCount, maxCountColor, globalCameraIndex;

	memset(&finalStudyResultData, 0, sizeof(TTabletStudyResultData));

	PastStudyComplete = 0;
	CurrentStudyComplete = 1;

	globalCameraIndex = SD1_2D_FRONT_FACE_CAMERA_INDEX - 1;
	if (CameraMapInfo[globalCameraIndex].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[globalCameraIndex] != 0)
	{
    // 정제 색상
		maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 0; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].ColorR[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].ColorR[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletColorR_ForCamera1 = maxCountColor;

		maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 0; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].ColorG[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].ColorG[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletColorG_ForCamera1 = maxCountColor;

		maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 0; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].ColorB[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].ColorB[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletColorB_ForCamera1 = maxCountColor;

    // 각인 색상
    maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 1; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].TabletPrintColorB[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].TabletPrintColorB[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletEngraveColorForCamera1[0] = maxCountColor;

    maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 1; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].TabletPrintColorG[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].TabletPrintColorG[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletEngraveColorForCamera1[1] = maxCountColor;

    maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 1; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].TabletPrintColorR[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].TabletPrintColorR[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletEngraveColorForCamera1[2] = maxCountColor;

		if (IsTwoColor)
		{
      // 정제 색상
			maxCount = 0;
			maxCountColor = 0;
			for (int dataIndex = 0; dataIndex < 256; dataIndex++)
			{
				if (maxCount < FinalStudyResult[globalCameraIndex].RearColorR[dataIndex])
				{
					maxCount = FinalStudyResult[globalCameraIndex].RearColorR[dataIndex];
					maxCountColor = dataIndex;
				}
			}
			finalStudyResultData.tabletRearColorR_ForCamera1 = maxCountColor;

			maxCount = 0;
			maxCountColor = 0;
			for (int dataIndex = 0; dataIndex < 256; dataIndex++)
			{
				if (maxCount < FinalStudyResult[globalCameraIndex].RearColorG[dataIndex])
				{
					maxCount = FinalStudyResult[globalCameraIndex].RearColorG[dataIndex];
					maxCountColor = dataIndex;
				}
			}
			finalStudyResultData.tabletRearColorG_ForCamera1 = maxCountColor;

			maxCount = 0;
			maxCountColor = 0;
			for (int dataIndex = 0; dataIndex < 256; dataIndex++)
			{
				if (maxCount < FinalStudyResult[globalCameraIndex].RearColorB[dataIndex])
				{
					maxCount = FinalStudyResult[globalCameraIndex].RearColorB[dataIndex];
					maxCountColor = dataIndex;
				}
			}

			finalStudyResultData.tabletRearColorB_ForCamera1 = maxCountColor;

      // 각인 색상
      maxCount = 0;
      maxCountColor = 0;
      for (int dataIndex = 1; dataIndex < 256; dataIndex++)
      {
        if (maxCount < FinalStudyResult[globalCameraIndex].TabletRearPrintColorB[dataIndex])
        {
          maxCount = FinalStudyResult[globalCameraIndex].TabletRearPrintColorB[dataIndex];
          maxCountColor = dataIndex;
        }
      }
      finalStudyResultData.tabletRearEngraveColorForCamera1[0] = maxCountColor;

      maxCount = 0;
      maxCountColor = 0;
      for (int dataIndex = 1; dataIndex < 256; dataIndex++)
      {
        if (maxCount < FinalStudyResult[globalCameraIndex].TabletRearPrintColorG[dataIndex])
        {
          maxCount = FinalStudyResult[globalCameraIndex].TabletRearPrintColorG[dataIndex];
          maxCountColor = dataIndex;
        }
      }
      finalStudyResultData.tabletRearEngraveColorForCamera1[1] = maxCountColor;

      maxCount = 0;
      maxCountColor = 0;
      for (int dataIndex = 1; dataIndex < 256; dataIndex++)
      {
        if (maxCount < FinalStudyResult[globalCameraIndex].TabletRearPrintColorR[dataIndex])
        {
          maxCount = FinalStudyResult[globalCameraIndex].TabletRearPrintColorR[dataIndex];
          maxCountColor = dataIndex;
        }
      }
      finalStudyResultData.tabletRearEngraveColorForCamera1[2] = maxCountColor;
		}
	}

	globalCameraIndex = SD2_2D_FRONT_FACE_CAMERA_INDEX - 1;
	if (CameraMapInfo[globalCameraIndex].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[globalCameraIndex] != 0)
	{
    // 정제 색상
		maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 0; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].ColorR[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].ColorR[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletColorR_ForCamera9 = maxCountColor;

		maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 0; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].ColorG[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].ColorG[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletColorG_ForCamera9 = maxCountColor;

		maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 0; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].ColorB[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].ColorB[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletColorB_ForCamera9 = maxCountColor;

    // 각인 색상
    maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 1; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].TabletPrintColorB[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].TabletPrintColorB[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletEngraveColorForCamera9[0] = maxCountColor;

    maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 1; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].TabletPrintColorG[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].TabletPrintColorG[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletEngraveColorForCamera9[1] = maxCountColor;

    maxCount = 0;
		maxCountColor = 0;
		for (int dataIndex = 1; dataIndex < 256; dataIndex++)
		{
			if (maxCount < FinalStudyResult[globalCameraIndex].TabletPrintColorR[dataIndex])
			{
				maxCount = FinalStudyResult[globalCameraIndex].TabletPrintColorR[dataIndex];
				maxCountColor = dataIndex;
			}
		}
		finalStudyResultData.tabletEngraveColorForCamera9[2] = maxCountColor;

		if (IsTwoColor)
		{
      // 정제 색상
			maxCount = 0;
			maxCountColor = 0;
			for (int dataIndex = 0; dataIndex < 256; dataIndex++)
			{
				if (maxCount < FinalStudyResult[globalCameraIndex].RearColorR[dataIndex])
				{
					maxCount = FinalStudyResult[globalCameraIndex].RearColorR[dataIndex];
					maxCountColor = dataIndex;
				}
			}
			finalStudyResultData.tabletRearColorR_ForCamera9 = maxCountColor;

			maxCount = 0;
			maxCountColor = 0;
			for (int dataIndex = 0; dataIndex < 256; dataIndex++)
			{
				if (maxCount < FinalStudyResult[globalCameraIndex].RearColorG[dataIndex])
				{
					maxCount = FinalStudyResult[globalCameraIndex].RearColorG[dataIndex];
					maxCountColor = dataIndex;
				}
			}
			finalStudyResultData.tabletRearColorG_ForCamera9 = maxCountColor;

			maxCount = 0;
			maxCountColor = 0;
			for (int dataIndex = 0; dataIndex < 256; dataIndex++)
			{
				if (maxCount < FinalStudyResult[globalCameraIndex].RearColorB[dataIndex])
				{
					maxCount = FinalStudyResult[globalCameraIndex].RearColorB[dataIndex];
					maxCountColor = dataIndex;
				}
			}
			finalStudyResultData.tabletRearColorB_ForCamera9 = maxCountColor;

      // 각인 색상
      maxCount = 0;
      maxCountColor = 0;
      for (int dataIndex = 1; dataIndex < 256; dataIndex++)
      {
        if (maxCount < FinalStudyResult[globalCameraIndex].TabletRearPrintColorB[dataIndex])
        {
          maxCount = FinalStudyResult[globalCameraIndex].TabletRearPrintColorB[dataIndex];
          maxCountColor = dataIndex;
        }
      }
      finalStudyResultData.tabletRearEngraveColorForCamera9[0] = maxCountColor;

      maxCount = 0;
      maxCountColor = 0;
      for (int dataIndex = 1; dataIndex < 256; dataIndex++)
      {
        if (maxCount < FinalStudyResult[globalCameraIndex].TabletRearPrintColorG[dataIndex])
        {
          maxCount = FinalStudyResult[globalCameraIndex].TabletRearPrintColorG[dataIndex];
          maxCountColor = dataIndex;
        }
      }
      finalStudyResultData.tabletRearEngraveColorForCamera9[1] = maxCountColor;

      maxCount = 0;
      maxCountColor = 0;
      for (int dataIndex = 1; dataIndex < 256; dataIndex++)
      {
        if (maxCount < FinalStudyResult[globalCameraIndex].TabletRearPrintColorR[dataIndex])
        {
          maxCount = FinalStudyResult[globalCameraIndex].TabletRearPrintColorR[dataIndex];
          maxCountColor = dataIndex;
        }
      }
      finalStudyResultData.tabletRearEngraveColorForCamera9[2] = maxCountColor;
		}
	}

  for(int globalCameraIndex = 1; globalCameraIndex <= SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    // side face
    if(globalCameraIndex != SD1_2D_FRONT_FACE_CAMERA_INDEX &&
        globalCameraIndex != SD1_3D_FRONT_FACE_CAMERA_INDEX &&
        globalCameraIndex != SD2_2D_FRONT_FACE_CAMERA_INDEX &&
        globalCameraIndex != SD2_3D_FRONT_FACE_CAMERA_INDEX)
    {
      if(ProductData.TabletType == TABLET_TYPE_SUGAR_COATED)
      {
        if(globalCameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX ||
            globalCameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX ||
            globalCameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX ||
            globalCameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX)
        {
          continue;
        }
      }
      
      if (CameraMapInfo[globalCameraIndex - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[globalCameraIndex - 1] != 0  )
      {
        maxCount = 0;
        maxCountColor = 0;
        for (int dataIndex = 0; dataIndex < 256; dataIndex++)
        {
          if (maxCount < FinalStudyResult[globalCameraIndex - 1].ColorR[dataIndex])
          {
            maxCount = FinalStudyResult[globalCameraIndex - 1].ColorR[dataIndex];
            maxCountColor = dataIndex;
          }
        }
        finalStudyResultData.SideFaceTabletRColor[globalCameraIndex - 1] = maxCountColor;

        maxCount = 0;
        maxCountColor = 0;
        for (int dataIndex = 0; dataIndex < 256; dataIndex++)
        {
          if (maxCount < FinalStudyResult[globalCameraIndex - 1].ColorG[dataIndex])
          {
            maxCount = FinalStudyResult[globalCameraIndex - 1].ColorG[dataIndex];
            maxCountColor = dataIndex;
          }
        }
        finalStudyResultData.SideFaceTabletGColor[globalCameraIndex - 1] = maxCountColor;

        maxCount = 0;
        maxCountColor = 0;
        for (int dataIndex = 0; dataIndex < 256; dataIndex++)
        {
          if (maxCount < FinalStudyResult[globalCameraIndex - 1].ColorB[dataIndex])
          {
            maxCount = FinalStudyResult[globalCameraIndex - 1].ColorB[dataIndex];
            maxCountColor = dataIndex;
          }
        }
        finalStudyResultData.SideFaceTabletBColor[globalCameraIndex - 1] = maxCountColor;
      }
    }
  }

	if (ProductData.EngraveType != ENGRAVE_TYPE_PRINT)
	{
		if (ProductData.EngravePos == ENGRAVE_POS_ONESIDE)
		{
			if (CameraMapInfo[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
			{
				finalStudyResultData.Print1_IsOrNotThreshold_ForCamera1 =
					Optimal_Threshold(FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 1, 3000, NULL, 1);
				finalStudyResultData.Print2_IsOrNotThreshold_ForCamera1 =
					Optimal_Threshold(FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 0, 3000, NULL, 0);
			}
			if (CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
			{
				finalStudyResultData.Print1_IsOrNotThreshold_ForCamera5 =
					Optimal_Threshold(FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 0, 2000, NULL, 0);
				finalStudyResultData.Print2_IsOrNotThreshold_ForCamera5 =
					Optimal_Threshold(FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 0, 2000, NULL, 0);
			}
			if (CameraMapInfo[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
			{
				finalStudyResultData.Print1_IsOrNotThreshold_ForCamera9 =
					Optimal_Threshold(FinalStudyResult[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 1, 3000, NULL, 1);
				finalStudyResultData.Print2_IsOrNotThreshold_ForCamera9 =
					Optimal_Threshold(FinalStudyResult[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 0, 3000, NULL, 0);
			}
			if (CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
			{
				finalStudyResultData.Print1_IsOrNotThreshold_ForCamera13 =
					Optimal_Threshold(FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 0, 2000, NULL, 0);
				finalStudyResultData.Print2_IsOrNotThreshold_ForCamera13 =
					Optimal_Threshold(FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 0, 2000, NULL, 0);
			}
		}
		else
		{
			if (CameraMapInfo[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
			{
				finalStudyResultData.Print1_IsOrNotThreshold_ForCamera1 =
					Optimal_Threshold(FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 0, 3000, NULL, 0);
				finalStudyResultData.Print2_IsOrNotThreshold_ForCamera1 =
					Optimal_Threshold(FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 0, 3000, NULL, 0);
			}
			if (CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
			{
				finalStudyResultData.Print1_IsOrNotThreshold_ForCamera5 =
					Optimal_Threshold(FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 0, 2000, NULL, 0);
				finalStudyResultData.Print2_IsOrNotThreshold_ForCamera5 =
					Optimal_Threshold(FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 0, 2000, NULL, 0);
			}
			if (CameraMapInfo[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
			{
				finalStudyResultData.Print1_IsOrNotThreshold_ForCamera9 =
					Optimal_Threshold(FinalStudyResult[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 0, 3000, NULL, 0);
				finalStudyResultData.Print2_IsOrNotThreshold_ForCamera9 =
					Optimal_Threshold(FinalStudyResult[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 0, 3000, NULL, 0);
			}
			if (CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
			{
				finalStudyResultData.Print1_IsOrNotThreshold_ForCamera13 =
					Optimal_Threshold(FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 0, 2000, NULL, 0);
				finalStudyResultData.Print2_IsOrNotThreshold_ForCamera13 =
					Optimal_Threshold(FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 0, 2000, NULL, 0);
			}
		}
	}
  else if (ProductData.EngraveType == ENGRAVE_TYPE_PRINT)
  {
    if (CameraMapInfo[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
		{
			finalStudyResultData.Print1_IsOrNotThreshold_ForCamera1 =
				Mean(FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 1, 3000);
			finalStudyResultData.Print2_IsOrNotThreshold_ForCamera1 =
				Mean(FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 1, 3000);
		}

		if (CameraMapInfo[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
		{
			finalStudyResultData.Print1_IsOrNotThreshold_ForCamera9 =
				Mean(FinalStudyResult[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 1, 3000);
			finalStudyResultData.Print2_IsOrNotThreshold_ForCamera9 =
				Mean(FinalStudyResult[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 1, 3000);
		}

    if(ProductData.DivisionLineInfo == DIVISION_LINE_NONE)
    {
      if (CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
      {
        finalStudyResultData.Print1_IsOrNotThreshold_ForCamera5 =
          Mean(FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 1, 2000);
        finalStudyResultData.Print2_IsOrNotThreshold_ForCamera5 =
          Mean(FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 1, 2000);
      }

      if (CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
      {
        finalStudyResultData.Print1_IsOrNotThreshold_ForCamera13 =
          Mean(FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 1, 2000);
        finalStudyResultData.Print2_IsOrNotThreshold_ForCamera13 =
          Mean(FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 1, 2000);
      }
    }
    else
    {
      if (CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
			{
				finalStudyResultData.Print1_IsOrNotThreshold_ForCamera5 =
					Optimal_Threshold(FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 0, 2000, NULL, 0);
				finalStudyResultData.Print2_IsOrNotThreshold_ForCamera5 =
					Optimal_Threshold(FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 0, 2000, NULL, 0);
			}

			if (CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT  && SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
			{
				finalStudyResultData.Print1_IsOrNotThreshold_ForCamera13 =
					Optimal_Threshold(FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 0, 2000, NULL, 0);
				finalStudyResultData.Print2_IsOrNotThreshold_ForCamera13 =
					Optimal_Threshold(FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 0, 2000, NULL, 0);
			}
    }
  }
	else
	{
		if (CameraMapInfo[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
		{
			finalStudyResultData.Print1_IsOrNotThreshold_ForCamera1 =
				Mean(FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 1, 3000);
			finalStudyResultData.Print2_IsOrNotThreshold_ForCamera1 =
				Mean(FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 1, 3000);
		}
		if (CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
		{
			finalStudyResultData.Print1_IsOrNotThreshold_ForCamera5 =
				Mean(FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 1, 2000);
			finalStudyResultData.Print2_IsOrNotThreshold_ForCamera5 =
				Mean(FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 1, 2000);
		}
		if (CameraMapInfo[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
		{
			finalStudyResultData.Print1_IsOrNotThreshold_ForCamera9 =
				Mean(FinalStudyResult[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 1, 3000);
			finalStudyResultData.Print2_IsOrNotThreshold_ForCamera9 =
				Mean(FinalStudyResult[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 1, 3000);
		}
		if (CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
		{
			finalStudyResultData.Print1_IsOrNotThreshold_ForCamera13 =
				Mean(FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue1, 1, 2000);
			finalStudyResultData.Print2_IsOrNotThreshold_ForCamera13 =
				Mean(FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].PrintMatchingValue2, 1, 2000);
		}
	}

	if (ProductData.EngraveType != ENGRAVE_TYPE_PRINT && ProductData.EngravePos == ENGRAVE_POS_ONESIDE)
	{
		if (FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatch_AddCount_Remaining != 0)
		{
			finalStudyResultData.TabletEngraveMisMatchCount_Remaining_CAM1 = FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatchCount_Remaining / FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatch_AddCount_Remaining;
		}
		else
		{
			finalStudyResultData.TabletEngraveMisMatchCount_Remaining_CAM1 = 10000;
		}

		if (FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatch_AddCount_Empty != 0)
		{
			finalStudyResultData.TabletEngraveMisMatchCount_Empty_CAM1 = FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatchCount_Empty / FinalStudyResult[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatch_AddCount_Empty;
		}
		else
		{
			finalStudyResultData.TabletEngraveMisMatchCount_Empty_CAM1 = 10000;
		}

		if (FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatch_AddCount_Remaining != 0)
		{
			finalStudyResultData.TabletEngraveMisMatchCount_Remaining_CAM9 = FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatchCount_Remaining / FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatch_AddCount_Remaining;
		}
		else
		{
			finalStudyResultData.TabletEngraveMisMatchCount_Remaining_CAM9 = 10000;
		}

		if (FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatch_AddCount_Empty != 0)
		{
			finalStudyResultData.TabletEngraveMisMatchCount_Empty_CAM9 = FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatchCount_Empty / FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].AccTabletEngraveMisMatch_AddCount_Empty;
		}
		else
		{
			finalStudyResultData.TabletEngraveMisMatchCount_Empty_CAM9 = 10000;
		}
	}
	else
	{
		finalStudyResultData.TabletEngraveMisMatchCount_Remaining_CAM1 = 10000;
		finalStudyResultData.TabletEngraveMisMatchCount_Empty_CAM1 = 10000;

		finalStudyResultData.TabletEngraveMisMatchCount_Remaining_CAM9 = 10000;
		finalStudyResultData.TabletEngraveMisMatchCount_Empty_CAM9 = 10000;
	}

	int maxHeightCountA = -1;
	int maxHeightValA = 0;
	int centerHeightCountA = -1;
	int centerHeightValA = 0;

	// For SELMA200
	// CameraMapInfo의 Index가 측면카메라로 잡혀있었음. 3D로 변경 후 이상유무 확인해야함
	if (CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
	{
		for (int dataIndex = 0; dataIndex < 256; dataIndex++)
		{
			if (maxHeightCountA < FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].ThreeDMaxHeight1[dataIndex])
			{
				maxHeightCountA = FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].ThreeDMaxHeight1[dataIndex];
				maxHeightValA = dataIndex;
			}

			if (centerHeightCountA < FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].ThreeDCenterHeight1[dataIndex])
			{
				centerHeightCountA = FinalStudyResult[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].ThreeDCenterHeight1[dataIndex];
				centerHeightValA = dataIndex;
			}
		}
	}

	int maxHeightCountB = -1;
	int maxHeightValB = 0;
	int centerHeightCountB = -1;
	int centerHeightValB = 0;
	if (CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 )
	{
		for (int dataIndex = 0; dataIndex < 256; dataIndex++)
		{
			if (maxHeightCountB < FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].ThreeDMaxHeight2[dataIndex])
			{
				maxHeightCountB = FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].ThreeDMaxHeight2[dataIndex];
				maxHeightValB = dataIndex;
			}

			if (centerHeightCountB < FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].ThreeDCenterHeight2[dataIndex])
			{
				centerHeightCountB = FinalStudyResult[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].ThreeDCenterHeight2[dataIndex];
				centerHeightValB = dataIndex;
			}
		}
	}

	finalStudyResultData.tabletMaxThickForFirstDisk = maxHeightValA;
	finalStudyResultData.tabletMaxThickForSecondDisk = maxHeightValB;
	finalStudyResultData.tabletCenterThickForFirstDisk = centerHeightValA;
	finalStudyResultData.tabletCenterThickForSecondDisk = centerHeightValB;	

	AnsiString studyResultFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".stl";
	TFileStream *fileStream = new TFileStream(studyResultFileName, fmCreate);
	if (fileStream)
	{
		fileStream->Write(FinalStudyResult, SYSTEM_TOTAL_CAMERA_COUNT * sizeof(TStudyResultData_SPB));
		delete fileStream;
	}

	AnsiString studyFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".stu";
	if (!SaveStudyData(studyFileName, finalStudyResultData))
	{
		ShowMessageFA(STUDYFORM_MSG_07);
	}

	if (IsTwoColor)
	{
		TabletTwoColorFrontShape1->Brush->Color = (TColor)((finalStudyResultData.tabletColorB_ForCamera1 << 16) +
			(finalStudyResultData.tabletColorG_ForCamera1 << 8) + finalStudyResultData.tabletColorR_ForCamera1);
		TabletTwoColorRearShape1->Brush->Color = (TColor)((finalStudyResultData.tabletRearColorB_ForCamera1 << 16) +
			(finalStudyResultData.tabletRearColorG_ForCamera1 << 8) + finalStudyResultData.tabletRearColorR_ForCamera1);

		TabletTwoColorFrontShape2->Brush->Color = (TColor)((finalStudyResultData.tabletColorB_ForCamera9 << 16) +
			(finalStudyResultData.tabletColorG_ForCamera9 << 8) + finalStudyResultData.tabletColorR_ForCamera9);
		TabletTwoColorRearShape2->Brush->Color = (TColor)((finalStudyResultData.tabletRearColorB_ForCamera9 << 16) +
			(finalStudyResultData.tabletRearColorG_ForCamera9 << 8) + finalStudyResultData.tabletRearColorR_ForCamera9);

		TabletTwoColorFrontLabel_Disk1_R->Caption = IntToStr(finalStudyResultData.tabletColorR_ForCamera1);
		TabletTwoColorFrontLabel_Disk1_G->Caption = IntToStr(finalStudyResultData.tabletColorG_ForCamera1);
		TabletTwoColorFrontLabel_Disk1_B->Caption = IntToStr(finalStudyResultData.tabletColorB_ForCamera1);

		TabletTwoColorRearLabel_Disk1_R->Caption = IntToStr(finalStudyResultData.tabletRearColorR_ForCamera1);
		TabletTwoColorRearLabel_Disk1_G->Caption = IntToStr(finalStudyResultData.tabletRearColorG_ForCamera1);
		TabletTwoColorRearLabel_Disk1_B->Caption = IntToStr(finalStudyResultData.tabletRearColorB_ForCamera1);

		TabletTwoColorFrontLabel_Disk2_R->Caption = IntToStr(finalStudyResultData.tabletColorR_ForCamera9);
		TabletTwoColorFrontLabel_Disk2_G->Caption = IntToStr(finalStudyResultData.tabletColorG_ForCamera9);
		TabletTwoColorFrontLabel_Disk2_B->Caption = IntToStr(finalStudyResultData.tabletColorB_ForCamera9);

		TabletTwoColorRearLabel_Disk2_R->Caption = IntToStr(finalStudyResultData.tabletRearColorR_ForCamera9);
		TabletTwoColorRearLabel_Disk2_G->Caption = IntToStr(finalStudyResultData.tabletRearColorG_ForCamera9);
		TabletTwoColorRearLabel_Disk2_B->Caption = IntToStr(finalStudyResultData.tabletRearColorB_ForCamera9);
	}
	else
	{
		TabletOneColorShape1->Brush->Color = (TColor)((finalStudyResultData.tabletColorB_ForCamera1 << 16) +
			(finalStudyResultData.tabletColorG_ForCamera1 << 8) + finalStudyResultData.tabletColorR_ForCamera1);
		TabletOneColorShape2->Brush->Color = (TColor)((finalStudyResultData.tabletColorB_ForCamera9 << 16) +
			(finalStudyResultData.tabletColorG_ForCamera9 << 8) + finalStudyResultData.tabletColorR_ForCamera9);

		TabletOneColorLabel_Disk1_R->Caption = IntToStr(finalStudyResultData.tabletColorR_ForCamera1);
		TabletOneColorLabel_Disk1_G->Caption = IntToStr(finalStudyResultData.tabletColorG_ForCamera1);
		TabletOneColorLabel_Disk1_B->Caption = IntToStr(finalStudyResultData.tabletColorB_ForCamera1);

		TabletOneColorLabel_Disk2_R->Caption = IntToStr(finalStudyResultData.tabletColorR_ForCamera9);
		TabletOneColorLabel_Disk2_G->Caption = IntToStr(finalStudyResultData.tabletColorG_ForCamera9);
		TabletOneColorLabel_Disk2_B->Caption = IntToStr(finalStudyResultData.tabletColorB_ForCamera9);
	}

  for(int globalCameraIndex = 1; globalCameraIndex <= SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    if(globalCameraIndex != SD1_2D_FRONT_FACE_CAMERA_INDEX &&
        globalCameraIndex != SD1_3D_FRONT_FACE_CAMERA_INDEX &&
        globalCameraIndex != SD2_2D_FRONT_FACE_CAMERA_INDEX &&
        globalCameraIndex != SD2_3D_FRONT_FACE_CAMERA_INDEX)
    {
      TTntShape *SideColorShape;
      SideColorShape = (TTntShape *)FindComponent("SideColorShapeCam" + IntToStr(globalCameraIndex));
      if(SideColorShape)
      {
        SideColorShape->Brush->Color = (TColor)((finalStudyResultData.SideFaceTabletBColor[globalCameraIndex - 1] << 16) +
                                                (finalStudyResultData.SideFaceTabletGColor[globalCameraIndex - 1] << 8) +
                                                (finalStudyResultData.SideFaceTabletRColor[globalCameraIndex - 1] << 0));

      }

      TTntLabel *SideCameraBColorLabel;
      SideCameraBColorLabel = (TTntLabel *)FindComponent("SideFaceTabletBColorLabelCam" + IntToStr(globalCameraIndex));
      if(SideCameraBColorLabel)
      {
        SideCameraBColorLabel->Caption = IntToStr(finalStudyResultData.SideFaceTabletBColor[globalCameraIndex - 1]);
      }

      TTntLabel *SideCameraGColorLabel;
      SideCameraGColorLabel = (TTntLabel *)FindComponent("SideFaceTabletGColorLabelCam" + IntToStr(globalCameraIndex));
      if(SideCameraGColorLabel)
      {
        SideCameraGColorLabel->Caption = IntToStr(finalStudyResultData.SideFaceTabletGColor[globalCameraIndex - 1]);
      }

      TTntLabel *SideCameraRColorLabel;
      SideCameraRColorLabel = (TTntLabel *)FindComponent("SideFaceTabletRColorLabelCam" + IntToStr(globalCameraIndex));
      if(SideCameraRColorLabel)
      {
        SideCameraRColorLabel->Caption = IntToStr(finalStudyResultData.SideFaceTabletRColor[globalCameraIndex - 1]);
      }
    }
  }

  
	WCHAR TempString[100];

	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, finalStudyResultData.Print1_IsOrNotThreshold_ForCamera1);
	ThresholdLabel_ForCam1_A->Caption = TempString;
	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, finalStudyResultData.Print2_IsOrNotThreshold_ForCamera1);
	ThresholdLabel_ForCam1_B->Caption = TempString;

	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, finalStudyResultData.Print1_IsOrNotThreshold_ForCamera5);
	ThresholdLabel_ForCam5_A->Caption = TempString;
	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, finalStudyResultData.Print2_IsOrNotThreshold_ForCamera5);
	ThresholdLabel_ForCam5_B->Caption = TempString;

	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, finalStudyResultData.Print1_IsOrNotThreshold_ForCamera9);
	ThresholdLabel_ForCam9_A->Caption = TempString;
	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, finalStudyResultData.Print2_IsOrNotThreshold_ForCamera9);
	ThresholdLabel_ForCam9_B->Caption = TempString;

	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, finalStudyResultData.Print1_IsOrNotThreshold_ForCamera13);
	ThresholdLabel_ForCam13_A->Caption = TempString;
	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, finalStudyResultData.Print2_IsOrNotThreshold_ForCamera13);
	ThresholdLabel_ForCam13_B->Caption = TempString;

	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, maxHeightValA);
	HeightThresholdLabel_Disc1->Caption = TempString;
	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, maxHeightValB);
	HeightThresholdLabel_Disc2->Caption = TempString;

	if (IsTwoColor)
	{
		TwoColorResultGroupBox1->Visible = true;
		TwoColorResultGroupBox2->Visible = true;

    OneColorResultGroupBox1->Visible = false;
		OneColorResultGroupBox2->Visible = false;
	}
	else
	{
    TwoColorResultGroupBox1->Visible = false;
		TwoColorResultGroupBox2->Visible = false;

		OneColorResultGroupBox1->Visible = true;
		OneColorResultGroupBox2->Visible = true;
	}

  /*
	Panel50->Visible = true;
  Panel53->Visible = true;
  Panel56->Visible = true;
  Panel107->Visible = true;
  Panel111->Visible = true;
  Panel118->Visible = true;
  */

  ColorValuePanel1->Visible = true;
  ColorValuePanel2->Visible = true;
  
	ThresholdGroupBox1->Visible = true;
	ThresholdGroupBox2->Visible = true;
	ThresholdGroupBox3->Visible = true;
	ThresholdGroupBox4->Visible = true;
	HeightGroupBox1->Visible = true;
	HeightGroupBox2->Visible = true;
}
//---------------------------------------------------------------------------
int __fastcall TStudyForm::Optimal_Threshold(unsigned short *histo, int st_gray, int end_gray, int *grayMean, int option)
{
	int opti_threshold;
	int new_opti_threshold;
	int gl;
	int low_mean;
	int low_mean_cnt;
	int high_mean;
	int high_mean_cnt;
	int repeat_cnt;
	int tcnt;
	repeat_cnt = 0;
	tcnt = 0;
	new_opti_threshold = 0;

	// histo[gl] 은 gl의 값이 카운팅된 횟수를 의미함
	for (gl = st_gray; gl < end_gray; gl++) // 0 : 1000
	{
		new_opti_threshold += histo[gl] * gl;
		tcnt += histo[gl];
	}
	if (tcnt != 0)
		new_opti_threshold /= tcnt; // 평균화
	else
		new_opti_threshold = 0;

	if (option)
		return new_opti_threshold;
	do
	{
		low_mean = 0;
		high_mean = 0;
		low_mean_cnt = 0;
		high_mean_cnt = 0;
		opti_threshold = new_opti_threshold;
		for (gl = st_gray; gl < opti_threshold; gl++)
		{
			low_mean += histo[gl] * gl;
			low_mean_cnt += (histo[gl]);
		}
		for (gl = opti_threshold; gl < end_gray; gl++)
		{
			high_mean += histo[gl] * gl;
			high_mean_cnt += (histo[gl]);
		}
		if (low_mean_cnt != 0)
			low_mean /= low_mean_cnt;
		if (high_mean_cnt != 0)
			high_mean /= high_mean_cnt;

		new_opti_threshold = (low_mean + high_mean) / 2;
		repeat_cnt++;
	} while (abs(new_opti_threshold - opti_threshold) > 2 && repeat_cnt < 10);

	return(new_opti_threshold);
}
//---------------------------------------------------------------------------
int __fastcall TStudyForm::Mean(unsigned short *data, int st_index, int end_index)
{
	int sum = 0;
	int count = 0;
	for (int index = st_index; index < end_index; index++)
	{
		sum += index * data[index];
		count += data[index];
	}

	if (count == 0) return 0;
	else return sum / count;
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::StudyCountEditClick(TObject *Sender)
{
	TTntEdit *theEdit = (TTntEdit *)Sender;

	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeypad() == mrOk)
	{
		theEdit->Text = KeyboardForm->Text;
	}
}
//---------------------------------------------------------------------------

void __fastcall TStudyForm::FormCreate(TObject *Sender)
{
	// load last study result
	PastStudyComplete = 0;
	CurrentStudyComplete = 0;

	AnsiString studyResultFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".stl";
	IsTwoColor = false;

	if (ProductData.TabletLayerCount > 1 && (ProductData.MultiLayeredTabletColor[0] != ProductData.MultiLayeredTabletColor[ProductData.TabletLayerCount - 1]))
	{
		IsTwoColor = true;
	}

	if (IsTwoColor)
	{
		TabletRearColorChart1->Visible = true;
		TabletRearColorChart2->Visible = true;
	}

	if (FileExists(studyResultFileName))
	{
		TFileStream *fileStream = new TFileStream(studyResultFileName, fmOpenRead);
		if (fileStream)
		{
			fileStream->Read(FinalStudyResult, SYSTEM_TOTAL_CAMERA_COUNT * sizeof(TStudyResultData_SPB));
			for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
			{
				// show last study result
				TStudyResultData_SPB studyResultData = FinalStudyResult[globalCameraIndex];

				if (globalCameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX - 1)
				{
					TabletColorChart1->Series[0]->Clear();
					TabletColorChart1->Series[1]->Clear();
					TabletColorChart1->Series[2]->Clear();
					for (int dataIndex = 0; dataIndex < 256; dataIndex++)
					{
						TabletColorChart1->Series[0]->Add(studyResultData.ColorB[dataIndex]);
						TabletColorChart1->Series[1]->Add(studyResultData.ColorG[dataIndex]);
						TabletColorChart1->Series[2]->Add(studyResultData.ColorR[dataIndex]);
					}

					if (IsTwoColor)
					{
						TabletRearColorChart1->Series[0]->Clear();
						TabletRearColorChart1->Series[1]->Clear();
						TabletRearColorChart1->Series[2]->Clear();
						for (int dataIndex = 0; dataIndex < 256; dataIndex++)
						{
							TabletRearColorChart1->Series[0]->Add(studyResultData.RearColorB[dataIndex]);
							TabletRearColorChart1->Series[1]->Add(studyResultData.RearColorG[dataIndex]);
							TabletRearColorChart1->Series[2]->Add(studyResultData.RearColorR[dataIndex]);
						}
					}

					TabletEngraveChart1->Series[0]->Clear();
					TabletEngraveChart1->Series[1]->Clear();
					for (int dataIndex = 0; dataIndex < 3000; dataIndex++)
					{
						TabletEngraveChart1->Series[0]->Add(studyResultData.PrintMatchingValue1[dataIndex]);
						TabletEngraveChart1->Series[1]->Add(studyResultData.PrintMatchingValue2[dataIndex]);
					}
				}
				else if (globalCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX - 1)
				{
					TabletEngraveChart2->Series[0]->Clear();
					TabletEngraveChart2->Series[1]->Clear();
					for (int dataIndex = 0; dataIndex < 2000; dataIndex++)
					{
						TabletEngraveChart2->Series[0]->Add(studyResultData.PrintMatchingValue1[dataIndex]);
						TabletEngraveChart2->Series[1]->Add(studyResultData.PrintMatchingValue2[dataIndex]);
					}

					TabletHeightChart1->Series[0]->Clear();
					TabletHeightChart1->Series[1]->Clear();
					for (int dataIndex = 0; dataIndex < 256; dataIndex++)
					{
						TabletHeightChart1->Series[0]->Add(studyResultData.ThreeDMaxHeight1[dataIndex]);
					}
				}
				else if (globalCameraIndex == SD2_2D_FRONT_FACE_CAMERA_INDEX - 1)
				{
					TabletColorChart2->Series[0]->Clear();
					TabletColorChart2->Series[1]->Clear();
					TabletColorChart2->Series[2]->Clear();
					for (int dataIndex = 0; dataIndex < 256; dataIndex++)
					{
						TabletColorChart2->Series[0]->Add(studyResultData.ColorB[dataIndex]);
						TabletColorChart2->Series[1]->Add(studyResultData.ColorG[dataIndex]);
						TabletColorChart2->Series[2]->Add(studyResultData.ColorR[dataIndex]);
					}

					if (IsTwoColor)
					{
						TabletRearColorChart2->Series[0]->Clear();
						TabletRearColorChart2->Series[1]->Clear();
						TabletRearColorChart2->Series[2]->Clear();
						for (int dataIndex = 0; dataIndex < 256; dataIndex++)
						{
							TabletRearColorChart2->Series[0]->Add(studyResultData.RearColorB[dataIndex]);
							TabletRearColorChart2->Series[1]->Add(studyResultData.RearColorG[dataIndex]);
							TabletRearColorChart2->Series[2]->Add(studyResultData.RearColorR[dataIndex]);
						}
					}

					TabletEngraveChart3->Series[0]->Clear();
					TabletEngraveChart3->Series[1]->Clear();
					for (int dataIndex = 0; dataIndex < 3000; dataIndex++)
					{
						TabletEngraveChart3->Series[0]->Add(studyResultData.PrintMatchingValue1[dataIndex]);
						TabletEngraveChart3->Series[1]->Add(studyResultData.PrintMatchingValue2[dataIndex]);
					}
				}
				else if (globalCameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX - 1)
				{
					TabletEngraveChart4->Series[0]->Clear();
					TabletEngraveChart4->Series[1]->Clear();
					for (int dataIndex = 0; dataIndex < 2000; dataIndex++)
					{
						TabletEngraveChart4->Series[0]->Add(studyResultData.PrintMatchingValue1[dataIndex]);
						TabletEngraveChart4->Series[1]->Add(studyResultData.PrintMatchingValue2[dataIndex]);
					}

					TabletHeightChart2->Series[0]->Clear();
					TabletHeightChart2->Series[1]->Clear();
					for (int dataIndex = 0; dataIndex < 256; dataIndex++)
					{
						TabletHeightChart2->Series[0]->Add(studyResultData.ThreeDMaxHeight2[dataIndex]);
					}
				}
        else
        {
          // Side Camera
          TChart *SideCameraColorChart;
          SideCameraColorChart = (TChart *)FindComponent("TabletColorChartSideCam" + IntToStr(globalCameraIndex + 1));

          if(SideCameraColorChart)
          {
            SideCameraColorChart->Series[0]->Clear();
            SideCameraColorChart->Series[1]->Clear();
            SideCameraColorChart->Series[2]->Clear();
            for (int dataIndex = 0; dataIndex < 256; dataIndex++)
            {
              SideCameraColorChart->Series[0]->Add(studyResultData.ColorB[dataIndex]);
              SideCameraColorChart->Series[1]->Add(studyResultData.ColorG[dataIndex]);
              SideCameraColorChart->Series[2]->Add(studyResultData.ColorR[dataIndex]);
            }
          }
        }
			}
			delete fileStream;
		}
	}

	AnsiString studyFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".stu";
	if (FileExists(studyFileName))
	{
		if (LoadStudyData(studyFileName, lastStudyResultData))
		{
			PastStudyComplete = 1;
			CurrentStudyComplete = 0;

			if (IsTwoColor)
			{
				TabletTwoColorFrontShape1->Brush->Color = (TColor)((lastStudyResultData.tabletColorB_ForCamera1 << 16) +
					(lastStudyResultData.tabletColorG_ForCamera1 << 8) + lastStudyResultData.tabletColorR_ForCamera1);
				TabletTwoColorFrontShape2->Brush->Color = (TColor)((lastStudyResultData.tabletColorB_ForCamera9 << 16) +
					(lastStudyResultData.tabletColorG_ForCamera9 << 8) + lastStudyResultData.tabletColorR_ForCamera9);

				TabletTwoColorRearShape1->Brush->Color = (TColor)((lastStudyResultData.tabletRearColorB_ForCamera1 << 16) +
					(lastStudyResultData.tabletRearColorG_ForCamera1 << 8) + lastStudyResultData.tabletRearColorR_ForCamera1);
				TabletTwoColorRearShape2->Brush->Color = (TColor)((lastStudyResultData.tabletRearColorB_ForCamera9 << 16) +
					(lastStudyResultData.tabletRearColorG_ForCamera9 << 8) + lastStudyResultData.tabletRearColorR_ForCamera9);

				TabletTwoColorFrontLabel_Disk1_R->Caption = IntToStr(lastStudyResultData.tabletColorR_ForCamera1);
				TabletTwoColorFrontLabel_Disk1_G->Caption = IntToStr(lastStudyResultData.tabletColorG_ForCamera1);
				TabletTwoColorFrontLabel_Disk1_B->Caption = IntToStr(lastStudyResultData.tabletColorB_ForCamera1);

				TabletTwoColorRearLabel_Disk1_R->Caption = IntToStr(lastStudyResultData.tabletRearColorR_ForCamera1);
				TabletTwoColorRearLabel_Disk1_G->Caption = IntToStr(lastStudyResultData.tabletRearColorG_ForCamera1);
				TabletTwoColorRearLabel_Disk1_B->Caption = IntToStr(lastStudyResultData.tabletRearColorB_ForCamera1);

				TabletTwoColorFrontLabel_Disk2_R->Caption = IntToStr(lastStudyResultData.tabletColorR_ForCamera9);
				TabletTwoColorFrontLabel_Disk2_G->Caption = IntToStr(lastStudyResultData.tabletColorG_ForCamera9);
				TabletTwoColorFrontLabel_Disk2_B->Caption = IntToStr(lastStudyResultData.tabletColorB_ForCamera9);

				TabletTwoColorRearLabel_Disk2_R->Caption = IntToStr(lastStudyResultData.tabletRearColorR_ForCamera9);
				TabletTwoColorRearLabel_Disk2_G->Caption = IntToStr(lastStudyResultData.tabletRearColorG_ForCamera9);
				TabletTwoColorRearLabel_Disk2_B->Caption = IntToStr(lastStudyResultData.tabletRearColorB_ForCamera9);
			}
			else
			{
				TabletOneColorShape1->Brush->Color = (TColor)((lastStudyResultData.tabletColorB_ForCamera1 << 16) +
					(lastStudyResultData.tabletColorG_ForCamera1 << 8) + lastStudyResultData.tabletColorR_ForCamera1);
				TabletOneColorShape2->Brush->Color = (TColor)((lastStudyResultData.tabletColorB_ForCamera9 << 16) +
					(lastStudyResultData.tabletColorG_ForCamera9 << 8) + lastStudyResultData.tabletColorR_ForCamera9);

				TabletOneColorLabel_Disk1_R->Caption = IntToStr(lastStudyResultData.tabletColorR_ForCamera1);
				TabletOneColorLabel_Disk1_G->Caption = IntToStr(lastStudyResultData.tabletColorG_ForCamera1);
				TabletOneColorLabel_Disk1_B->Caption = IntToStr(lastStudyResultData.tabletColorB_ForCamera1);

				TabletOneColorLabel_Disk2_R->Caption = IntToStr(lastStudyResultData.tabletColorR_ForCamera9);
				TabletOneColorLabel_Disk2_G->Caption = IntToStr(lastStudyResultData.tabletColorG_ForCamera9);
				TabletOneColorLabel_Disk2_B->Caption = IntToStr(lastStudyResultData.tabletColorB_ForCamera9);
			}

      for(int globalCameraIndex = 1; globalCameraIndex <= SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
      {
        if(globalCameraIndex != SD1_2D_FRONT_FACE_CAMERA_INDEX &&
            globalCameraIndex != SD1_3D_FRONT_FACE_CAMERA_INDEX &&
            globalCameraIndex != SD2_2D_FRONT_FACE_CAMERA_INDEX &&
            globalCameraIndex != SD2_3D_FRONT_FACE_CAMERA_INDEX)
        {
          TTntShape *SideColorShape;
          SideColorShape = (TTntShape *)FindComponent("SideColorShapeCam" + IntToStr(globalCameraIndex));
          if(SideColorShape)
          {
            SideColorShape->Brush->Color = (TColor)((lastStudyResultData.SideFaceTabletBColor[globalCameraIndex - 1] << 16) +
					                                          (lastStudyResultData.SideFaceTabletGColor[globalCameraIndex - 1] << 8) +
                                                    (lastStudyResultData.SideFaceTabletRColor[globalCameraIndex - 1] << 0));

          }

          TTntLabel *SideCameraBColorLabel;
          SideCameraBColorLabel = (TTntLabel *)FindComponent("SideFaceTabletBColorLabelCam" + IntToStr(globalCameraIndex));
          if(SideCameraBColorLabel)
          {
            SideCameraBColorLabel->Caption = IntToStr(lastStudyResultData.SideFaceTabletBColor[globalCameraIndex - 1]);
          }

          TTntLabel *SideCameraGColorLabel;
          SideCameraGColorLabel = (TTntLabel *)FindComponent("SideFaceTabletGColorLabelCam" + IntToStr(globalCameraIndex));
          if(SideCameraGColorLabel)
          {
            SideCameraGColorLabel->Caption = IntToStr(lastStudyResultData.SideFaceTabletGColor[globalCameraIndex - 1]);
          }

          TTntLabel *SideCameraRColorLabel;
          SideCameraRColorLabel = (TTntLabel *)FindComponent("SideFaceTabletRColorLabelCam" + IntToStr(globalCameraIndex));
          if(SideCameraRColorLabel)
          {
            SideCameraRColorLabel->Caption = IntToStr(lastStudyResultData.SideFaceTabletRColor[globalCameraIndex - 1]);
          }
        }
      }

			WCHAR TempString[100];

			wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, lastStudyResultData.Print1_IsOrNotThreshold_ForCamera1);
			ThresholdLabel_ForCam1_A->Caption = TempString;
			wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, lastStudyResultData.Print2_IsOrNotThreshold_ForCamera1);
			ThresholdLabel_ForCam1_B->Caption = TempString;

			wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, lastStudyResultData.Print1_IsOrNotThreshold_ForCamera5);
			ThresholdLabel_ForCam5_A->Caption = TempString;
			wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, lastStudyResultData.Print2_IsOrNotThreshold_ForCamera5);
			ThresholdLabel_ForCam5_B->Caption = TempString;

			wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, lastStudyResultData.Print1_IsOrNotThreshold_ForCamera9);
			ThresholdLabel_ForCam9_A->Caption = TempString;
			wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, lastStudyResultData.Print2_IsOrNotThreshold_ForCamera9);
			ThresholdLabel_ForCam9_B->Caption = TempString;

			wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, lastStudyResultData.Print1_IsOrNotThreshold_ForCamera13);
			ThresholdLabel_ForCam13_A->Caption = TempString;
			wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, lastStudyResultData.Print2_IsOrNotThreshold_ForCamera13);
			ThresholdLabel_ForCam13_B->Caption = TempString;

			wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, lastStudyResultData.tabletMaxThickForFirstDisk);
			HeightThresholdLabel_Disc1->Caption = TempString;
			wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_12, lastStudyResultData.tabletMaxThickForSecondDisk);
			HeightThresholdLabel_Disc2->Caption = TempString;

      ColorValuePanel1->Visible = true;
      ColorValuePanel2->Visible = true;
  
			ThresholdGroupBox1->Visible = true;
			ThresholdGroupBox2->Visible = true;
			ThresholdGroupBox3->Visible = true;
			ThresholdGroupBox4->Visible = true;
			HeightGroupBox1->Visible = true;
			HeightGroupBox2->Visible = true;

			if (IsTwoColor)
      {
        TwoColorResultGroupBox1->Visible = true;
        TwoColorResultGroupBox2->Visible = true;

        OneColorResultGroupBox1->Visible = false;
        OneColorResultGroupBox2->Visible = false;
      }
      else
      {
        TwoColorResultGroupBox1->Visible = false;
        TwoColorResultGroupBox2->Visible = false;

        OneColorResultGroupBox1->Visible = true;
        OneColorResultGroupBox2->Visible = true;
      }
		}

    /*
		Panel50->Visible = true;
    Panel53->Visible = true;
    Panel56->Visible = true;
    Panel107->Visible = true;
    Panel111->Visible = true;
    Panel118->Visible = true;
    */
	}
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    AnsiString ConvertString;
    if(SystemLinkCameraInfo[globalCameraIndex] != 0)
    {
      if(globalCameraIndex != SD1_3D_FRONT_FACE_CAMERA_INDEX-1 && globalCameraIndex != SD2_3D_FRONT_FACE_CAMERA_INDEX-1)
      {
        TPanel *CamColorInfoPanel = (TPanel *)FindComponent("Cam" + IntToStr(globalCameraIndex+1) + "ColorInfoPanel");
        ConvertString = ConvertCameraIndex(globalCameraIndex);
        CamColorInfoPanel->Caption = ConvertString;
      }
      if(globalCameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX-1 || globalCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX-1)
      {
        TTntLabel *ThresholdNameA = (TTntLabel *)FindComponent("ThresholdName" + IntToStr(globalCameraIndex+1) + "A");
        TTntLabel *ThresholdNameB = (TTntLabel *)FindComponent("ThresholdName" + IntToStr(globalCameraIndex+1) + "B");
        TPanel *ENNamePanel = (TPanel *)FindComponent("ENNamePanel" + IntToStr(globalCameraIndex+1));

        ConvertString = ConvertCameraIndex(globalCameraIndex);

        ThresholdNameA->Caption = ConvertString;
        ThresholdNameB->Caption = ConvertString;
        ENNamePanel->Caption = ConvertString;
      }
      if(globalCameraIndex == SD2_2D_FRONT_FACE_CAMERA_INDEX-1 || globalCameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX-1)
      {
        TTntLabel *ThresholdNameA = (TTntLabel *)FindComponent("ThresholdName" + IntToStr(globalCameraIndex+1) + "A");
        TTntLabel *ThresholdNameB = (TTntLabel *)FindComponent("ThresholdName" + IntToStr(globalCameraIndex+1) + "B");
        TPanel *ENNamePanel = (TPanel *)FindComponent("ENNamePanel" + IntToStr(globalCameraIndex+1));

        ConvertString = ConvertCameraIndex(globalCameraIndex);

        ThresholdNameA->Caption = ConvertString;
        ThresholdNameB->Caption = ConvertString;
        ENNamePanel->Caption = ConvertString;
      }

      TPanel *CamNamePanel = (TPanel *)FindComponent("CamNamePanel" + IntToStr(globalCameraIndex+1));
      ConvertString = ConvertCameraIndex(globalCameraIndex);
      CamNamePanel->Caption = ConvertString;

    }
  }

  if(GlobalProgramID == PROGRAM_ID_150P)
  {
    for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      TPanel *CamPanel = (TPanel *)FindComponent("CamPanel" + IntToStr(globalCameraIndex+1));
      TPanel *CamColorInfoPanel = (TPanel *)FindComponent("Cam" + IntToStr(globalCameraIndex+1) + "ColorInfoPanel");
      TPanel *CamColorValuePanel = (TPanel *)FindComponent("Cam" + IntToStr(globalCameraIndex+1) + "ColorValuePanel");
      if(SystemLinkCameraInfo[globalCameraIndex] == 0)
      {
        CamPanel->Visible = false;
        CamColorInfoPanel->Visible = false;
        CamColorValuePanel->Visible = false;
      }
    }
    CamPanel2->Align = alClient;
    CamPanel10->Align = alClient;
  }
  else if(ProductData.TabletType == TABLET_TYPE_SUGAR_COATED)
  {
    for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if(globalCameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
          globalCameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1 ||
          globalCameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
          globalCameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1)
      {
        TPanel *CamPanel = (TPanel *)FindComponent("CamPanel" + IntToStr(globalCameraIndex+1));
        TPanel *CamColorInfoPanel = (TPanel *)FindComponent("Cam" + IntToStr(globalCameraIndex+1) + "ColorInfoPanel");
        TPanel *CamColorValuePanel = (TPanel *)FindComponent("Cam" + IntToStr(globalCameraIndex+1) + "ColorValuePanel");

        if(CamPanel)
        {
          CamPanel->Visible = false;
        }

        if(CamColorInfoPanel)
        {
          CamColorInfoPanel->Visible = false;
        }

        if(CamColorValuePanel)
        {
          CamColorValuePanel->Visible = false;
        }
      }
    }
    CamPanel2->Align = alClient;
    CamPanel10->Align = alClient;
  }
	if(ProductData.EngraveType == ENGRAVE_TYPE_PRINT && MachineSetupData.LasercomplexerInfo.Laser_complexer_Enable==1)
	{
		MessageDlgFA("2차 학습에서는 인쇄가 되지 않습니다. 인쇄가 되어 있는 정제를 사용해 학습해 주세요.", mtConfirmation, TMsgDlgButtons() << mbOK);
	}
}
//---------------------------------------------------------------------------

void __fastcall TStudyForm::BrightnessTestButtonClick(TObject *Sender)
{
  if (!SimulationInspectionCheckBox->Checked)
  {
    if (!IsBrightnessCheckMode)
    {
      if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE1 && MachineSetupData.Qualis_Machine1_CutomOption == 0)
      {
        if(MainForm->GetLastSafetyMode() == 0)
        {
          Comm_Request(COMM_HCB, CMD_SAFETY_MAINTAENACE);
        }
      }

      BrightnessTestPanel->BringToFront();
      RefreshBrightnessTestStatus();
      // blow on
      int speed1 = 255;
      int speed2 = 255;
      Machine.RingBlowerOn(0, speed1, speed2);
      Machine.RingBlowerOn(1, speed1, speed2);

      CaptureSetup();
      BrightnessTestTimer->Enabled = true;
      IsBrightnessCheckMode = true;
      Study2MenuPanel->Visible = false;

      ImageEvalCount = 0;
    }
  }
  else
  {
    CameraTestStatus[TEST_CAMERA_1_INDEX] = ECTS_OK;
	  CameraTestStatus[TEST_CAMERA_9_INDEX] = ECTS_OK;
	  RefreshBrightnessTestStatus();
	  StudyEnableButton->Click();
  }
}
//---------------------------------------------------------------------------


void __fastcall TStudyForm::BrightnessTestTimerTimer(TObject *Sender)
{
	bool bProceedCamera = false;
	try
	{
		bool bCaptureExist;
		// check capture exists
		char cameraIndex;
		unsigned int data[2];
		unsigned int receivedData[2];
		unsigned char *captureData = NULL;
		int spbIndex = CameraMapInfo[CurrentCamGlobalIndex].SPBIndex;
		int camIndex = CameraMapInfo[CurrentCamGlobalIndex].CamIndex;
		data[0] = camIndex;
		data[1] = ImageWidth * ImageHeight;
		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)
		{
			captureData = new char[(ImageWidth + 1) * (ImageHeight + 1)];     // bayer 보정을 위해 여분을 둔다.
			if (captureData == NULL) throw(0);

			if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_UPLOAD, data, 2 * sizeof(unsigned int),
				captureData, ImageWidth * ImageHeight))
			{
				throw(0);
			}

			GetNFACamera2DColorImage(CameraImage->Picture->Bitmap, captureData, ImageWidth, ImageHeight, CurrentCamGlobalIndex, SystemImageOffsetSWCal[CurrentCamGlobalIndex - 1], SystemOffsetImage[CurrentCamGlobalIndex - 1], ProductData.SubSamplingMode);

			if (ImageEvalCount > 0)
			{
				int centerPos[2];
				ImageEvalSum += EvalBitmap(CameraImage->Picture->Bitmap, centerPos);
				double cameraRatio = MachineParams.CameraResolution[CurrentCamGlobalIndex] / 10.0;
				if (cameraRatio == 0) cameraRatio = 40.0;
				//int circleRadius = 10.0 * 1000 / cameraRatio / 2;
				int circleRadius = 6.0 * 1000 / cameraRatio / 2;

				CameraImage->Canvas->Pen->Color = clBlue;
				CameraImage->Canvas->Pen->Width = 2;
				CameraImage->Canvas->Brush->Style = bsClear;
				CameraImage->Canvas->Ellipse(
					Rect(centerPos[0] - circleRadius, centerPos[1] - circleRadius,
						centerPos[0] + circleRadius, centerPos[1] + circleRadius));

				ImageEvalCount--;
				if (ImageEvalCount == 0)
				{
					CameraEvalValue[CurrentCamListIndex] = ImageEvalSum / IMAGE_EVAL_COUNT;
					if (MachineParams.CameraBrightnessEvalValue[CurrentCamListIndex] > 0)
					{
						if (CameraEvalValue[CurrentCamListIndex] * 100 / MachineParams.CameraBrightnessEvalValue[CurrentCamListIndex] >= EVAL_VALUE_OK_LOWER_RATIO &&
                CameraEvalValue[CurrentCamListIndex] * 100 / MachineParams.CameraBrightnessEvalValue[CurrentCamListIndex] <= EVAL_VALUE_OK_HIGHER_RATIO)
						{
							CameraTestStatus[CurrentCamListIndex] = ECTS_OK;
						}
						else
						{
							CameraTestStatus[CurrentCamListIndex] = ECTS_NG;
						}
					}
					else
					{
						CameraTestStatus[CurrentCamListIndex] = ECTS_NG;
					}

					if (CurrentCamListIndex < 1)
					{
						if (CameraTestStatus[CurrentCamListIndex] == ECTS_OK)
						{
							ShowMessageFA(STUDYFORM_MSG_02);
							bProceedCamera = true;
						}
						else
						{
							ShowMessageFA(STUDYFORM_MSG_03);
						}
					}
					else
					{
						if (CameraTestStatus[TEST_CAMERA_1_INDEX] == ECTS_OK &&
							CameraTestStatus[TEST_CAMERA_9_INDEX] == ECTS_OK)
						{
							ShowMessageFA(STUDYFORM_MSG_01);
							bProceedCamera = true;
						}
						else
						{
							if (CameraTestStatus[CurrentCamListIndex] == ECTS_OK)
							{
								ShowMessageFA(STUDYFORM_MSG_02);
							}
							else
							{
								ShowMessageFA(STUDYFORM_MSG_03);
							}
						}
					}
				}
			}
			else
			{
				double cameraRatio = MachineParams.CameraResolution[CurrentCamGlobalIndex] / 10.0;
				if (cameraRatio == 0) cameraRatio = 40.0;
				//int circleRadius = 10.0 * 1000 / cameraRatio / 2;
				int circleRadius = 6.0 * 1000 / cameraRatio / 2;

				CameraImage->Canvas->Pen->Color = clRed;
				CameraImage->Canvas->Pen->Width = 20;
				CameraImage->Canvas->Brush->Style = bsClear;
				CameraImage->Canvas->Ellipse(
					Rect(CameraImage->Picture->Bitmap->Width / 2 - circleRadius, CameraImage->Picture->Bitmap->Height / 2 - circleRadius,
						CameraImage->Picture->Bitmap->Width / 2 + circleRadius, CameraImage->Picture->Bitmap->Height / 2 + circleRadius));
			}
			delete[] captureData;
		}
	}
	catch (...)
	{
		BrightnessTestTimer->Enabled = false;
	}
	RefreshBrightnessTestStatus();

	if (bProceedCamera)
	{
		AnsiString cameraSelectPanelNameList[TOTAL_CHECKING_CAMERA_COUNT] = { "Camera1SelectPanel", "Camera9SelectPanel" };
		int curCamListIndex = CurrentCamListIndex + 1;
		if (curCamListIndex >= TOTAL_CHECKING_CAMERA_COUNT)
		{
			curCamListIndex = 0;
		}
		TTntPanel *cameraSelectPanel = NULL;
		for (int camListCount = 1; camListCount < TOTAL_CHECKING_CAMERA_COUNT; camListCount++)
		{
			if (CameraTestStatus[curCamListIndex] != ECTS_OK)
			{
				cameraSelectPanel = (TTntPanel *)FindComponent(cameraSelectPanelNameList[curCamListIndex]);
				break;
			}
			curCamListIndex = curCamListIndex + 1;
			if (curCamListIndex >= TOTAL_CHECKING_CAMERA_COUNT)
			{
				curCamListIndex = 0;
			}
		}
		if (cameraSelectPanel)
		{
			CameraSelectPanelClick(cameraSelectPanel);
		}
		else if (CameraTestStatus[TEST_CAMERA_1_INDEX] == ECTS_OK &&
			CameraTestStatus[TEST_CAMERA_9_INDEX] == ECTS_OK)
		{
                        if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE1)
                        {
                          TntButton1->Caption = "Next Step";
                        }
                        else
                          StudyEnableButton->Click();
		}
	}
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::RefreshBrightnessTestStatus(void)
{
	Camera1BasisValueLabel->Caption = IntToStr(MachineParams.CameraBrightnessEvalValue[TEST_CAMERA_1_INDEX]);
	Camera9BasisValueLabel->Caption = IntToStr(MachineParams.CameraBrightnessEvalValue[TEST_CAMERA_9_INDEX]);

	AnsiString camEvalValueLabelNameList[TOTAL_CHECKING_CAMERA_COUNT] = { "Camera1EvalValueLabel", "Camera9EvalValueLabel" };

	if (CurrentCamListIndex < 2)
	{
		InstructionLabel1->Caption = STUDYFORM_LABEL_CAPTION_16;
	}
	else
	{
		InstructionLabel1->Caption = STUDYFORM_LABEL_CAPTION_17;
	}

	WCHAR TempString[1000];
	wsprintfW(TempString, STUDYFORM_LABEL_CAPTION_19, CurrentCamGlobalIndex + 1);
	InformationLabel1->Caption = WideString(TempString);

	if (CameraTestStatus[CurrentCamListIndex] == ECTS_NONE)
	{
		InformationLabel2->Font->Color = clWhite;
		InformationLabel2->Caption = STUDYFORM_LABEL_CAPTION_09;
	}
	else if (CameraTestStatus[CurrentCamListIndex] == ECTS_CHECKING)
	{
		InformationLabel2->Font->Color = clBlue;
		InformationLabel2->Caption = STUDYFORM_LABEL_CAPTION_10;
	}
	else if (CameraTestStatus[CurrentCamListIndex] == ECTS_OK)
	{
		InformationLabel2->Font->Color = clLime;
		InformationLabel2->Caption = STUDYFORM_LABEL_CAPTION_07;
	}
	else if (CameraTestStatus[CurrentCamListIndex] == ECTS_NG)
	{
		InformationLabel2->Font->Color = clRed;
		InformationLabel2->Caption = STUDYFORM_LABEL_CAPTION_08;
	}

	for (int camListIndex = 0; camListIndex < TOTAL_CHECKING_CAMERA_COUNT; camListIndex++)
	{
		TTntLabel *camEvalValueLabel = (TTntLabel *)FindComponent(camEvalValueLabelNameList[camListIndex]);
		switch (CameraTestStatus[camListIndex])
		{
		case ECTS_NONE:

			camEvalValueLabel->Font->Color = clYellow;
			camEvalValueLabel->Caption = STUDYFORM_LABEL_CAPTION_14;

			break;

		case ECTS_CHECKING:

			camEvalValueLabel->Font->Color = clBlue;
			camEvalValueLabel->Caption = STUDYFORM_LABEL_CAPTION_15;

			break;

		case ECTS_OK:

			camEvalValueLabel->Font->Color = clLime;
			if (MachineParams.CameraBrightnessEvalValue[camListIndex])
			{
				WCHAR TempString[100];
				wsprintfW(TempString, L"%d(%d%%)", CameraEvalValue[camListIndex], CameraEvalValue[camListIndex] * 100 / MachineParams.CameraBrightnessEvalValue[camListIndex]);
				camEvalValueLabel->Caption = TempString;
			}
			else
			{
				camEvalValueLabel->Caption = IntToStr(CameraEvalValue[camListIndex]);
			}

			break;

		case ECTS_NG:

			camEvalValueLabel->Font->Color = clRed;
			if (MachineParams.CameraBrightnessEvalValue[camListIndex])
			{
				WCHAR TempString[100];
				wsprintfW(TempString, L"%d(%d%%)", CameraEvalValue[camListIndex], CameraEvalValue[camListIndex] * 100 / MachineParams.CameraBrightnessEvalValue[camListIndex]);
				camEvalValueLabel->Caption = TempString;
			}
			else
			{
				camEvalValueLabel->Caption = IntToStr(CameraEvalValue[camListIndex]);
			}

			break;
		}
	}

	if (CameraTestStatus[TEST_CAMERA_1_INDEX] == ECTS_OK &&
		CameraTestStatus[TEST_CAMERA_9_INDEX] == ECTS_OK)
	{
		StudyEnableButton->Enabled = true;
	}

}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::CaptureSetup(void)
{
	if (SendSPBCaptureSetup())
	{
		TCaptureCommandParam_HCB captureCommandParam_HCB;
		captureCommandParam_HCB.Action = 1;

    int getCaptureIndex = 0;

		if (CurrentCamGlobalIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX - 1)
		{
      getCaptureIndex = 0;

      int maskValue = (0x0001 << CurrentCamGlobalIndex);
      for(int captureIndex = 0; captureIndex < SYSTEM_MACHINE_CAPTURE_COUNT; captureIndex++)
      {
        if(MachineSetupData.MachineCaptureInfo.CamMask[captureIndex] & maskValue)
        {
          getCaptureIndex = captureIndex;
          break;
        }
      }
		}
		else if (CurrentCamGlobalIndex == SD2_2D_FRONT_FACE_CAMERA_INDEX - 1)
		{
      getCaptureIndex = 3;

      int maskValue = (0x0001 << CurrentCamGlobalIndex);
      for(int captureIndex = 0; captureIndex < SYSTEM_MACHINE_CAPTURE_COUNT; captureIndex++)
      {
        if(MachineSetupData.MachineCaptureInfo.CamMask[captureIndex] & maskValue)
        {
          getCaptureIndex = captureIndex;
          break;
        }
      }
		}

    captureCommandParam_HCB.LEDMask[0] = 0;
    captureCommandParam_HCB.LEDMask[0] |= MachineSetupData.MachineCaptureInfo.IlluminatorMask[getCaptureIndex];

    for(int captureIndex = 0; captureIndex < SYSTEM_MACHINE_CAPTURE_COUNT; captureIndex++)
    {
      captureCommandParam_HCB.LEDOnTime[captureIndex] = 13 * 20 + 0.5; // default
    }

		captureCommandParam_HCB.FrameTime = 100 * 20 + 0.5;     // per 100 ms
		captureCommandParam_HCB.ShutterDelay = 1 * 20 + 0.5;    // capture after 1ms

		if (Comm_Request(COMM_HCB, CMD_TABLET_CAPTURE, &captureCommandParam_HCB, sizeof(TCaptureCommandParam_HCB),
			NULL, 0))
		{
			//bOnCapture = true;
		}
	}
}
//---------------------------------------------------------------------------
bool __fastcall TStudyForm::SendSPBCaptureSetup(void)
{
	bool returnValue = true;

	TCaptureSetupData captureSetupData;
	int spbIndex, camIndex;

	AnsiString shutterSpeedFileName = ProgramPath.Env + "\\ShutterSpeedInfor.ini";
	TIniFile *inifiles = new TIniFile(shutterSpeedFileName);

	int whiteColorShutterSpeed;
	if (inifiles)
	{
		whiteColorShutterSpeed = inifiles->ReadInteger("White", "Shutter Speed1", 17);
	}

	delete inifiles;

  int writeMask = 0;
	writeMask |= CAMERA_WRITE_MASK_2D_SH;
	writeMask |= CAMERA_WRITE_MASK_2D_ROI;

  bool cameraEnabled[SYSTEM_TOTAL_CAMERA_COUNT];
  for(int cameraIndex = 0; cameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; cameraIndex++)
  {
    if (CameraMapInfo[cameraIndex].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[cameraIndex] == 0)
    {
      cameraEnabled[cameraIndex] = false;
    }
    else if(ProductData.TabletType == TABLET_TYPE_SUGAR_COATED && (cameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                    cameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                    cameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                    cameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1))
    {
      cameraEnabled[cameraIndex] = false;
    }
    else
    {
      cameraEnabled[cameraIndex] = true;
    }

    if (cameraEnabled[cameraIndex])
    {
      if(CameraMapInfo[cameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
      {
        int ThreedCameraIndex = 0;
        if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX-1) ThreedCameraIndex = 0;
        else ThreedCameraIndex = 1;

        if(ThreeDParamSetSatus[ThreedCameraIndex] == 0)
        {
          if(ProductData.ExposureTime3D[ThreedCameraIndex] != -1)
          {
            Set3DCamera_CaptureParameter(cameraIndex,ProductData.AnalogGain3D[ThreedCameraIndex],ProductData.ExposureTime3D[ThreedCameraIndex]);
          }
          else
          {
            Set3DCamera_CaptureParameter(cameraIndex,ThreeDCameraDefaultInformation[cameraIndex].AnalogCameraGain,ThreeDCameraDefaultInformation[cameraIndex].ExposureTime);
          }
          ThreeDParamSetSatus[ThreedCameraIndex] = 1;
        }
      }
    }
  }

  RefreshCameraInfoForInspectionSetting(&ProductData, whiteColorShutterSpeed, writeMask, CurrentCamGlobalIndex, cameraEnabled, true);
  SetCameraGain(CurrentCamGlobalIndex + 1, SYSTEM_DEFAULT_ANLOG_GAIN, 1, 0);

	spbIndex = CameraMapInfo[CurrentCamGlobalIndex].SPBIndex;
	camIndex = CameraMapInfo[CurrentCamGlobalIndex].CamIndex;

	captureSetupData.CaptureType = CAPTURE_TYPE_SINGLE_CAPTURE;
	captureSetupData.CaptureMode = CAPTURE_MODE_DEFAULT;
	captureSetupData.FrameBufferCount = 2;
	captureSetupData.ShutterSpeed[camIndex] = whiteColorShutterSpeed;	// whiteColor
	captureSetupData.ShutterDelay[camIndex] = 0;

  if(ProductData.SubSamplingMode == IMAGE_FULL_SCALE_MODE)
    captureSetupData.SubsamplingMode[camIndex] = RESOLUTION_HIGH_QUALITY;
  else
    captureSetupData.SubsamplingMode[camIndex] = RESOLUTION_NORMAL_QUALITY;

	int defaultTriggerFreq;

  if(CurrentCamGlobalIndex + 1 < HALF_INSPECTION_CAMERA_INDEX)
    defaultTriggerFreq = RANGER_3D_BASE_SHUTTER_SPEED;
  else
    defaultTriggerFreq = RANGER_3D_BASE_SHUTTER_SPEED2;

  bool ApplyLSFTable = false;
  if(PCProgramOption.ApplyLSFTableSW)
  {
    if(CurrentCamGlobalIndex + 1 < HALF_INSPECTION_CAMERA_INDEX)
    {
      if(GlobalSD1LSFTable[ProductData.StudyMotorSpeedList[SD1_MOTOR_INDEX][0]])
      {
        defaultTriggerFreq = GlobalSD1LSFTable[ProductData.StudyMotorSpeedList[SD1_MOTOR_INDEX][0]];
        ApplyLSFTable = true;
      }
    }
    else
    {
      if(GlobalSD2LSFTable[ProductData.StudyMotorSpeedList[SD2_MOTOR_INDEX][0]])
      {
        defaultTriggerFreq = GlobalSD2LSFTable[ProductData.StudyMotorSpeedList[SD2_MOTOR_INDEX][0]];
        ApplyLSFTable = true;
      }
    }
  }

  if(ApplyLSFTable)
  {
    captureSetupData.TriggerFreq[camIndex] = defaultTriggerFreq;
  }
  else
  {
    if(CurrentCamGlobalIndex + 1 < HALF_INSPECTION_CAMERA_INDEX)
    {
      captureSetupData.TriggerFreq[camIndex] = defaultTriggerFreq *
        ProductData.StudyMotorSpeedList[SD1_MOTOR_INDEX][0] / MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed;
    }
    else
    {
      captureSetupData.TriggerFreq[camIndex] = defaultTriggerFreq *
        ProductData.StudyMotorSpeedList[SD2_MOTOR_INDEX][0] / MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed;
    }
  }

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

  //captureSetupData.SubSamplingMode = ProductData.SubSamplingMode;
	captureSetupData.TabletType = ProductData.TabletType;
	captureSetupData.SensorLength= ProductData.StudiedSensor1Length;
	if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_SETUP, &captureSetupData, sizeof(TCaptureSetupData),
		NULL, 0))
	{
		returnValue = false;
	}

	return returnValue;
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::CameraSelectPanelClick(TObject *Sender)
{
	AnsiString panelNameList[TOTAL_CHECKING_CAMERA_COUNT] = { "Camera1SelectPanel", "Camera9SelectPanel" };
	int globalCamIndexList[TOTAL_CHECKING_CAMERA_COUNT] = { SD1_2D_FRONT_FACE_CAMERA_INDEX - 1, SD2_2D_FRONT_FACE_CAMERA_INDEX - 1 };
	TTntPanel *thePanel = (TTntPanel *)Sender;
	CurrentCamListIndex = thePanel->Tag;
	CurrentCamGlobalIndex = globalCamIndexList[CurrentCamListIndex];

	for (int camListIndex = 0; camListIndex < TOTAL_CHECKING_CAMERA_COUNT; camListIndex++)
	{
		TTntPanel *aPanel = (TTntPanel *)FindComponent(panelNameList[camListIndex]);
		if (camListIndex == CurrentCamListIndex)
		{
			if (aPanel)
			{
				aPanel->Font->Color = clWhite;
				aPanel->Color = clBlue;
			}
		}
		else
		{
			if (aPanel)
			{
				aPanel->Font->Color = clBlack;
				aPanel->Color = clWhite;
			}
			if (CameraTestStatus[camListIndex] == ECTS_CHECKING)
			{
				CameraTestStatus[camListIndex] = ECTS_NONE;
			}
		}
	}

	CaptureSetup();
	ImageEvalCount = 0;
	RefreshBrightnessTestStatus();
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::StudyEnableButtonClick(TObject *Sender)
{
	if (IsBrightnessCheckMode)
	{
    if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE1 && MachineSetupData.Qualis_Machine1_CutomOption == 0)
    {
      if(MainForm->GetLastSafetyMode() == 0)
      {
        Comm_Request(COMM_HCB, CMD_SAFETY_REVERT);
      }
    }
		// blow off
		Machine.RingBlowerOff(0);
		Machine.RingBlowerOff(1);
		// capture stop
		TCaptureCommandParam_HCB captureCommandParam_HCB;
		captureCommandParam_HCB.Action = 0;
		Comm_Request(COMM_HCB, CMD_TABLET_CAPTURE, &captureCommandParam_HCB, sizeof(TCaptureCommandParam_HCB));

		BrightnessTestPanel->SendToBack();
		BrightnessTestTimer->Enabled = false;
		IsBrightnessCheckMode = false;
	}

	Study2MenuPanel->Visible = true;
	TLMenuPanel->Visible = false;
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::ImageEvalStartButtonClick(TObject *Sender)
{
	CameraTestStatus[CurrentCamListIndex] = ECTS_CHECKING;

	ImageEvalCount = IMAGE_EVAL_COUNT;
	ImageEvalSum = 0;
}
//---------------------------------------------------------------------------
unsigned int __fastcall TStudyForm::EvalBitmap(Graphics::TBitmap *srcBitmap, int *center)
{
	// find optimal threshold
	unsigned short histogram[256];

	memset(histogram, 0, 256 * sizeof(unsigned short));
	for (int y = 0; y < ImageHeight; y++)
	{
		byte *pBitmap = (byte *)srcBitmap->ScanLine[y];
		unsigned char avrColor;
		for (int x = 0; x < ImageWidth; x++)
		{
			avrColor = (pBitmap[3 * x] + pBitmap[3 * x + 1] + pBitmap[3 * x + 2]) / 3;
			if (histogram[avrColor] < 0xFFFF)
			{
				histogram[avrColor]++;
			}
		}
	}

	int opti_threshold = Optimal_Threshold(histogram, 0, 256, NULL, 0);

	// find center of binary image
	int centerX, centerY;

	unsigned short countY[SYSTEM_CAMERA_HD_WIDTH], countX[SYSTEM_CAMERA_HD_HEIGHT];
	memset(countY, 0, SYSTEM_CAMERA_HD_WIDTH * sizeof(unsigned short));
	memset(countX, 0, SYSTEM_CAMERA_HD_HEIGHT * sizeof(unsigned short));

	for (int y = 0; y < ImageHeight; y++)
	{
		byte *pBitmap = (byte *)srcBitmap->ScanLine[y];
		unsigned char avrColor;
		for (int x = 0; x < ImageWidth; x++)
		{
			avrColor = (pBitmap[3 * x] + pBitmap[3 * x + 1] + pBitmap[3 * x + 2]) / 3;
			if (avrColor > opti_threshold)
			{
				countY[x]++;
				countX[y]++;
			}
		}
	}

	unsigned int xSum = 0, ySum = 0;
	unsigned int xSumCount = 0, ySumCount = 0;
	for (int y = 0; y < ImageHeight; y++)
	{
		ySum += countX[y] * y;
		ySumCount += countX[y];
	}
	for (int x = 0; x < ImageWidth; x++)
	{
		xSum += countY[x] * x;
		xSumCount += countY[x];
	}

	centerX = xSum / xSumCount;
	centerY = ySum / ySumCount;

	int startY = centerY - 30;
	int endY = centerY + 30;
	int startX = centerX - 30;
	int endX = centerX + 30;
	unsigned int sum = 0, count = 0;
	for (int y = startY; y < endY; y++)
	{
		byte *pBitmap = (byte *)srcBitmap->ScanLine[y];
		for (int x = startX; x < endX; x++)
		{
			if ((centerX - x) * (centerX - x) + (centerY - y) * (centerY - y) < 20 * 20)
			{
				sum += (pBitmap[3 * x] + pBitmap[3 * x + 1] + pBitmap[3 * x + 2]);
				count++;
			}
		}
	}

	if (count > 0)
	{
		sum /= (3 * count);
	}
	else
	{
		sum = 0;
	}
	if (center)
	{
		center[0] = centerX;
		center[1] = centerY;
	}
	return sum;
}
//---------------------------------------------------------------------------

void __fastcall TStudyForm::SetDiskBasisValueButtonClick(TObject *Sender)
{
	if (CameraEvalValue[TEST_CAMERA_1_INDEX] > 0 && CameraEvalValue[TEST_CAMERA_9_INDEX] > 0)
	{
		if (MessageDlgFA(STUDYFORM_MSG_09, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
		{
			TInputTextDialog *inputTextDialog = new TInputTextDialog(this);
			if (inputTextDialog->ExecutePassword())
			{
				AnsiString passwordStr = inputTextDialog->InputText;
				if (passwordStr == "999999")
				{
					MachineParams.CameraBrightnessEvalValue[TEST_CAMERA_1_INDEX] = CameraEvalValue[TEST_CAMERA_1_INDEX];
					MachineParams.CameraBrightnessEvalValue[TEST_CAMERA_9_INDEX] = CameraEvalValue[TEST_CAMERA_9_INDEX];
					WriteMachineParams(ProgramPath.Env + "\\MachineInfor.ini", MachineParams);
				}
				else
				{
					ShowMessageFA(STUDYFORM_MSG_04);
				}
			}
			delete inputTextDialog;
		}
	}
	else
	{
		ShowMessageFA(STUDYFORM_MSG_06);
	}
	RefreshBrightnessTestStatus();
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::FormClose(TObject *Sender,
	TCloseAction &Action)
{
	if (IsBrightnessCheckMode)
	{
		// blow off
		Machine.RingBlowerOff(0);
		Machine.RingBlowerOff(1);

		// capture stop
		TCaptureCommandParam_HCB captureCommandParam_HCB;
		captureCommandParam_HCB.Action = 0;
		Comm_Request(COMM_HCB, CMD_TABLET_CAPTURE, &captureCommandParam_HCB, sizeof(TCaptureCommandParam_HCB));
	}
}
//---------------------------------------------------------------------------

void __fastcall TStudyForm::SecretPanelDblClick(TObject *Sender)
{
  if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE1 && MachineSetupData.Qualis_Machine1_CutomOption == 0)
                {
                        if(MainForm->GetLastSafetyMode() == 0)
                        {
                                Comm_Request(COMM_HCB, CMD_SAFETY_REVERT);
                        }
                }
	CameraTestStatus[TEST_CAMERA_1_INDEX] = ECTS_OK;
	CameraTestStatus[TEST_CAMERA_9_INDEX] = ECTS_OK;
	RefreshBrightnessTestStatus();
	StudyEnableButton->Click();
}
//---------------------------------------------------------------------------


void __fastcall TStudyForm::CameraImageDblClick(TObject *Sender)
{
	TOpenPictureDialog *openPictureDialog = new TOpenPictureDialog(this);
	if (openPictureDialog->Execute())
	{
		int centerPos[2];
		CameraImage->Picture->Bitmap->LoadFromFile(openPictureDialog->FileName);
		CameraEvalValue[CurrentCamListIndex] = EvalBitmap(CameraImage->Picture->Bitmap, centerPos);
		CameraTestStatus[CurrentCamListIndex] = ECTS_OK;

		double cameraRatio = MachineParams.CameraResolution[CurrentCamGlobalIndex] / 10.0;
		if (cameraRatio == 0) cameraRatio = 40.0;
		int circleRadius = 6.0 * 1000 / cameraRatio / 2;

		CameraImage->Canvas->Pen->Color = clBlue;
		CameraImage->Canvas->Pen->Width = 2;
		CameraImage->Canvas->Brush->Style = bsClear;
		CameraImage->Canvas->Ellipse(
			Rect(centerPos[0] - circleRadius, centerPos[1] - circleRadius,
				centerPos[0] + circleRadius, centerPos[1] + circleRadius));
	}

	delete openPictureDialog;
}
//---------------------------------------------------------------------------

void __fastcall TStudyForm::CloseButtonClick(TObject *Sender)
{

	if (IsBrightnessCheckMode)
	{
    if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE1 && MachineSetupData.Qualis_Machine1_CutomOption == 0)
                {
                        if(MainForm->GetLastSafetyMode() == 0)
                        {
                                Comm_Request(COMM_HCB, CMD_SAFETY_REVERT);
                        }
                }
		// blow off
		Machine.RingBlowerOff(0);
		Machine.RingBlowerOff(1);

		// capture stop
		TCaptureCommandParam_HCB captureCommandParam_HCB;
		captureCommandParam_HCB.Action = 0;
		Comm_Request(COMM_HCB, CMD_TABLET_CAPTURE, &captureCommandParam_HCB, sizeof(TCaptureCommandParam_HCB));

		BrightnessTestPanel->SendToBack();
		BrightnessTestTimer->Enabled = false;
		IsBrightnessCheckMode = false;
	}
	else
	{
		ModalResult = mrCancel;
		this->Close();
	}
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::SendStudyReadyCommand(int disk1TargetSpeed, int disk1BaseSpeed,
	int disk2TargetSpeed, int disk2BaseSpeed)
{
	StudyCount = StrToInt(StudyCountEdit->Text);

	int writeMask;

	TStudySetupData studySetupData;
	studySetupData.StudyCount = StudyCount;

	int defaultTriggerFreq;

  bool cameraEnabled[SYSTEM_TOTAL_CAMERA_COUNT];
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    if (CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[globalCameraIndex] == 0)
    {
      cameraEnabled[globalCameraIndex] = false;
    }
    else if(ProductData.TabletType == TABLET_TYPE_SUGAR_COATED && (globalCameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                    globalCameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                    globalCameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                                                                    globalCameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1))
    {
      cameraEnabled[globalCameraIndex] = false;
    }
    else
    {
      cameraEnabled[globalCameraIndex] = true;
    }

    if (cameraEnabled[globalCameraIndex])
    {
      if(CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
      {
        int ThreedCameraIndex = 0;
        if(globalCameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX-1) ThreedCameraIndex = 0;
        else ThreedCameraIndex = 1;

        if(ThreeDParamSetSatus[ThreedCameraIndex] == 0)
        {
          if(ProductData.ExposureTime3D[ThreedCameraIndex] != -1)
          {
            Set3DCamera_CaptureParameter(globalCameraIndex,ProductData.AnalogGain3D[ThreedCameraIndex],ProductData.ExposureTime3D[ThreedCameraIndex]);
          }
          else
          {
            Set3DCamera_CaptureParameter(globalCameraIndex,ThreeDCameraDefaultInformation[globalCameraIndex].AnalogCameraGain,ThreeDCameraDefaultInformation[globalCameraIndex].ExposureTime);
          }
          ThreeDParamSetSatus[ThreedCameraIndex] = 1;
        }
      }
    }
  }
  
  if(0)//MachineSetupData.LasercomplexerInfo.Laser_complexer_Enable)
  {
    if(cameraEnabled[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] == false)
    {
      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(cameraEnabled[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] == false)
    {
      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);
    }
  }

	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
    if (Comm_IsConnected(COMM_SPB + spbIndex))
    {
      studySetupData.CamMask = 0;
      for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
      {
        if(globalCameraIndex + 1 < HALF_INSPECTION_CAMERA_INDEX)
          defaultTriggerFreq = RANGER_3D_BASE_SHUTTER_SPEED;
        else
          defaultTriggerFreq = RANGER_3D_BASE_SHUTTER_SPEED2;

        bool ApplyLSFTable = false;
        if(PCProgramOption.ApplyLSFTableSW)
        {
          if(globalCameraIndex + 1 < HALF_INSPECTION_CAMERA_INDEX)
          {
            if(GlobalSD1LSFTable[disk1TargetSpeed])
            {
              defaultTriggerFreq = GlobalSD1LSFTable[disk1TargetSpeed];
              ApplyLSFTable = true;
            }
          }
          else
          {
            if(GlobalSD2LSFTable[disk2TargetSpeed])
            {
              defaultTriggerFreq = GlobalSD2LSFTable[disk2TargetSpeed];
              ApplyLSFTable = true;
            }
          }
        }

        int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
        if (spbIndex == CameraMapInfo[globalCameraIndex].SPBIndex)
        {
          for (int captureIndex = 0; captureIndex < SYSTEM_MACHINE_CAPTURE_COUNT; captureIndex++)
          {
            if (MachineSetupData.MachineCaptureInfo.CamMask[captureIndex] & (0x0001 << globalCameraIndex))
            {
              if (captureIndex < 3)
              {
                if (CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D) // 3d camera
                {
                  studySetupData.ShutterDelay[camIndex] = MachineSetupData.MachineCaptureInfo.IlluminatorDelay[captureIndex] * disk1TargetSpeed / disk1BaseSpeed;
                  studySetupData.TriggerFreq[camIndex] = defaultTriggerFreq * disk1TargetSpeed / disk1BaseSpeed;

                  if(ApplyLSFTable)
                  {
                    studySetupData.TriggerFreq[camIndex] = defaultTriggerFreq;
                  }
                }
                else
                {				
    			if(0)//MachineSetupData.LasercomplexerInfo.Laser_complexer_Enable)
			{
				studySetupData.ShutterDelay[camIndex] = (MachineSetupData.MachineCaptureInfo.IlluminatorDelay[captureIndex]-(ProductData.StudiedSensor1Length/2)) * disk1TargetSpeed / disk1BaseSpeed;
			}
			else
			{
				studySetupData.ShutterDelay[camIndex] = (MachineSetupData.MachineCaptureInfo.IlluminatorDelay[captureIndex]) * disk1TargetSpeed / disk1BaseSpeed;
			
			}	
                  studySetupData.TriggerFreq[camIndex] = 1000;
                }
              }
              else
              {
                if (CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D) // 3d camera
                {
                  studySetupData.ShutterDelay[camIndex] = MachineSetupData.MachineCaptureInfo.IlluminatorDelay[captureIndex] * disk2TargetSpeed / disk2BaseSpeed;
                  studySetupData.TriggerFreq[camIndex] = defaultTriggerFreq * disk2TargetSpeed / disk2BaseSpeed;

                  if(ApplyLSFTable)
                  {
                    studySetupData.TriggerFreq[camIndex] = defaultTriggerFreq;
                  }
                }
                else
                {
    			if(0)//MachineSetupData.LasercomplexerInfo.Laser_complexer_Enable)
			{
				studySetupData.ShutterDelay[camIndex] = (MachineSetupData.MachineCaptureInfo.IlluminatorDelay[captureIndex]-(ProductData.StudiedSensor2Length/2)) * disk2TargetSpeed / disk2BaseSpeed;
			}
			else
			{
				studySetupData.ShutterDelay[camIndex] = (MachineSetupData.MachineCaptureInfo.IlluminatorDelay[captureIndex]) * disk2TargetSpeed / disk2BaseSpeed;
			}	
                  studySetupData.TriggerFreq[camIndex] = 1000;
                }
              }
              studySetupData.ShutterSpeed[camIndex] = ProductData.ShutterSpeed[globalCameraIndex];
            }
          }

          if(ProductData.TabletType == TABLET_TYPE_SUGAR_COATED)
          {
            if(!(globalCameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                  globalCameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                  globalCameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
                  globalCameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1))
            {
              if (CameraMapInfo[globalCameraIndex].CameraInspectPosition != CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[globalCameraIndex] != 0)
              {
                studySetupData.CamMask |= (0x0001 << camIndex);
              }
            }
          }
          else
          {
            if (CameraMapInfo[globalCameraIndex].CameraInspectPosition != CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[globalCameraIndex] != 0)
            {
              studySetupData.CamMask |= (0x0001 << camIndex);
            }
          }

          if(CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
          {
            studySetupData.SubSamplingMode[camIndex] = RESOLUTION_NORMAL_QUALITY;
          }
          else
          {
            if(ProductData.SubSamplingMode == IMAGE_FULL_SCALE_MODE)
              studySetupData.SubSamplingMode[camIndex] = RESOLUTION_HIGH_QUALITY;
            else
              studySetupData.SubSamplingMode[camIndex] = RESOLUTION_NORMAL_QUALITY;
          }

          writeMask = 0;

          if (CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
            writeMask |= CAMERA_WRITE_MASK_3D_SH;
          else
            writeMask |= CAMERA_WRITE_MASK_2D_SH;

          if (CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
            writeMask |= CAMERA_WRITE_MASK_3D_ROI;
          else
            writeMask |= CAMERA_WRITE_MASK_2D_ROI;

          if (CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_3D)
          {
            writeMask |= CAMERA_WRITE_MASK_TH;
          }

          if (cameraEnabled[globalCameraIndex])
          {
            RefreshCameraInfoForInspectionSetting(&ProductData, ProductData.ShutterSpeed[globalCameraIndex], writeMask, globalCameraIndex, cameraEnabled, true);
            SetCameraGain(globalCameraIndex + 1, SYSTEM_DEFAULT_ANLOG_GAIN, ProductData.DigitalGainV[globalCameraIndex], 0);
          }
        }
      }
	studySetupData.TabletType = ProductData.TabletType;
	studySetupData.SensorLength= ProductData.StudiedSensor1Length;
	
      if (!Comm_Request(COMM_SPB + spbIndex, CMD_STUDY_READY, &studySetupData, sizeof(TStudySetupData)))
      {
        //ShowMessageFA(SPBConnection[spbIndex].GetLastErrorMessage());
      }
	
      int data;
	int side_thick = 0;
	side_thick = (ProductData.TabletSideThick * 20 *0.8) * disk1TargetSpeed / disk1BaseSpeed;
	data = (MachineSetupData.LasercomplexerInfo.Laser_deley_time-CAPTURE_INT_DELAY_50US - (ProductData.StudiedSensor1Length/2)) * disk1TargetSpeed / disk1BaseSpeed;
      if (!Comm_Request(COMM_SPB + spbIndex, CMD_GET_MAX_LASER_PROCESSING_TIME, &data, sizeof(int), NULL, 0))
      {

      }
    }
    }

  if(0)//MachineSetupData.LasercomplexerInfo.Laser_complexer_Enable)
  {
    // CAPTURE_TYPE_SINGLE_CAPTURE 모드에서는 함수가 호출되어서는 안됨
    SendThreeDCameraSensorOnOffSignal(1, RecentDisk1ThreeDCameraLSFValue, RecentDisk2ThreeDCameraLSFValue);
	}
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::StudyCountSetLabelDblClick(TObject *Sender)
{
	TLMenuPanel->Visible = true;
}
//---------------------------------------------------------------------------

void __fastcall TStudyForm::SetSPBVirtualInspectionImage()
{
  if (ProductData.SubSamplingMode == IMAGE_FULL_SCALE_MODE)
	{
		SourceImageWidth[0] = SYSTEM_CAMERA_HD_WIDTH;
		SourceImageHeight[0] = SYSTEM_CAMERA_HD_HEIGHT;

		SourceImageWidth[1] = SYSTEM_CAMERA_WIDTH;
		SourceImageHeight[1] = SYSTEM_CAMERA_HEIGHT;

		rate[0] = 2;
		rate[1] = 1;
	}
	else
	{
		SourceImageWidth[0] = SYSTEM_CAMERA_WIDTH;
		SourceImageHeight[0] = SYSTEM_CAMERA_HEIGHT;

		SourceImageWidth[1] = SYSTEM_CAMERA_WIDTH;
		SourceImageHeight[1] = SYSTEM_CAMERA_HEIGHT;

		rate[0] = 1;
		rate[1] = 1;
	}
  
	bool bThreeD;
	for (int cameraIndex = 1; cameraIndex <= SYSTEM_TOTAL_CAMERA_COUNT; cameraIndex++)
	{
		if (cameraIndex != SD1_3D_FRONT_FACE_CAMERA_INDEX &&
			cameraIndex != SD2_3D_FRONT_FACE_CAMERA_INDEX)
		{
			bThreeD = false;
		}
		else
		{
			bThreeD = true;
		}

    if(ProductData.TabletType == TABLET_TYPE_SUGAR_COATED)
    {
      if(!(cameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX ||
            cameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX ||
            cameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX ||
            cameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX))
      {
        if ((CameraMapInfo[cameraIndex - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT) && (SystemLinkCameraInfo[cameraIndex - 1] != 0))
        {
          int spbIndex = CameraMapInfo[cameraIndex - 1].SPBIndex;

          memset(BayerImage, 0, sizeof(BayerImage));
          ExtractBayerImage(BayerImage, 1, cameraIndex);

          int x, y;
          int tempAddress;
          int camnum;
          camnum = CameraMapInfo[cameraIndex - 1].CamIndex;

          Comm_RequestEx(COMM_SPB + spbIndex, CMD_VIRTUAL_INSPECTION_SET_IMAGE, &camnum, sizeof(int), BayerImage, SourceImageWidth[bThreeD] * SourceImageHeight[bThreeD]);
        }
      }
    }
    else
    {
      if ((CameraMapInfo[cameraIndex - 1].CameraInspectPosition < CAMERA_POSITION_DISCONNECT) && (SystemLinkCameraInfo[cameraIndex - 1] != 0))
      {
        int spbIndex = CameraMapInfo[cameraIndex - 1].SPBIndex;

        memset(BayerImage, 0, sizeof(BayerImage));
        ExtractBayerImage(BayerImage, 1, cameraIndex);

        int x, y;
        int tempAddress;
        int camnum;
        camnum = CameraMapInfo[cameraIndex - 1].CamIndex;

        Comm_RequestEx(COMM_SPB + spbIndex, CMD_VIRTUAL_INSPECTION_SET_IMAGE, &camnum, sizeof(int), BayerImage, SourceImageWidth[bThreeD] * SourceImageHeight[bThreeD]);
      }
    }
	}
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::TLMenuPanelDblClick(TObject *Sender)
{
  if(Panel143->Visible == false)
  {
    BrightnessTestButton->Height = 30;
    Panel143->Visible = true;
  }
  else
  {
    BrightnessTestButton->Height = 55;
    Panel143->Visible = false;
  }
}
//---------------------------------------------------------------------------
void __fastcall TStudyForm::TntFormActivate(TObject *Sender)
{
  SetScreenPosition(this);  
}
//---------------------------------------------------------------------------

