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

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

#include "MachineSetupProcess_Form.h"
#include "Message_Form.h"
#include "Environment.h"
#include "MotorSpeedSelection_Form.h"
#include "Bayer.h"
#include "MachineControl.h"
#include "MultiLanguage.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "TntButtons"
#pragma link "TntComCtrls"
#pragma link "TntExtCtrls"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"
TMachineSetupProcessForm *MachineSetupProcessForm;
//---------------------------------------------------------------------------
__fastcall TMachineSetupProcessForm::TMachineSetupProcessForm(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();

	SettingStep = 0;

  if(ProductData.SubSamplingMode == 0)
  {
    CAM_Width =  SYSTEM_CAMERA_WIDTH;
    CAM_Height =  SYSTEM_CAMERA_HEIGHT;
  }
  else
  {
    CAM_Width =  SYSTEM_CAMERA_HD_WIDTH;
    CAM_Height =  SYSTEM_CAMERA_HD_HEIGHT;
  }
  
	SelectedControlIndex = -1;
	DSSelectedControlIndex = -1;
	DCSelectedControlIndex = -1;

	NCPosParamMul[0] = NC_POS_PARAM_1_MUL;
	NCPosParamMul[1] = NC_POS_PARAM_2_MUL;
	NCPosParamMul[2] = NC_POS_PARAM_3_MUL;
	NCPosParamMul[3] = NC_POS_PARAM_4_MUL;
	NCPosParamMul[4] = NC_POS_PARAM_5_MUL;

	NCPosParamDiv[0] = NC_POS_PARAM_1_DIV;
	NCPosParamDiv[1] = NC_POS_PARAM_2_DIV;
	NCPosParamDiv[2] = NC_POS_PARAM_3_DIV;
	NCPosParamDiv[3] = NC_POS_PARAM_4_DIV;
	NCPosParamDiv[4] = NC_POS_PARAM_5_DIV;

	UserMinusLimitPortIndex[0] = IP_NC_1_LIMIT_L;
	UserPlusLimitPortIndex[0] = IP_NC_1_LIMIT_H;
	UserMinusLimitPortIndex[1] = IP_NC_2_LIMIT_L;
	UserPlusLimitPortIndex[1] = IP_NC_2_LIMIT_H;
	UserMinusLimitPortIndex[2] = IP_NC_3_LIMIT_H;
	UserPlusLimitPortIndex[2] = IP_NC_3_LIMIT_L;
	UserMinusLimitPortIndex[3] = IP_NC_4_LIMIT_H;
	UserPlusLimitPortIndex[3] = IP_NC_4_LIMIT_L;
	UserMinusLimitPortIndex[4] = IP_NC_5_LIMIT_L;
	UserPlusLimitPortIndex[4] = IP_NC_5_LIMIT_H;

	OnCapture = false;

  CaptureImage1->Picture->Bitmap->Width = CAM_Width;
  CaptureImage1->Picture->Bitmap->Height = CAM_Height;
  CaptureImage1->Picture->Bitmap->PixelFormat = pf24bit;
  CaptureImage2->Picture->Bitmap->Width = CAM_Width;
  CaptureImage2->Picture->Bitmap->Height = CAM_Height;
  CaptureImage2->Picture->Bitmap->PixelFormat = pf24bit;

	CaptureImage[0] = CaptureImage1;
	CaptureImage[1] = CaptureImage2;
	UploadingCameraIndex[0] = SD1_2D_FRONT_FACE_CAMERA_INDEX - 1; // For SELMA200, 20180223, moon
	UploadingCameraIndex[1] = SD2_2D_FRONT_FACE_CAMERA_INDEX - 1; // For SELMA200, 20180223, moon

	MachineSetupMode = EMSM_SETUP;
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::GetDefaultString()
{
	NextBitBtn->Caption = MACHINESETUPPROCESSFORM_BITBTN_CAPTION_01;
	PrevBitBtn->Caption = MACHINESETUPPROCESSFORM_BITBTN_CAPTION_02;
	CancelBitBtn->Caption = MACHINESETUPPROCESSFORM_BITBTN_CAPTION_03;

	MCBFIDSpeedChangeButton->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_02;
	
	MCSDSpeedChangeButton->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_02;
	CaptureStartSpeedButton->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_03;
	VFRunSpeedButton->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_03;
	CaptureStopSpeedButton->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_04;
	VFStopSpeedButton->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_04;
	BFSpeedChangeButton1->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_01;
	BFSpeedChangeButton2->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_02;	
	BFSpeedChangeButton3->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_02;	
	GroupBox31->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_01;
	GroupBox33->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_02;
	GroupBox10->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_03;
	GroupBox7->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_04;
	
	GroupBox6->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_06;
	GroupBox30->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_07;
	GroupBox5->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_08;
	GroupBox29->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_09;
	GroupBox34->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_10;
	GroupBox9->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_11;
	NCControlGroupBox->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_12;
	DSNCControlGroupBox->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_12;
	DCNCControlGroupBox->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_12;

	Label38->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_01;
	Label22->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_02;
	Label41->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_03;
	Label19->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_04;
	Label74->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_05;
	Label1->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_06;
	Label49->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_07;
	Label71->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_08;
	Label75->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_09;
	Label72->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_10;
	Label73->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_11;
	Label2->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_12;
	Label10->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_13;
	Label13->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_14;
	Label11->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_15;
	Label30->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_16;
	Label8->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_16;
	Label28->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_17;
	Label12->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_18;
	Label14->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_19;
	Label77->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_20;
	Label93->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_21;
	Label3->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_22;
	Label46->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_23;
	Label54->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_24;
	Label37->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_25;

	Label81->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_27;
	Label79->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_28;
	Label21->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_29;
	Label78->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_30;
	Label69->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_31;
	Label90->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_32;
	Label20->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_33;
	Label39->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_33;
	Label23->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_33;
	Label44->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_34;
	Label17->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_34;
	TntLabel2->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_34;
	Label16->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_35;
	Label35->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_35;
	Label18->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_35;
	Label36->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_36;
	Label31->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_37;
	Label29->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_37;
	Label34->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_37;
	Label76->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_38;
	Label53->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_39;
	Label27->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_40;
	Label70->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_07;
	NCInterlockAPanel->Caption = MACHINESETUPPROCESSFORM_PANEL_CAPTION_01;
	MCBFODinSpeedChangeButton->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_02;
	MCBFODoutSpeedChangeButton->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_02;

	//ID 없음, 임시
	Label9->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_17;
	Label40->Caption = GRADESETTINGUSER_TEXT_CAPTION_01;
	Label47->Caption = NEW_ADD_STRING_01;
	Label48->Caption = NEW_ADD_STRING_02;
	Label50->Caption = NEW_ADD_STRING_03;
	Label51->Caption = NEW_ADD_STRING_04;

    BFRunSpeedButton1->Caption = MACHINESETUPPROCESSFORM_BITBTN_CAPTION_06;
    BFStopSpeedButton->Caption = MACHINESETUPPROCESSFORM_BITBTN_CAPTION_07;

    BFRunSpeedButton2->Caption = MACHINESETUPPROCESSFORM_BITBTN_CAPTION_06;
    BFStopSpeedButton2->Caption = MACHINESETUPPROCESSFORM_BITBTN_CAPTION_07;

    AirKnifeOnSpeedButton->Caption 	= MACHINESETUPPROCESSFORM_BITBTN_CAPTION_04;
    AirKnifeOffSpeedButton->Caption = MACHINESETUPPROCESSFORM_BITBTN_CAPTION_05;

	SuctionOnSpeedButton1->Caption 	= MACHINESETUPPROCESSFORM_BITBTN_CAPTION_04;
    SuctionOffSpeedButton1->Caption = MACHINESETUPPROCESSFORM_BITBTN_CAPTION_05;

    SuctionOnSpeedButton2->Caption 	= MACHINESETUPPROCESSFORM_BITBTN_CAPTION_04;
    SuctionOffSpeedButton2->Caption = MACHINESETUPPROCESSFORM_BITBTN_CAPTION_05;

    StepMotorMinusLimitPanel3->Caption 	= "- " + MACHINESETUPPROCESSFORM_PANEL_CAPTION_02;
    StepMotorPlusLimitPanel3->Caption 	= "+ " + MACHINESETUPPROCESSFORM_PANEL_CAPTION_02;

    StepMotorMinusLimitPanel4->Caption 	= "- " + MACHINESETUPPROCESSFORM_PANEL_CAPTION_02;
    StepMotorPlusLimitPanel4->Caption 	= "+ " + MACHINESETUPPROCESSFORM_PANEL_CAPTION_02;

    StepMotorMinusLimitPanel1->Caption 	= "- " + MACHINESETUPPROCESSFORM_PANEL_CAPTION_02;
    StepMotorPlusLimitPanel1->Caption 	= "+ " + MACHINESETUPPROCESSFORM_PANEL_CAPTION_02;

    StepMotorMinusLimitPanel5->Caption 	= "- " + MACHINESETUPPROCESSFORM_PANEL_CAPTION_02;
    StepMotorPlusLimitPanel5->Caption 	= "+ " + MACHINESETUPPROCESSFORM_PANEL_CAPTION_02;

    StepMotorMinusLimitPanel2->Caption 	= "- " + MACHINESETUPPROCESSFORM_PANEL_CAPTION_02;
    StepMotorPlusLimitPanel2->Caption 	= "+ " + MACHINESETUPPROCESSFORM_PANEL_CAPTION_02;

    if(MachineSetupData.MachineType < 2)
    {
	//TntGroupBox1->Caption ="회전 가이드 외측 디스크";
	GroupBox8->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_05;
	MCBFODinSpeedChangeButton->Caption = MACHINESETUPPROCESSFORM_BUTTON_CAPTION_02;
	MCBFODoutSpeedChangeButton->Visible = false;	
	TntGroupBox1->Visible = false;
	
	Label88->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_26;
	//TntLabel1->Caption = "회전가이드 외측 디스크 속도";
	TntLabel1->Visible = false;
	MCBFODOutSpeedLabel->Visible = false;
	MCBFODoutSpeedChangeButton->Visible = false;
    }
    else
    {
	TntGroupBox1->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_14;
	GroupBox8->Caption = MACHINESETUPPROCESSFORM_GROUPBOX_CAPTION_13;
	
	MCBFODoutSpeedChangeButton->Visible = true;	
	TntGroupBox1->Visible = true;
	
	Label88->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_41;
	TntLabel1->Caption = MACHINESETUPPROCESSFORM_LABEL_CAPTION_42;
	TntLabel1->Visible = true;
	MCBFODOutSpeedLabel->Visible = true;
	MCBFODoutSpeedChangeButton->Visible = true;
    }
    

}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::FormCreate(TObject *Sender)
{
	ServoMotorSpeedToRPMParam[0] = SERVO_MOTOR_SPEED_TO_RPM_PARAM1;
	ServoMotorSpeedToRPMParam[1] = SERVO_MOTOR_SPEED_TO_RPM_PARAM2;
	ServoMotorSpeedToRPMParam[2] = SERVO_MOTOR_SPEED_TO_RPM_PARAM3;
	ServoMotorSpeedToRPMParam[3] = SERVO_MOTOR_SPEED_TO_RPM_PARAM4;
    ServoMotorSpeedToRPMParam[4] = SERVO_MOTOR_SPEED_TO_RPM_PARAM5;

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

	for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
	{
		MachineSettingNCMotorPos[stepMotorIndex] = ProductData.NCMotorPos[stepMotorIndex];
	}

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

	ShutterSpeedEdit1->Text = IntToStr(ShutterSpeed[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1]); // For SELMA200, 20180223, moon
	ShutterSpeedEdit2->Text = IntToStr(ShutterSpeed[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1]); // For SELMA200, 20180223, moon


	MainSettingTabSheet->TabVisible = false;
	RotateGuideSettingTabSheet->TabVisible = false;
	PEGuideSettingTabSheet->TabVisible = false;
	VerticalGateSettingTabSheet->TabVisible = false;
	VerticalGateWarningTabSheet->TabVisible = false;
	BowlFeederSettingTabSheet->TabVisible = false;
	BowlFeederMoveWarningTabSheet->TabVisible = false;
	DiskDistanceSettingTabSheet->TabVisible = false;
	DiskCenterSettingTabSheet->TabVisible = false;
	ProcessEndTabSheet->TabVisible = false;

	RefreshForm();
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::RefreshForm(void)
{
	if (SettingStep == 0)
	{
		PrevBitBtn->Enabled = false;
	}
	else
	{
		PrevBitBtn->Enabled = true;
	}

	if (SettingStep == 0)
	{
		MachineSettingPageControl->ActivePage = MainSettingTabSheet;
	}
	else if (SettingStep == 1)
	{
		MachineSettingPageControl->ActivePage = RotateGuideSettingTabSheet;

        if(MachineSetupData.MachineType == MACHINE_TYPE_SELMA_ADVANCED || MachineSetupData.MachineType == MACHINE_TYPE_LIMA_ADVANCED )
        {
			RotGuideImage->Picture->LoadFromFile(ProgramPath.Env + "\\RotGuide_in.bmp");
        }
        else
        {
			RotGuideImage->Picture->LoadFromFile(ProgramPath.Env + "\\RotGuide.bmp");        
        }

		RotGuideSettingTabletWidthLabel->Caption = FloatToStr(ProductData.TabletWidth);
		RotGuideLabel->Caption = "1 - " + IntToStr(ProductData.RotatingGuideKind);
	}
	else if (SettingStep == 2)
	{
		MachineSettingPageControl->ActivePage = RotateGuideSettingTabSheet;
		RotGuideImage->Picture->LoadFromFile(ProgramPath.Env + "\\RotGuide_out.bmp");
		RotGuideSettingTabletWidthLabel->Caption = FloatToStr(ProductData.TabletWidth);
		RotGuideLabel->Caption = "2 - " + IntToStr(ProductData.RotatingGuideKind);
	}	
	else if (SettingStep == 3)
	{
		if(MachineSetupData.MachineType < 2)
		{
			PEGuideLabel->Caption = "3 - " + IntToStr(ProductData.FixedGuideKind);
		}
		else
		{
			PEGuideLabel->Caption = "2 - " + IntToStr(ProductData.FixedGuideKind);
		}
		MachineSettingPageControl->ActivePage = PEGuideSettingTabSheet;
		PEGuideImage->Picture->LoadFromFile(ProgramPath.Env + "\\PEGuide.bmp");
		PEGuideSettingTabletWidthLabel->Caption = FloatToStr(ProductData.TabletWidth);
		
	}
	else if (SettingStep == 4)
	{
		MachineSettingPageControl->ActivePage = VerticalGateSettingTabSheet;
		VerticalGateImage->Picture->LoadFromFile(ProgramPath.Env + "\\VGate.bmp");
		VerticalGateTabletWidthLabel->Caption = FloatToStr(ProductData.TabletWidth);
		VerticalGateIndLabel1->Caption = "2 - " + IntToStr(ProductData.VerticalGate2Kind);
	}
	else if (SettingStep == 5)
	{
		MachineSettingPageControl->ActivePage = VerticalGateWarningTabSheet;
	}
	else if (SettingStep == 6)
	{
		MachineSettingPageControl->ActivePage = BowlFeederSettingTabSheet;
		for (int motorIndex = BF_ID_MOTOR_INDEX; motorIndex <= BF_OD_OUT_MOTOR_INDEX; motorIndex++)
		{
			TTntLabel *motorSpeedLabel = (TTntLabel *)FindComponent("MotorSpeedLabel" + IntToStr(motorIndex - BF_ID_MOTOR_INDEX + 1));
			motorSpeedLabel->Caption = IntToStr(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed * 100 / ServoMotorSpeed[motorIndex]) + "%(" +
				IntToStr((int)(ServoMotorSpeedToRPMParam[motorIndex] / ServoMotorSpeed[motorIndex])) + "RPM)";
		}
	}
	else if (SettingStep == 7)
	{
		MachineSettingPageControl->ActivePage = BowlFeederMoveWarningTabSheet;
	}
	else if (SettingStep == 8)
	{
		MachineSettingPageControl->ActivePage = DiskDistanceSettingTabSheet;
	}
	else if (SettingStep == 9)
	{
		MachineSettingPageControl->ActivePage = DiskCenterSettingTabSheet;

		MCBFIDSpeedLabel->Caption = IntToStr(MachineSetupData.ServoMotorData[BF_ID_MOTOR_INDEX].BaseSpeed * 100 / ServoMotorSpeed[BF_ID_MOTOR_INDEX]) + "%(" +
			IntToStr((int)(ServoMotorSpeedToRPMParam[BF_ID_MOTOR_INDEX] / ServoMotorSpeed[BF_ID_MOTOR_INDEX])) + "RPM)";
		MCBFODInSpeedLabel->Caption = IntToStr(MachineSetupData.ServoMotorData[BF_OD_IN_MOTOR_INDEX].BaseSpeed * 100 / ServoMotorSpeed[BF_OD_IN_MOTOR_INDEX]) + "%(" +
			IntToStr((int)(ServoMotorSpeedToRPMParam[BF_OD_IN_MOTOR_INDEX] / ServoMotorSpeed[BF_OD_IN_MOTOR_INDEX])) + "RPM)";
		if(MachineSetupData.MachineType == MACHINE_TYPE_SELMA_ADVANCED || MachineSetupData.MachineType == MACHINE_TYPE_LIMA_ADVANCED)		
		{
			MCBFODOutSpeedLabel->Caption = IntToStr(MachineSetupData.ServoMotorData[BF_OD_OUT_MOTOR_INDEX].BaseSpeed * 100 / ServoMotorSpeed[BF_OD_OUT_MOTOR_INDEX]) + "%(" +
				IntToStr((int)(ServoMotorSpeedToRPMParam[BF_OD_OUT_MOTOR_INDEX] / ServoMotorSpeed[BF_OD_OUT_MOTOR_INDEX])) + "RPM)";	
		}
		MCSDSpeedLabel->Caption = IntToStr(MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed * 100 / ServoMotorSpeed[SD1_MOTOR_INDEX]) + "%(" +
			IntToStr((int)(ServoMotorSpeedToRPMParam[SD1_MOTOR_INDEX] / ServoMotorSpeed[SD1_MOTOR_INDEX])) + "RPM)";
	}
	else if (SettingStep == 10)
	{
		MachineSettingPageControl->ActivePage = ProcessEndTabSheet;
	}
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::PrevBitBtnClick(TObject *Sender)
{
	if (SettingStep == 0)
	{
		Machine.MachineCleaning();
	}
	else if (SettingStep == 3)
	{
		if(MachineSetupData.MachineType < 2)
		{
			SettingStep--;
		}	
	}
	else if (SettingStep == 6)
	{
		Machine.ServoMotorStop(BF_ID_MOTOR_INDEX, MachineSetupData.ServoMotorData[BF_ID_MOTOR_INDEX].DecTime);
		Machine.ServoMotorStop(BF_OD_IN_MOTOR_INDEX, MachineSetupData.ServoMotorData[BF_OD_IN_MOTOR_INDEX].DecTime);
		Machine.ServoMotorStop(BF_OD_OUT_MOTOR_INDEX, MachineSetupData.ServoMotorData[BF_OD_OUT_MOTOR_INDEX].DecTime);
		Machine.BowlFeederAKSpeedChange(0);
	}
	else if (SettingStep == 8)
	{
		Machine.RingBlowerOff(0);
		Machine.RingBlowerOff(1);
	}
	else if (SettingStep == 9)
	{
		Machine.MachineStop();
		Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP);
		CaptureCheckTimer->Enabled = false;
	}

	SettingStep--;
	RefreshForm();
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::NextBitBtnClick(TObject *Sender)
{
	bool bCanProceed = true;
	if (SettingStep == 0)
	{
		Machine.MachineCleaning();
	}
	else if (SettingStep == 4)
	{
		bool bOriginNotDetected = false;
		for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
		{
			if (!Machine.Status.OriginDetected[stepMotorIndex])
			{
				bOriginNotDetected = true;
				break;
			}
		}

		bool bMotorMoving = false;
		for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
		{
			if (Machine.Status.StepMotorMoving[stepMotorIndex])
			{
				bMotorMoving = true;
				break;
			}
		}
		if (bOriginNotDetected)
		{
			ShowMessageFA(MACHINESETUPPROCESSFORM_MSG_02);
			bCanProceed = false;
		}
		else if (bMotorMoving)
		{
			ShowMessageFA(MACHINESETUPPROCESSFORM_MSG_01);
			bCanProceed = false;
		}
	}
	else if (SettingStep == 5)
	{
		Machine.NCMovePos(VG1_UP_DOWN_MOTOR_INDEX, MachineSettingNCMotorPos[VG1_UP_DOWN_MOTOR_INDEX]);
		Machine.NCMovePos(VG2_UP_DOWN_MOTOR_INDEX, MachineSettingNCMotorPos[VG2_UP_DOWN_MOTOR_INDEX]);
	}
	else if (SettingStep == 6)
	{
		bool bMotorMoving = false;
		for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
		{
			if (Machine.Status.StepMotorMoving[stepMotorIndex])
			{
				bMotorMoving = true;
				break;
			}
		}

		if (bMotorMoving)
		{
			ShowMessageFA(MACHINESETUPPROCESSFORM_MSG_01);
			bCanProceed = false;
		}
		else
		{
      		MachineSettingNCMotorPos[VG1_UP_DOWN_MOTOR_INDEX] = ((double)Machine.Status.StepMotorAbsEncoder[VG1_UP_DOWN_MOTOR_INDEX] * 1000.0 * (double)NCPosParamDiv[VG1_UP_DOWN_MOTOR_INDEX] / (double)NCPosParamMul[VG1_UP_DOWN_MOTOR_INDEX] + 5.0)
                                    / 10.0 / 100.0 - (double)MachineSetupData.ZeroPositionValue[VG1_UP_DOWN_MOTOR_INDEX];
      		MachineSettingNCMotorPos[VG2_UP_DOWN_MOTOR_INDEX] = ((double)Machine.Status.StepMotorAbsEncoder[VG2_UP_DOWN_MOTOR_INDEX] * 1000.0 * (double)NCPosParamDiv[VG2_UP_DOWN_MOTOR_INDEX] / (double)NCPosParamMul[VG2_UP_DOWN_MOTOR_INDEX] + 5.0)
                                    / 10.0 / 100.0 - (double)MachineSetupData.ZeroPositionValue[VG2_UP_DOWN_MOTOR_INDEX];                                    
					
			ProductData.NCMotorPos[VG1_UP_DOWN_MOTOR_INDEX] = MachineSettingNCMotorPos[VG1_UP_DOWN_MOTOR_INDEX];
			ProductData.NCMotorPos[VG2_UP_DOWN_MOTOR_INDEX] = MachineSettingNCMotorPos[VG2_UP_DOWN_MOTOR_INDEX];

			Machine.ServoMotorStop(BF_ID_MOTOR_INDEX, MachineSetupData.ServoMotorData[BF_ID_MOTOR_INDEX].DecTime);
			Machine.ServoMotorStop(BF_OD_IN_MOTOR_INDEX, MachineSetupData.ServoMotorData[BF_OD_IN_MOTOR_INDEX].DecTime);
			Machine.ServoMotorStop(BF_OD_OUT_MOTOR_INDEX, MachineSetupData.ServoMotorData[BF_OD_OUT_MOTOR_INDEX].DecTime);
			Machine.BowlFeederAKSpeedChange(0);
		}
	}
	else if (SettingStep == 7)
	{
		Machine.NCMovePos(BF_UP_DOWN_MOTOR_INDEX, MachineSettingNCMotorPos[BF_UP_DOWN_MOTOR_INDEX]);
		Machine.NCMovePos(SD2_LEFT_RIGHT_MOTOR_INDEX, MachineSettingNCMotorPos[SD2_LEFT_RIGHT_MOTOR_INDEX]);
	}
	else if (SettingStep == 8)
	{
		bool bMotorMoving = false;
		for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
		{
			if (Machine.Status.StepMotorMoving[stepMotorIndex])
			{
				bMotorMoving = true;
				break;
			}
		}

		if (bMotorMoving)
		{
			ShowMessageFA(MACHINESETUPPROCESSFORM_MSG_01);
			bCanProceed = false;
		}
		else
		{		
      		MachineSettingNCMotorPos[BF_UP_DOWN_MOTOR_INDEX] = ((double)Machine.Status.StepMotorAbsEncoder[BF_UP_DOWN_MOTOR_INDEX] * 1000.0 * (double)NCPosParamDiv[BF_UP_DOWN_MOTOR_INDEX] / (double)NCPosParamMul[BF_UP_DOWN_MOTOR_INDEX] + 5.0)
                                    / 10.0 / 100.0 - (double)MachineSetupData.ZeroPositionValue[BF_UP_DOWN_MOTOR_INDEX];     
      		MachineSettingNCMotorPos[SD2_LEFT_RIGHT_MOTOR_INDEX] = ((double)Machine.Status.StepMotorAbsEncoder[SD2_LEFT_RIGHT_MOTOR_INDEX] * 1000.0 * (double)NCPosParamDiv[SD2_LEFT_RIGHT_MOTOR_INDEX] / (double)NCPosParamMul[SD2_LEFT_RIGHT_MOTOR_INDEX] + 5.0)
                                    / 10.0 / 100.0 - (double)MachineSetupData.ZeroPositionValue[SD2_LEFT_RIGHT_MOTOR_INDEX];                                         

			ProductData.NCMotorPos[BF_UP_DOWN_MOTOR_INDEX] = MachineSettingNCMotorPos[BF_UP_DOWN_MOTOR_INDEX];
			ProductData.NCMotorPos[SD2_LEFT_RIGHT_MOTOR_INDEX] = MachineSettingNCMotorPos[SD2_LEFT_RIGHT_MOTOR_INDEX];

			Machine.NCMovePos(BF_IN_OUT_MOTOR_INDEX, MachineSettingNCMotorPos[BF_IN_OUT_MOTOR_INDEX]);
			Machine.RingBlowerOff(0);
			Machine.RingBlowerOff(1);
		}
	}
	else if (SettingStep == 9)
	{
		bool bMotorMoving = false;
		for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
		{
			if (Machine.Status.StepMotorMoving[stepMotorIndex])
			{
				bMotorMoving = true;
				break;
			}
		}

		if (bMotorMoving)
		{
			ShowMessageFA(MACHINESETUPPROCESSFORM_MSG_01);
			bCanProceed = false;
		}
		else
		{								
      		MachineSettingNCMotorPos[BF_IN_OUT_MOTOR_INDEX] = ((double)Machine.Status.StepMotorAbsEncoder[BF_IN_OUT_MOTOR_INDEX] * 1000.0 * (double)NCPosParamDiv[BF_IN_OUT_MOTOR_INDEX] / (double)NCPosParamMul[BF_IN_OUT_MOTOR_INDEX] + 5.0)
                                    / 10.0 / 100.0 - (double)MachineSetupData.ZeroPositionValue[BF_IN_OUT_MOTOR_INDEX];      
					
			ProductData.NCMotorPos[BF_IN_OUT_MOTOR_INDEX] = MachineSettingNCMotorPos[BF_IN_OUT_MOTOR_INDEX];

			Machine.MachineStop();
		}
	}
	else if (SettingStep >= 10)
	{	
		for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
		{
			machineSettingChangeData.NewNCPos[stepMotorIndex] = ProductData.NCMotorPos[stepMotorIndex];
		}
		AddCSVActionLog(ECSV_ACTION_CHANGE_MACHINE_SETTING, UserInfo.Name, ProductData.ProductName, (unsigned char *)&machineSettingChangeData, sizeof(TCSVMachineSettingChangeData));

		if (ProductDataModified())
		{
			AnsiString fileName = GetProductDataFileName(ProductData.ProductCode);
			BackupProductData(EPDBR_MACHINE_SETUP);
			WriteProductData(fileName, ProductData);
		}
		ShowMessageFA(MACHINESETUPPROCESSFORM_MSG_03);
		ModalResult = mrOk;
	}

	if (MachineSetupMode == EMSM_RESETUP && SettingStep == 4)
	{
		ShowMessageFA(MACHINESETUPPROCESSFORM_MSG_03);
		ModalResult = mrOk;
	}

	if (bCanProceed)
	{
		if (SettingStep == 1)
		{
    		if(MachineSetupData.MachineType == MACHINE_TYPE_SELMA_ADVANCED || MachineSetupData.MachineType == MACHINE_TYPE_LIMA_ADVANCED )
        	{
        		SettingStep = 2;
        	}
        	else
        	{
        		SettingStep = 3;
        	}
		}
        else
        {
			SettingStep++;
        }
		RefreshForm();
	}
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::NCReadTimerTimer(
	TObject *Sender)
{
	Machine.ReadMachineStatus();
	Machine.ReadPortStatus();

	WCHAR TempString[100];

	wsprintfW(TempString, L"%Smm", FloatToStrF(Machine.Status.StepMotorAbsEncoder[0] * (double)NCPosParamDiv[0] / NCPosParamMul[0] - MachineSetupData.ZeroPositionValue[0], ffFixed, 10, 2));
	NCPosLabel1->Caption = TempString;

	wsprintfW(TempString, L"%Smm", FloatToStrF(Machine.Status.StepMotorAbsEncoder[1] * (double)NCPosParamDiv[1] / NCPosParamMul[1] - MachineSetupData.ZeroPositionValue[1], ffFixed, 10, 2));
	NCPosLabel2->Caption = TempString;

	wsprintfW(TempString, L"%Smm", FloatToStrF(Machine.Status.StepMotorAbsEncoder[2] * (double)NCPosParamDiv[2] / NCPosParamMul[2] - MachineSetupData.ZeroPositionValue[2], ffFixed, 10, 2));
	NCPosLabel3->Caption = TempString;

	wsprintfW(TempString, L"%Smm", FloatToStrF(Machine.Status.StepMotorAbsEncoder[3] * (double)NCPosParamDiv[3] / NCPosParamMul[3] - MachineSetupData.ZeroPositionValue[3], ffFixed, 10, 2));
	NCPosLabel4->Caption = TempString;

	double suctionDisk2Position = Machine.Status.StepMotorAbsEncoder[4] * (double)NCPosParamDiv[4] / NCPosParamMul[4] - MachineSetupData.ZeroPositionValue[4];
	double suctionDiskDistance = sqrt((SUCTION_DISK_DISTANCE_BASE_X + suctionDisk2Position) * (SUCTION_DISK_DISTANCE_BASE_X + suctionDisk2Position) + SUCTION_DISK_DISTANCE_Y * SUCTION_DISK_DISTANCE_Y) - SUCTION_DISK_DIAMETER;

	wsprintfW(TempString, L"%Smm [D = %Smm]", FloatToStrF(suctionDisk2Position, ffFixed, 10, 2), FloatToStrF(suctionDiskDistance, ffFixed, 10, 2));
	NCPosLabel5->Caption = TempString;

	if (SelectedControlIndex != -1)
	{
		CurrentNCValue = (Machine.Status.StepMotorAbsEncoder[SelectedControlIndex] * (double)NCPosParamDiv[SelectedControlIndex] / NCPosParamMul[SelectedControlIndex] - MachineSetupData.ZeroPositionValue[SelectedControlIndex] + 0.005) * 100;
		int currentNCAbsValue = abs(CurrentNCValue);
		CurrentNCValueDigit[0] = currentNCAbsValue / 1000 % 10;
		CurrentNCValueDigit[1] = currentNCAbsValue / 100 % 10;
		CurrentNCValueDigit[2] = currentNCAbsValue / 10 % 10;
		CurrentNCValueDigit[3] = currentNCAbsValue / 1 % 10;

		machineSettingChangeData.NewNCPos[SelectedControlIndex] = MachineSettingNCMotorPos[SelectedControlIndex] = ((double)Machine.Status.StepMotorAbsEncoder[SelectedControlIndex] * 1000.0 * (double)NCPosParamDiv[SelectedControlIndex] / (double)NCPosParamMul[SelectedControlIndex] + 5.0)
                                    / 10.0 / 100.0 - (double)MachineSetupData.ZeroPositionValue[SelectedControlIndex];

		if (CurrentNCValue > 0)
		{
			NCValueLabel1->Caption = IntToStr(CurrentNCValueDigit[0]);
		}
		else
		{
			NCValueLabel1->Caption = "-";
		}

		NCValueLabel2->Caption = IntToStr(CurrentNCValueDigit[1]);
		NCValueLabel3->Caption = IntToStr(CurrentNCValueDigit[2]);
		NCValueLabel4->Caption = IntToStr(CurrentNCValueDigit[3]);
	}

	if (DSSelectedControlIndex != -1)
	{
		DSCurrentNCValue = (Machine.Status.StepMotorAbsEncoder[DSSelectedControlIndex] * (double)NCPosParamDiv[DSSelectedControlIndex] / NCPosParamMul[DSSelectedControlIndex] - MachineSetupData.ZeroPositionValue[DSSelectedControlIndex] + 0.005) * 100;
		int currentNCAbsValue = abs(DSCurrentNCValue);
		DSCurrentNCValueDigit[0] = currentNCAbsValue / 1000 % 10;
		DSCurrentNCValueDigit[1] = currentNCAbsValue / 100 % 10;
		DSCurrentNCValueDigit[2] = currentNCAbsValue / 10 % 10;
		DSCurrentNCValueDigit[3] = currentNCAbsValue / 1 % 10;

		machineSettingChangeData.NewNCPos[DSSelectedControlIndex] = MachineSettingNCMotorPos[DSSelectedControlIndex] = ((double)Machine.Status.StepMotorAbsEncoder[DSSelectedControlIndex] * 1000.0 * (double)NCPosParamDiv[DSSelectedControlIndex] / (double)NCPosParamMul[DSSelectedControlIndex] + 5.0)
                                    / 10.0 / 100.0 - (double)MachineSetupData.ZeroPositionValue[DSSelectedControlIndex];

		if (DSCurrentNCValue > 0)
		{
			DSNCValueLabel1->Caption = IntToStr(DSCurrentNCValueDigit[0]);
		}
		else
		{
			DSNCValueLabel1->Caption = "-";
		}
		
		DSNCValueLabel2->Caption = IntToStr(DSCurrentNCValueDigit[1]);
		DSNCValueLabel3->Caption = IntToStr(DSCurrentNCValueDigit[2]);
		DSNCValueLabel4->Caption = IntToStr(DSCurrentNCValueDigit[3]);
	}

	if (DCSelectedControlIndex != -1)
	{
		DCCurrentNCValue = (Machine.Status.StepMotorAbsEncoder[DCSelectedControlIndex] * (double)NCPosParamDiv[DCSelectedControlIndex] / NCPosParamMul[DCSelectedControlIndex] - MachineSetupData.ZeroPositionValue[DCSelectedControlIndex] + 0.005) * 100;
		int currentNCAbsValue = abs(DCCurrentNCValue);
		DCCurrentNCValueDigit[0] = currentNCAbsValue / 1000 % 10;
		DCCurrentNCValueDigit[1] = currentNCAbsValue / 100 % 10;
		DCCurrentNCValueDigit[2] = currentNCAbsValue / 10 % 10;
		DCCurrentNCValueDigit[3] = currentNCAbsValue / 1 % 10;

		machineSettingChangeData.NewNCPos[DCSelectedControlIndex] = MachineSettingNCMotorPos[DCSelectedControlIndex] = ((double)Machine.Status.StepMotorAbsEncoder[DCSelectedControlIndex] * 1000.0 * (double)NCPosParamDiv[DCSelectedControlIndex] / (double)NCPosParamMul[DCSelectedControlIndex] + 5.0)
                                    / 10.0 / 100.0 - (double)MachineSetupData.ZeroPositionValue[DCSelectedControlIndex];		

		if (DCCurrentNCValue > 0)
		{
			DCNCValueLabel1->Caption = IntToStr(DCCurrentNCValueDigit[0]);
		}
		else
		{
			DCNCValueLabel1->Caption = "-";
		}

		DCNCValueLabel2->Caption = IntToStr(DCCurrentNCValueDigit[1]);
		DCNCValueLabel3->Caption = IntToStr(DCCurrentNCValueDigit[2]);
		DCNCValueLabel4->Caption = IntToStr(DCCurrentNCValueDigit[3]);
	}
	
	for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
	{
		TTntPanel *minusLimitPanel = (TTntPanel *)FindComponent("StepMotorMinusLimitPanel" + IntToStr(stepMotorIndex + 1));
		if (minusLimitPanel)
		{
			if (Machine.PortStatus.IPStatus[UserMinusLimitPortIndex[stepMotorIndex]])
			{
				minusLimitPanel->Color = clRed;
			}
			else
			{
				minusLimitPanel->Color = clBlack;
			}
		}
		TTntPanel *plusLimitPanel = (TTntPanel *)FindComponent("StepMotorPlusLimitPanel" + IntToStr(stepMotorIndex + 1));
		if (plusLimitPanel)
		{
			if (Machine.PortStatus.IPStatus[UserPlusLimitPortIndex[stepMotorIndex]])
			{
				plusLimitPanel->Color = clRed;
			}
			else
			{
				plusLimitPanel->Color = clBlack;
			}
		}
	}

	//sjm VG2
	//if ((Machine.Status.StepMotorAbsEncoder[VG2_UP_DOWN_MOTOR_INDEX] * 100 / NC_POS_PARAM_4 -
	//		Machine.Status.StepMotorAbsEncoder[BF_UP_DOWN_MOTOR_INDEX] * 100 / NC_POS_PARAM_1)
		//if ((Machine.Status.StepMotorAbsEncoder[VG2_UP_DOWN_MOTOR_INDEX] * 100 * NC_POS_PARAM_4_DIV / NC_POS_PARAM_4_MUL -
	//	Machine.Status.StepMotorAbsEncoder[BF_UP_DOWN_MOTOR_INDEX] * 100 * NC_POS_PARAM_1_DIV / NC_POS_PARAM_1_MUL)
	//	>= MachineSetupData.InterlockInfo.NCInterlockAValue - 1)
	if ((Machine.Status.StepMotorAbsEncoder[VG2_UP_DOWN_MOTOR_INDEX] * 100 * NC_POS_PARAM_4_DIV / NC_POS_PARAM_4_MUL -
		Machine.Status.StepMotorAbsEncoder[BF_UP_DOWN_MOTOR_INDEX] * 100 * NC_POS_PARAM_1_DIV / NC_POS_PARAM_1_MUL)
	> MachineSetupData.InterlockInfo.NCInterlockAValue-1)
	{
		NCInterlockAPanel->Color = clRed;
	}
	else
	{
		NCInterlockAPanel->Color = clBlack;
	}

	bool originDetected = true;
	for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
	{
		if (!Machine.Status.OriginDetected[stepMotorIndex])
		{
			originDetected = false;
			break;
		}
	}
	/*
		FNCOriginDetected = originDetected;
		if (!FNCOriginDetected)
		{
			OriginWarningPanel->Visible = true;
		}
		else
		{
			OriginWarningPanel->Visible = false;
		}
	*/
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::BFSpeedChangeButtonClick(TObject *Sender)
{
	TTntButton *theButton = (TTntButton *)Sender;
	int motorIndex = theButton->Tag + BF_ID_MOTOR_INDEX;
	TTntLabel *motorSpeedLabel = (TTntLabel *)FindComponent("MotorSpeedLabel" + IntToStr(motorIndex - BF_ID_MOTOR_INDEX + 1));

	TMotorSpeedSelectionForm *motorSpeedSelectionForm = new TMotorSpeedSelectionForm(this);
	motorSpeedSelectionForm->SetSpeed(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed, ServoMotorSpeed[motorIndex]);
	if (motorSpeedSelectionForm->ShowModal() == mrOk)
	{
		ServoMotorSpeed[motorIndex] = motorSpeedSelectionForm->GetSelectedSpeed();
		motorSpeedLabel->Caption = IntToStr(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed * 100 / ServoMotorSpeed[motorIndex]) + "%(" +
			IntToStr((int)(ServoMotorSpeedToRPMParam[motorIndex] / ServoMotorSpeed[motorIndex])) + "RPM)";
	}
	delete motorSpeedSelectionForm;
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::BFRunSpeedButtonClick(
	TObject *Sender)
{
	TTntSpeedButton *theSpeedButton = (TTntSpeedButton *)Sender;
	int motorIndex = theSpeedButton->Tag + BF_ID_MOTOR_INDEX;
	int baseSpeed = MachineSetupData.ServoMotorData[motorIndex].BaseSpeed;
	int targetSpeed = ServoMotorSpeed[motorIndex];
	int accTime = MachineSetupData.ServoMotorData[motorIndex].AccTime;
	int dir = 0;
	if (MachineSetupData.ServoMotorData[motorIndex].Dir)
	{
		dir = 1;
	}
	else
	{
		dir = 0;
	}

	Machine.ServoMotorRun(motorIndex, baseSpeed, targetSpeed, accTime, dir);
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::BFStopSpeedButtonClick(
	TObject *Sender)
{
	TTntSpeedButton *theSpeedButton = (TTntSpeedButton *)Sender;
	int motorIndex = theSpeedButton->Tag + BF_ID_MOTOR_INDEX;
	int decTime = MachineSetupData.ServoMotorData[motorIndex].DecTime;
	Machine.ServoMotorStop(motorIndex, decTime);
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::AirKnifePowerPanelClick(
	TObject *Sender)
{
	TTntPanel *thePanel = (TTntPanel *)Sender;
	AirKnifePower = thePanel->Tag;
	for (int akpIndex = 0; akpIndex < 3; akpIndex++)
	{
		TTntPanel *akpPanel = (TTntPanel *)FindComponent("AirKnifePowerPanel" + IntToStr(akpIndex + 1));
		if (akpPanel == thePanel)
		{
			akpPanel->Color = clBlue;
			akpPanel->Font->Color = clWhite;
		}
		else
		{
			akpPanel->Color = clWhite;
			akpPanel->Font->Color = clBlack;
		}
	}
}
//---------------------------------------------------------------------------

void __fastcall TMachineSetupProcessForm::AirKnifeOnSpeedButtonClick(
	TObject *Sender)
{
	if (AirKnifePower == 0)
	{
		Machine.BowlFeederAKSpeedChange(1);
	}
	else if (AirKnifePower == 1)
	{
		Machine.BowlFeederAKSpeedChange(2);
	}
	else	// 2
	{
		Machine.BowlFeederAKSpeedChange(3);
	}
}
//---------------------------------------------------------------------------

void __fastcall TMachineSetupProcessForm::AirKnifeOffSpeedButtonClick(
	TObject *Sender)
{
	Machine.BowlFeederAKSpeedChange(0);
}
//---------------------------------------------------------------------------

void __fastcall TMachineSetupProcessForm::NCControlPanelClick(TObject *Sender)
{
	TControl *theControl = (TControl *)Sender;
	for (int panelIndex = 0; panelIndex < MAX_STEP_MOTOR_COUNT; panelIndex++)
	{
		TTntPanel *aPanel = (TTntPanel *)FindComponent("NCControlPanel" + IntToStr(panelIndex + 1));
		if (aPanel)
		{
			aPanel->Color = clBlack;
		}
	}
	if (SelectedControlIndex != theControl->Tag)
	{
		SelectedControlIndex = theControl->Tag;
		TTntPanel *aPanel = (TTntPanel *)FindComponent("NCControlPanel" + IntToStr(SelectedControlIndex + 1));
		if (aPanel)
		{
			aPanel->Color = clBlue;
		}
		NCControlGroupBox->Visible = true;
		InstructionImagePanel->Visible = true;
		InstructionImagePanel->BringToFront();

		AnsiString imageFileName;

		if (DefaultLCID == 1042 || DefaultLCID == 2066)
		{
			imageFileName = ProgramPath.Env + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
		}
		else if (DefaultLCID == 1033)
		{
			if (SelectedControlIndex != 1)
				imageFileName = ProgramPath.Env + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
			else
				imageFileName = ProgramPath.Env + "\\En" + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
		}
    else if(DefaultLCID == 1041)
    {
      if (SelectedControlIndex != 1)
				imageFileName = ProgramPath.Env + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
			else
				imageFileName = ProgramPath.Env + "\\Jp" + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
    }
		else if (DefaultLCID == 2052 || DefaultLCID == 3076 || DefaultLCID == 4100)
		{
      		if (SelectedControlIndex != 1)
				imageFileName = ProgramPath.Env + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
			else
				imageFileName = ProgramPath.Env + "\\Ch" + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";;
		}
        else if (DefaultLCID == 1028)
		{
      		if (SelectedControlIndex != 1)
				imageFileName = ProgramPath.Env + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
			else
				imageFileName = ProgramPath.Env + "\\Tiw" + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
		}
		else if (DefaultLCID == 3082)
		{
			if (SelectedControlIndex != 1)
				imageFileName = ProgramPath.Env + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
			else
				imageFileName = ProgramPath.Env + "\\Sp" + "\\NC" + IntToStr(SelectedControlIndex + 1) + ".bmp";
		}

		if (FileExists(imageFileName))
		{
			InstructionImage->Picture->LoadFromFile(imageFileName);
		}
		//this->ClientWidth = MenuPanel->Width + 1000;
	}
	else
	{
		SelectedControlIndex = -1;
		NCControlGroupBox->Visible = false;
		InstructionImagePanel->Visible = false;
		//this->ClientWidth = MenuPanel->Width;
	}
}
//---------------------------------------------------------------------------


void __fastcall TMachineSetupProcessForm::DSNCControlPanelClick(
	TObject *Sender)
{
	TControl *theControl = (TControl *)Sender;
	for (int panelIndex = 0; panelIndex < MAX_STEP_MOTOR_COUNT; panelIndex++)
	{
		TTntPanel *aPanel = (TTntPanel *)FindComponent("DSNCControlPanel" + IntToStr(panelIndex + 1));
		if (aPanel)
		{
			aPanel->Color = clBlack;
		}
	}
	if (DSSelectedControlIndex != theControl->Tag)
	{
		DSSelectedControlIndex = theControl->Tag;
		TTntPanel *aPanel = (TTntPanel *)FindComponent("DSNCControlPanel" + IntToStr(DSSelectedControlIndex + 1));
		if (aPanel)
		{
			aPanel->Color = clBlue;
		}
		DSNCControlGroupBox->Visible = true;
		DSInstructionImagePanel->Visible = true;
		DSInstructionImagePanel->BringToFront();

		AnsiString imageFileName;

		if (DefaultLCID == 1042 || DefaultLCID == 2066)
		{
			imageFileName = ProgramPath.Env + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
		}
		else if (DefaultLCID == 1033)
		{
			if (DSSelectedControlIndex != 1)
				imageFileName = ProgramPath.Env + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
			else
				imageFileName = ProgramPath.Env + "\\En" + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
		}
    else if (DefaultLCID == 1041)
    {
      if (DSSelectedControlIndex != 1)
				imageFileName = ProgramPath.Env + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
			else
				imageFileName = ProgramPath.Env + "\\Jp" + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
    }
		else if (DefaultLCID == 2052 || DefaultLCID == 3076 || DefaultLCID == 4100)
		{
      		if (DSSelectedControlIndex != 1)
				imageFileName = ProgramPath.Env + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
			else
				imageFileName = ProgramPath.Env + "\\Ch" + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
		}
		else if (DefaultLCID == 1028)
		{
      		if (DSSelectedControlIndex != 1)
				imageFileName = ProgramPath.Env + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
			else
				imageFileName = ProgramPath.Env + "\\Tiw" + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
		}
		else if (DefaultLCID == 3082)
		{
			if (DSSelectedControlIndex != 1)
				imageFileName = ProgramPath.Env + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
			else
				imageFileName = ProgramPath.Env + "\\Sp" + "\\NC" + IntToStr(DSSelectedControlIndex + 1) + ".bmp";
		}

		if (FileExists(imageFileName))
		{
			DSInstructionImage->Picture->LoadFromFile(imageFileName);
		}
		//this->ClientWidth = MenuPanel->Width + 1000;
	}
	else
	{
		DSSelectedControlIndex = -1;
		DSNCControlGroupBox->Visible = false;
		DSInstructionImagePanel->Visible = false;
		//this->ClientWidth = MenuPanel->Width;
	}
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::NCControlUpButtonClick(TObject *Sender)
{
	if (SelectedControlIndex == -1) return;

	TTntButton *theButton = (TTntButton *)Sender;
	int divVal = pow(10, theButton->Tag);

	MachineSettingNCMotorPos[SelectedControlIndex] = CurrentNCValue / 100.0 + 1.0 / divVal;
	Machine.NCMovePos(SelectedControlIndex, MachineSettingNCMotorPos[SelectedControlIndex]);
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::NCControlDownButtonClick(TObject *Sender)
{
	if (SelectedControlIndex == -1) return;

	TTntButton *theButton = (TTntButton *)Sender;
	int divVal = pow(10, theButton->Tag);

	MachineSettingNCMotorPos[SelectedControlIndex] = CurrentNCValue / 100.0 - 1.0 / divVal;
	Machine.NCMovePos(SelectedControlIndex, MachineSettingNCMotorPos[SelectedControlIndex]);
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::DSNCControlUpButtonClick(TObject *Sender)
{
	if (DSSelectedControlIndex == -1) return;

	TTntButton *theButton = (TTntButton *)Sender;
	int divVal = pow(10, theButton->Tag);

	MachineSettingNCMotorPos[DSSelectedControlIndex] = DSCurrentNCValue / 100.0 + 1.0 / divVal;
	Machine.NCMovePos(DSSelectedControlIndex, MachineSettingNCMotorPos[DSSelectedControlIndex]);
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::DSNCControlDownButtonClick(TObject *Sender)
{
	if (DSSelectedControlIndex == -1) return;

	TTntButton *theButton = (TTntButton *)Sender;
	int divVal = pow(10, theButton->Tag);

	MachineSettingNCMotorPos[DSSelectedControlIndex] = DSCurrentNCValue / 100.0 - 1.0 / divVal;
	Machine.NCMovePos(DSSelectedControlIndex, MachineSettingNCMotorPos[DSSelectedControlIndex]);
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::DCNCControlUpButtonClick(TObject *Sender)
{
	if (DCSelectedControlIndex == -1) return;

	TTntButton *theButton = (TTntButton *)Sender;
	int divVal = pow(10, theButton->Tag);

	MachineSettingNCMotorPos[DCSelectedControlIndex] = DCCurrentNCValue / 100.0 + 1.0 / divVal;
	Machine.NCMovePos(DCSelectedControlIndex, MachineSettingNCMotorPos[DCSelectedControlIndex]);
}
//---------------------------------------------------------------------------

void __fastcall TMachineSetupProcessForm::DCNCControlDownButtonClick(TObject *Sender)
{
	if (DCSelectedControlIndex == -1) return;

	TTntButton *theButton = (TTntButton *)Sender;
	int divVal = pow(10, theButton->Tag);

	MachineSettingNCMotorPos[DCSelectedControlIndex] = DCCurrentNCValue / 100.0 - 1.0 / divVal;
	Machine.NCMovePos(DCSelectedControlIndex, MachineSettingNCMotorPos[DCSelectedControlIndex]);
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::SuctionOnSpeedButtonClick(
	TObject *Sender)
{
	try
	{
		TTntSpeedButton *theButton = (TTntSpeedButton *)Sender;
		int rbIndex = theButton->Tag;
		int speed1 = ProductData.MachineRunOption.SuctionDisk1InverterSpeed;
		int speed2 = ProductData.MachineRunOption.SuctionDisk2InverterSpeed;
		Machine.RingBlowerOn(rbIndex, speed1, speed2);
	}
	catch (Exception &ec)
	{
		ShowMessageFA(ec.Message);
	}
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::SuctionOffSpeedButtonClick(
	TObject *Sender)
{
	TTntSpeedButton *theButton = (TTntSpeedButton *)Sender;
	int rbIndex = theButton->Tag;

	Machine.RingBlowerOff(rbIndex);
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::CancelBitBtnClick(
	TObject *Sender)
{
	if (SettingStep == 0)
	{
		Machine.MachineCleaning();
	}
	else if (SettingStep == 6)
	{
		Machine.ServoMotorStop(BF_ID_MOTOR_INDEX, MachineSetupData.ServoMotorData[BF_ID_MOTOR_INDEX].DecTime);
		Machine.ServoMotorStop(BF_OD_IN_MOTOR_INDEX, MachineSetupData.ServoMotorData[BF_OD_IN_MOTOR_INDEX].DecTime);
		Machine.ServoMotorStop(BF_OD_OUT_MOTOR_INDEX, MachineSetupData.ServoMotorData[BF_OD_OUT_MOTOR_INDEX].DecTime);
		Machine.BowlFeederAKSpeedChange(0);
	}
	else if (SettingStep == 8)
	{
		Machine.RingBlowerOff(0);
		Machine.RingBlowerOff(1);
	}
	else if (SettingStep == 9)
	{
		Machine.MachineStop();
		Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP);
		CaptureCheckTimer->Enabled = false;
	}

	if (MessageDlgFA(MACHINESETUPPROCESSFORM_MSG_04, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
	{
		for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
		{
			ProductData.NCMotorPos[stepMotorIndex] = machineSettingChangeData.NewNCPos[stepMotorIndex];
		}
		
		AddCSVActionLog(ECSV_ACTION_CHANGE_MACHINE_SETTING, UserInfo.Name, ProductData.ProductName, (unsigned char *)&machineSettingChangeData, sizeof(TCSVMachineSettingChangeData));

		if (ProductDataModified())
		{
			AnsiString fileName = GetProductDataFileName(ProductData.ProductCode);
			BackupProductData(EPDBR_MACHINE_SETUP);
			WriteProductData(fileName, ProductData);
		}
	}
	ModalResult = mrCancel;
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::DCNCControlPanel1Click(
	TObject *Sender)
{
	TControl *theControl = (TControl *)Sender;
	for (int panelIndex = 0; panelIndex < MAX_STEP_MOTOR_COUNT; panelIndex++)
	{
		TTntPanel *aPanel = (TTntPanel *)FindComponent("DCNCControlPanel" + IntToStr(panelIndex + 1));
		if (aPanel)
		{
			aPanel->Color = clBlack;
		}
	}
	if (DCSelectedControlIndex != theControl->Tag)
	{
		DCSelectedControlIndex = theControl->Tag;
		TTntPanel *aPanel = (TTntPanel *)FindComponent("DCNCControlPanel" + IntToStr(DCSelectedControlIndex - BF_IN_OUT_MOTOR_INDEX + 1));
		if (aPanel)
		{
			aPanel->Color = clBlue;
		}
		DCNCControlGroupBox->Visible = true;
		DCInstructionImagePanel->Visible = true;
		DCInstructionImagePanel->BringToFront();

		AnsiString imageFileName;
		if (DefaultLCID == 1042 || DefaultLCID == 2066)
		{
			imageFileName = ProgramPath.Env + "\\NC2-2.bmp";
		}
		else if (DefaultLCID == 1033)
		{
			imageFileName = ProgramPath.Env + "\\En" + "\\NC2-2.bmp";
		}
    	else if (DefaultLCID == 1041)
    	{
      		imageFileName = ProgramPath.Env + "\\Jp" + "\\NC2-2.bmp";
    	}
		else if (DefaultLCID == 2052 || DefaultLCID == 3076 || DefaultLCID == 4100)
		{
			imageFileName = ProgramPath.Env + "\\Ch" + "\\NC2-2.bmp";
		}
		else if (DefaultLCID == 1028)
		{
			imageFileName = ProgramPath.Env + "\\Tiw" + "\\NC2-2.bmp";
		}
		else if (DefaultLCID == 3082)
		{
			imageFileName = ProgramPath.Env + "\\Sp" + "\\NC2-2.bmp";
		}

		if (FileExists(imageFileName))
		{
			DCInstructionImage->Picture->LoadFromFile(imageFileName);
		}
		//this->ClientWidth = MenuPanel->Width + 1000;
	}
	else
	{
		DCSelectedControlIndex = -1;
		DCNCControlGroupBox->Visible = false;
		DCInstructionImagePanel->Visible = false;
		//this->ClientWidth = MenuPanel->Width;
	}
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::CaptureStartSpeedButtonClick(
	TObject *Sender)
{
  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;
  }
  
	MachineSettingNCMotorPos[BF_IN_OUT_MOTOR_INDEX] =
		(Machine.Status.StepMotorAbsEncoder[BF_IN_OUT_MOTOR_INDEX] * (double)NCPosParamDiv[BF_IN_OUT_MOTOR_INDEX] / NCPosParamMul[BF_IN_OUT_MOTOR_INDEX] -
			MachineSetupData.ZeroPositionValue[BF_IN_OUT_MOTOR_INDEX] + 0.005);

	TMachineRunOption machineRunOption = ProductData.MachineRunOption;
	//	machineRunOption.MaxSpeedTrainingMode = MAX_SPEED_TRAINING_MODE_MANUAL;
	//	machineRunOption.ManualMaxSpeed = 0;

	Machine.MachineRun(PROCEDURE_MODE_CAPTURE, &machineRunOption,
		MachineSettingNCMotorPos, ServoMotorSpeed);

	MachineOperationInfo.ServoMotorSpeed[SD1_MOTOR_INDEX] = ServoMotorSpeed[SD1_MOTOR_INDEX];
	MachineOperationInfo.ServoMotorSpeed[SD2_MOTOR_INDEX] = ServoMotorSpeed[SD2_MOTOR_INDEX];
	MachineOperationInfo.ServoMotorSpeed[BF_ID_MOTOR_INDEX] = ServoMotorSpeed[BF_ID_MOTOR_INDEX];
	MachineOperationInfo.ServoMotorSpeed[BF_OD_IN_MOTOR_INDEX] = ServoMotorSpeed[BF_OD_IN_MOTOR_INDEX];
	MachineOperationInfo.ServoMotorSpeed[BF_OD_OUT_MOTOR_INDEX] = ServoMotorSpeed[BF_OD_OUT_MOTOR_INDEX];

	unsigned int camMask = 0;

	for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
	{
		camMask |= (0x0001 << globalCameraIndex);
	}

	float tabletHalfLength = ProductData.TabletLength / 2;
	try
	{
    RefreshCameraInfo(SD1_2D_FRONT_FACE_CAMERA_INDEX - 1, ShutterSpeed[SD1_2D_FRONT_FACE_CAMERA_INDEX - 1]);
    RefreshCameraInfo(SD2_2D_FRONT_FACE_CAMERA_INDEX - 1, ShutterSpeed[SD2_2D_FRONT_FACE_CAMERA_INDEX - 1]);
    
    if(0)//(MachineSetupData.LasercomplexerInfo.Laser_complexer_Enable)
    {
      if((camMask & (0x0001 << (SD1_3D_FRONT_FACE_CAMERA_INDEX - 1))) == 0)
      {
        Set3DCamera_CaptureParameter(SD1_3D_FRONT_FACE_CAMERA_INDEX - 1, ThreeDCameraDefaultInformation[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].AnalogCameraGain, ThreeDCameraDefaultInformation[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].ExposureTime);
      }

      if((camMask & (0x0001 << (SD2_3D_FRONT_FACE_CAMERA_INDEX - 1))) == 0)
      {
        Set3DCamera_CaptureParameter(SD2_3D_FRONT_FACE_CAMERA_INDEX - 1, ThreeDCameraDefaultInformation[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].AnalogCameraGain, ThreeDCameraDefaultInformation[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].ExposureTime);
      }
    }
    
		if (!SendSPBCaptureSetup_Multi(&ProductData,camMask, tabletHalfLength, ShutterSpeed,
			ServoMotorSpeed[SD1_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed,
			ServoMotorSpeed[SD2_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed,ProductData.SubSamplingMode, false, 3))
			//			MotorSpeed[SD2_MOTOR_INDEX], ServoMotorInfo[SD2_MOTOR_INDEX].BaseSpeed, 128))
		{
			throw Exception("");
		}

		TMachineCaptureSetupData machineCaptureSetupData;

		memcpy(machineCaptureSetupData.IlluminatorMask, MachineSetupData.MachineCaptureInfo.IlluminatorMask, SYSTEM_MACHINE_CAPTURE_COUNT * sizeof(int));
		machineCaptureSetupData.CaptureOption = 2;
		machineCaptureSetupData.TabletSideThick = ProductData.TabletSideThick*10;
		machineCaptureSetupData.TabletLength = ProductData.TabletLength;
		machineCaptureSetupData.SuctionDiskSpeed = ServoMotorSpeed[SD1_MOTOR_INDEX];
		machineCaptureSetupData.StudiedTabletSensorLength = ProductData.TabletLength / MOTOR_SPEED_TO_LENGTH_CONSTANT_DISC_1 * 20.0 * 1000;
		if (!Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE, &machineCaptureSetupData, sizeof(TMachineCaptureSetupData),
			NULL, 0))
		{
			throw Exception("");
		}

		CaptureCheckTimer->Enabled = true;
		OnCapture = true;
	}
	catch (...)
	{

	}

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

void __fastcall TMachineSetupProcessForm::CaptureCheckTimerTimer(
	TObject *Sender)
{
	bool bCaptureExist;
	// check capture exists
	char cameraIndex;
	unsigned int data[2];
	unsigned int receivedData[2];

	int spbCameraMap[SYSTEM_SPB_MAX_COUNT][SYSTEM_SPB_CAMERA_COUNT];

	for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
	{
		for (int camIndex = 0; camIndex < SYSTEM_SPB_CAMERA_COUNT; camIndex++)
		{
			spbCameraMap[spbIndex][camIndex] = -1;
		}
	}

	for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
	{
		int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
		int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
		spbCameraMap[spbIndex][camIndex] = globalCameraIndex;
	}

  CaptureImage[0]->Width = 640;
  CaptureImage[0]->Height = 480;
  CaptureImage[1]->Width = 640;
  CaptureImage[1]->Height = 480;

	try
	{
		for (int spbIndex = 0; spbIndex < MachineSetupData.IPB_BoardCount; spbIndex++)
		{
			for (int camIndex = 0; camIndex < SYSTEM_SPB_CAMERA_COUNT; camIndex++)
			{
				bool imageExist = false;
				for (int imageIndex = 0; imageIndex < VISUAL_IMAGE_COUNT; imageIndex++)
				{
					if (UploadingCameraIndex[imageIndex] == spbCameraMap[spbIndex][camIndex])
					{
						imageExist = true;
						break;
					}
				}
				if (!imageExist) continue;

				data[0] = camIndex;
				if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_EXIST, data, sizeof(unsigned int),
					receivedData, sizeof(unsigned int) * 2))
				{
					throw Exception("");
				}

				int filledBufferCount = receivedData[0];
				int bufferSize = receivedData[1];
				if (receivedData[0])
				{
					bCaptureExist = true;
				}
				else
				{
					bCaptureExist = false;
				}

				if (bCaptureExist)
				{
					data[1] = CAM_Width * CAM_Height;

          if(CAM_Width == 1280)
          {
            if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_UPLOAD, data, 2 * sizeof(unsigned int),
						CaptureLargeData, CAM_Width * CAM_Height))
            {
              throw Exception("");
            }
          }
          else
          {
            if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_UPLOAD, data, 2 * sizeof(unsigned int),
						CaptureData, CAM_Width * CAM_Height))
            {
              throw Exception("");
            }
          }


					for (int imageIndex = 0; imageIndex < VISUAL_IMAGE_COUNT; imageIndex++)
					{
						if (UploadingCameraIndex[imageIndex] == spbCameraMap[spbIndex][camIndex])
						{
              if(CAM_Width == 1280)
              {
                GetNFACamera2DColorImage(CaptureImage[imageIndex]->Picture->Bitmap, CaptureLargeData, CAM_Width, CAM_Height, UploadingCameraIndex[imageIndex], SystemImageOffsetSWCal[UploadingCameraIndex[imageIndex] - 1], SystemOffsetImage[UploadingCameraIndex[imageIndex] - 1], ProductData.SubSamplingMode );
              }
              else
              {
                GetNFACamera2DColorImage(CaptureImage[imageIndex]->Picture->Bitmap, CaptureData, CAM_Width, CAM_Height, UploadingCameraIndex[imageIndex], SystemImageOffsetSWCal[UploadingCameraIndex[imageIndex] - 1], SystemOffsetImage[UploadingCameraIndex[imageIndex] - 1], ProductData.SubSamplingMode);
              }

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

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

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

							CaptureImage[imageIndex]->Repaint();
						}
					}
				}
			}
		}
	}
	catch (...)
	{

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

void __fastcall TMachineSetupProcessForm::MCBFIDSpeedChangeButtonClick(TObject *Sender)
{
	TTntButton *theButton = (TTntButton *)Sender;
	int motorIndex = BF_ID_MOTOR_INDEX;

	TMotorSpeedSelectionForm *motorSpeedSelectionForm = new TMotorSpeedSelectionForm(this);
	motorSpeedSelectionForm->SetSpeed(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed, ServoMotorSpeed[motorIndex]);
	if (motorSpeedSelectionForm->ShowModal() == mrOk)
	{
		ServoMotorSpeed[motorIndex] = motorSpeedSelectionForm->GetSelectedSpeed();
		MCBFIDSpeedLabel->Caption = IntToStr(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed * 100 / ServoMotorSpeed[motorIndex]) + "%(" +
			IntToStr((int)(ServoMotorSpeedToRPMParam[motorIndex] / ServoMotorSpeed[motorIndex])) + "RPM)";
	}
	delete motorSpeedSelectionForm;
}
//---------------------------------------------------------------------------

void __fastcall TMachineSetupProcessForm::MCBFODinSpeedChangeButtonClick(
	TObject *Sender)
{
	TTntButton *theButton = (TTntButton *)Sender;
	int motorIndex = BF_OD_IN_MOTOR_INDEX;

	TMotorSpeedSelectionForm *motorSpeedSelectionForm = new TMotorSpeedSelectionForm(this);
	motorSpeedSelectionForm->SetSpeed(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed, ServoMotorSpeed[motorIndex]);
	if (motorSpeedSelectionForm->ShowModal() == mrOk)
	{
		ServoMotorSpeed[motorIndex] = motorSpeedSelectionForm->GetSelectedSpeed();
		MCBFODInSpeedLabel->Caption = IntToStr(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed * 100 / ServoMotorSpeed[motorIndex]) + "%(" +
			IntToStr((int)(ServoMotorSpeedToRPMParam[motorIndex] / ServoMotorSpeed[motorIndex])) + "RPM)";
	}
	delete motorSpeedSelectionForm;
}
//---------------------------------------------------------------------------

void __fastcall TMachineSetupProcessForm::MCSDSpeedChangeButtonClick(
	TObject *Sender)
{
	TTntButton *theButton = (TTntButton *)Sender;
	int motorIndex = SD1_MOTOR_INDEX;

	TMotorSpeedSelectionForm *motorSpeedSelectionForm = new TMotorSpeedSelectionForm(this);
	motorSpeedSelectionForm->SetSpeed(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed, ServoMotorSpeed[motorIndex]);
	if (motorSpeedSelectionForm->ShowModal() == mrOk)
	{
		ServoMotorSpeed[SD1_MOTOR_INDEX] = motorSpeedSelectionForm->GetSelectedSpeed();
		ServoMotorSpeed[SD2_MOTOR_INDEX] = motorSpeedSelectionForm->GetSelectedSpeed();

		MCSDSpeedLabel->Caption = IntToStr(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed * 100 / ServoMotorSpeed[motorIndex]) + "%(" +
			IntToStr((int)(ServoMotorSpeedToRPMParam[motorIndex] / ServoMotorSpeed[motorIndex])) + "RPM)";
	}
	delete motorSpeedSelectionForm;
}
//---------------------------------------------------------------------------

void __fastcall TMachineSetupProcessForm::CaptureStopSpeedButtonClick(
	TObject *Sender)
{
	Machine.MachineStop();

	Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP);
	OnCapture = false;
	CaptureCheckTimer->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::SetMode(EMachineSetupMode machineSetupMode)
{
	MachineSetupMode = machineSetupMode;
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::ShutterSpeedEditClick(
	TObject *Sender)
{
	TTntEdit *theEdit = (TTntEdit *)Sender;
	KeyboardForm->Text = theEdit->Text;
	if (KeyboardForm->ShowKeypad() == mrOk)
	{
		theEdit->Text = KeyboardForm->Text;
	}

	int globalCameraIndex = theEdit->Tag;
	ShutterSpeed[globalCameraIndex] = StrToInt(theEdit->Text);

	if (OnCapture)
	{
		float tabletHalfLength = ProductData.TabletLength / 2;
		unsigned int camMask = 0;
		for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
		{
			camMask |= (0x0001 << globalCameraIndex);
		}

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

      if((camMask & (0x0001 << (SD2_3D_FRONT_FACE_CAMERA_INDEX - 1))) == 0)
      {
        Set3DCamera_CaptureParameter(SD2_3D_FRONT_FACE_CAMERA_INDEX - 1, ThreeDCameraDefaultInformation[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].AnalogCameraGain, ThreeDCameraDefaultInformation[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].ExposureTime);
      }
    }
    
		SendSPBCaptureSetup_Multi(&ProductData,camMask, tabletHalfLength, ShutterSpeed,
			ServoMotorSpeed[SD1_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed,
			ServoMotorSpeed[SD2_MOTOR_INDEX], MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed,ProductData.SubSamplingMode, false, 3);
	}
}
//---------------------------------------------------------------------------
void __fastcall TMachineSetupProcessForm::VFRunSpeedButtonClick(
	TObject *Sender)
{
	Machine.VFRun_AutoControl(ProductData.MachineRunOption.MaxSpeedTrainingMode, ProductData.MachineRunOption.ManualMaxSpeed, ProductData.MachineRunOption.ManualModeSensorIndex,
		ProductData.MachineRunOption.ManualModeSensorActiveRatio, ProductData.MachineRunOption.EmptySensorActiveRatio, ProductData.MachineRunOption.FullSensorActiveRatio);
}
//---------------------------------------------------------------------------

void __fastcall TMachineSetupProcessForm::VFStopSpeedButtonClick(
	TObject *Sender)
{
	Machine.VFStop();
}
//---------------------------------------------------------------------------

bool __fastcall TMachineSetupProcessForm::RefreshCameraInfo(int camIndex, int ShutterSpeed)
{ 
  int WriteMask = 0;

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

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

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

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



void __fastcall TMachineSetupProcessForm::TntFormActivate(TObject *Sender)
{
	memset(&machineSettingChangeData, 0, sizeof(TCSVMachineSettingChangeData));

	for (int stepMotorIndex = 0; stepMotorIndex < MAX_STEP_MOTOR_COUNT; stepMotorIndex++)
	{
		machineSettingChangeData.OldNCPos[stepMotorIndex] = ProductData.NCMotorPos[stepMotorIndex];
		machineSettingChangeData.NewNCPos[stepMotorIndex] = ProductData.NCMotorPos[stepMotorIndex];				
	}	
	
  SetScreenPosition(this);  
}
//---------------------------------------------------------------------------

void __fastcall TMachineSetupProcessForm::MCBFODoutSpeedChangeButtonClick(
      TObject *Sender)
{
	TTntButton *theButton = (TTntButton *)Sender;
	int motorIndex = BF_OD_OUT_MOTOR_INDEX;

	TMotorSpeedSelectionForm *motorSpeedSelectionForm = new TMotorSpeedSelectionForm(this);
	motorSpeedSelectionForm->SetSpeed(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed, ServoMotorSpeed[motorIndex]);
	if (motorSpeedSelectionForm->ShowModal() == mrOk)
	{
		ServoMotorSpeed[motorIndex] = motorSpeedSelectionForm->GetSelectedSpeed();
		MCBFODOutSpeedLabel->Caption = IntToStr(MachineSetupData.ServoMotorData[motorIndex].BaseSpeed * 100 / ServoMotorSpeed[motorIndex]) + "%(" +
			IntToStr((int)(ServoMotorSpeedToRPMParam[motorIndex] / ServoMotorSpeed[motorIndex])) + "RPM)";
	}
	delete motorSpeedSelectionForm;	
}
//---------------------------------------------------------------------------

