//---------------------------------------------------------------------------
#ifndef Common_PCH
#define Common_PCH

#include "processing.h"
#include <Classes.hpp>
#include <Controls.hpp>
#include "Message_Form.h"
#include "common.h"

#define PROGRAM_REGISTRY_KEY                "Software\\FAElectronics\\ELMA100"

//#define MOTOR_SPEED_STEP_COUNT					10
//#define MOTOR_SPEED_STEP_COUNT					3					
#define MOTOR_SPEED_STEP_COUNT_FOR_PRODUCT		3

#define MS_TABLET_TYPE_COUNT			8
#define MS_TABLET_SHAPE_COUNT			8
#define MS_MOTOR_SPEED_STEP_COUNT		3

#define TABLET_TYPE_COUNT				4

#define TABLET_TYPE_UNKNOWN				0
#define TABLET_TYPE_UNCOATED			1
#define TABLET_TYPE_FILM_COATED         2
#define TABLET_TYPE_SUGAR_COATED        3
#define TABLET_TYPE_MULTI_LAYERED       4
#define TABLET_TYPE_OTHER				0xFF

#define TABLET_SHAPE_COUNT				4

#define TABLET_SHAPE_UNKNOWN			0
#define TABLET_SHAPE_CIRCLE				1
#define TABLET_SHAPE_OBLONG         	2
#define TABLET_SHAPE_OVAL        		3
#define TABLET_SHAPE_HEXAGON        	4
#define TABLET_SHAPE_TRIANGLE        	5
#define TABLET_SHAPE_SQUARE        		6
#define TABLET_SHAPE_OCTAGON        	7
#define TABLET_SHAPE_ETC				10

#define ENGRAVE_TYPE_UNKNOWN			0
#define ENGRAVE_TYPE_RELIEF				1
#define ENGRAVE_TYPE_INTAGLIO			2
#define ENGRAVE_TYPE_PRINT				3
#define ENGRAVE_TYPE_EMPTY				4

#define ENGRAVE_POS_UNKNOWN				0
#define ENGRAVE_POS_ONESIDE				1
#define ENGRAVE_POS_SAME				2
#define ENGRAVE_POS_DIFF				3

#define PRINT_BRIGHTNESS_UNKNOWN		0
#define PRINT_BRIGHTNESS_LIGHT			1
#define PRINT_BRIGHTNESS_DARK			2

#define DIVISION_LINE_NONE          0
#define DIVISION_LINE_ONE_SIDE      1
#define DIVISION_LINE_BOTH_SIDE     2

#define LARGE_TABLET_CIRCLE_THICK			5.0
#define LARGE_TABLET_CIRCLE_LENGTH     		10.0
#define LARGE_TABLET_OBLONG_LENGTH     		13.0

#define TABLET_PROCESSING_STEP_NONE								0
#define TABLET_PROCESSING_STEP_CALIBRATION_REQUIRED				1
#define TABLET_PROCESSING_STEP_EXTRACT_CHARACTER_REQUIRED		2
#define TABLET_PROCESSING_STEP_FIRST_STUDY_REQUIRED				3
#define TABLET_PROCESSING_STEP_STUDY_REQUIRED					4
#define TABLET_PROCESSING_STEP_STUDY_COMPLETE					5

#define RESOLUTION_NORMAL_QUALITY 0
#define RESOLUTION_HIGH_QUALITY 1


//#define MOTOR_SPEED_TO_LENGTH_CONSTANT_DISC_1		((float)3000 / 500 * 3 / 10 * 102 * 3.141592)		// 초당 회전 거리 (mm/s)
//#define MOTOR_SPEED_TO_LENGTH_CONSTANT_DISC_2		((float)1500 / 500 * 3 / 10 * 202 * 3.141592)		// 초당 회전 거리 (mm/s)

//#define MOTOR_SPEED_TO_LENGTH_CONSTANT_DISC_1		((float)102 * 3.141592 * 2)		// 초당 회전 거리 (mm/s)
//#define MOTOR_SPEED_TO_LENGTH_CONSTANT_DISC_2		((float)202 * 3.141592)		// 초당 회전 거리 (mm/s)
#define MOTOR_SPEED_TO_LENGTH_CONSTANT_DISC_1		((float)302 * 3.141592)		// 초당 회전 거리 (mm/s)
#define MOTOR_SPEED_TO_LENGTH_CONSTANT_DISC_2		((float)302 * 3.141592)		// 초당 회전 거리 (mm/s)

//#define RANGER_3D_BASE_SHUTTER_SPEED		316	// 100 us	(101us)
//#define RANGER_3D_BASE_SHUTTER_SPEED				310
//#define RANGER_3D_BASE_SHUTTER_SPEED				311
//#define RANGER_3D_BASE_SHUTTER_SPEED				260
//#define RANGER_3D_BASE_SHUTTER_SPEED				432 // 150% Test1
//#define RANGER_3D_BASE_SHUTTER_SPEED				452 // 150% Test2
//#define RANGER_3D_BASE_SHUTTER_SPEED				512 // 150% Test3
//#define RANGER_3D_BASE_SHUTTER_SPEED				288
//#define RANGER_3D_BASE_SHUTTER_SPEED				335 //0707 TEST
//#define RANGER_3D_BASE_SHUTTER_SPEED				194 // 3D 접사렌즈

//#define MOTOA_BASE_SPEED_DISC1       32
//#define MOTOA_BASE_SPEED_DISC2       16
//#define MOTOA_BASE_SPEED_DISC3       32

#define SUCTION_DISK_100P_RPM			54.0

#define SERVO_MOTOR_SPEED_TO_RPM_PARAM1			(25000000.0 / 3000 * 60)
#define SERVO_MOTOR_SPEED_TO_RPM_PARAM2			(25000000.0 / 3000 * 60)
#define SERVO_MOTOR_SPEED_TO_RPM_PARAM3			(25000000.0 / 3000 * 60)
#define SERVO_MOTOR_SPEED_TO_RPM_PARAM4			(25000000.0 / 3000 / 21 * 5 * 60)
#define SERVO_MOTOR_SPEED_TO_RPM_PARAM5			(25000000.0 / 3000 / 21 * 5 * 60)

#define SUCTION_DISK_DIAMETER						303
#define SUCTION_DISK_DISTANCE_Y						265
#define SUCTION_DISK_DISTANCE_BASE_X				sqrt(SUCTION_DISK_DIAMETER * SUCTION_DISK_DIAMETER - SUCTION_DISK_DISTANCE_Y * SUCTION_DISK_DISTANCE_Y)


#define MAX_CPB_DEFECT_SERIES_COUNT		97 // 97 + 2 +1
#define MAX_DEFECT_SERIES_COUNT			(MAX_CPB_DEFECT_SERIES_COUNT + 2)

#define CAMERA_INFO_WRITE_SHUTTER_2D      1
#define CAMERA_INFO_WRITE_SHUTTER_3D      2
#define CAMERA_INFO_WRITE_THRESHOLD       3
#define CAMERA_INFO_WRITE_ROI_2D          4
#define CAMERA_INFO_WRITE_ROI_3D          5
#define CAMERA_INFO_WRITE_TRIG_FRQ        6
#define CAMERA_INFO_WRITE_SUBSAMPLING_MODE 7
#define CAMERA_INFO_WRITE_GAIN_3D 8

#define IMAGE_SUBSAMPLING_MODE  0
#define IMAGE_FULL_SCALE_MODE   1

#define TABLET_SETUP_MODE_NORMAL     0
#define TABLET_SETUP_MODE_REVISION   1

#define BACKUP_PROCESS_SPEED_FAST		0	// default 
#define BACKUP_PROCESS_SPEED_NORMAL	1

//#define DAEHWAPROGRAM

extern bool GlobalEnabledCameraStatus[SYSTEM_TOTAL_CAMERA_COUNT];
extern int  SystemImageOffsetSWCal[SYSTEM_TOTAL_CAMERA_COUNT];
extern unsigned char SystemOffsetImage[SYSTEM_TOTAL_CAMERA_COUNT][SYSTEM_CAMERA_WIDTH / 2 * SYSTEM_CAMERA_HEIGHT / 2];
//---------------------------------------------------------------------------
typedef struct
{
    AnsiString Root;
    AnsiString Hex;
    AnsiString Env;
    AnsiString Image;
    AnsiString Product;
    AnsiString Log;
    AnsiString Defect;
    AnsiString Temp;
} TProgramPath;
typedef struct
{
    int DefaultCPBProgramID;
    bool CPBEnabled[SYSTEM_CPB_COUNT];
    int CameraDistribution[SYSTEM_CPB_COUNT];
    int CPBSDRSizeType[SYSTEM_CPB_COUNT];
    unsigned char CPBClockKind[SYSTEM_CPB_COUNT];
    unsigned char CameraHardwarePosition[SYSTEM_SPB_CAMERA_MAX_COUNT];
    unsigned short ShutterSpeed[SYSTEM_SPB_CAMERA_MAX_COUNT];
//    unsigned short ShutterDelay[SYSTEM_SPB_CAMERA_MAX_COUNT];
    unsigned short GlobalCameraIndex[SYSTEM_SPB_CAMERA_MAX_COUNT];
    unsigned char CamMask;
} TSPBInfo;

typedef struct
{
	int MotorSpeedList[MS_TABLET_TYPE_COUNT][MS_TABLET_SHAPE_COUNT][MAX_SERVO_MOTOR_COUNT][MS_MOTOR_SPEED_STEP_COUNT];
  int DiscCenterPos[SYSTEM_TOTAL_CAMERA_COUNT];
	int CameraResolution[SYSTEM_TOTAL_CAMERA_COUNT];
	int CameraBrightnessEvalValue[4];
  int MotorSimpleSpeedList[18];
} TMachineParams;

typedef struct
{
	int ShutterSpeed[SYSTEM_TOTAL_CAMERA_COUNT];
  int DigitalGain[SYSTEM_TOTAL_CAMERA_COUNT];
} TInitialValues;
/*
typedef struct
{
	int BaseSpeed;
	int AccTime;
	int DecTime;
	bool IsPositiveDirection;
} TServoMotorInfo;
*/
typedef struct
{
	unsigned char Disk1InverterSpeed;
	unsigned char Disk2InverterSpeed;
  unsigned char Disk3InverterSpeed;
	char dummyChar[2];
	unsigned int ServoMotorSpeed[MAX_SERVO_MOTOR_COUNT];
	int SpeedIndex;
} TMachineOperationInfo;


/*
class TSystemInfor
{
private:
public:
	__fastcall TSystemInfor();
	TSPBInfo SPBInfo[SYSTEM_SPB_COUNT];
	TCameraMapInfo CameraMapInfo[SYSTEM_TOTAL_CAMERA_COUNT];
//    int ShutterSpeed[SYSTEM_TOTAL_CAMERA_COUNT];
//    float Resolution[SYSTEM_TOTAL_CAMERA_COUNT];
//    unsigned int LEDOnMask[SYSTEM_TOTAL_CAMERA_COUNT];
	int SpeedIndex;

	bool __fastcall LoadData(AnsiString fileName);
	bool __fastcall SaveData(AnsiString fileName);
};
*/

#define STUDY_STEP_NONE				0
#define STUDY_STEP_FEATURE_EXTRACTED		1
#define STUDY_STEP_STUDY_COMPLETE		2

#define MAX_TABLET_LAYER_COUNT			16

typedef struct
{
    int MaxSpeedTrainingMode;
    int ManualMaxSpeed;
    int ManualModeSensorIndex;
    int ManualModeSensorActiveRatio;
    int ManualLimitSpeed;
    int ManualModeLimitSensorIndex;
    int ManualModeLimitSensorActiveRatio;
    //int EmptySensorIndex;
    int EmptySensorActiveRatio;
    //int FullSensorIndex;
    int FullSensorActiveRatio;
    int SuctionDisk1InverterSpeed;
    int SuctionDisk2InverterSpeed;
    unsigned char AirKnifeSpeed;
    char dummy1;
    int StartSpeed;
    int LampKind;
    int applyEjectorDelay;
    int adjustUnInsDelay;
    int adjustDefectDelay;
    int adjustEjectorWindStrength;
    int EnabledSensorType;
    int adjustGoodDelay; //Q사
} TMachineRunOption;

typedef struct
{
	WideString ProductCode;
	WideString ProductName;
	WideString LOTName;
	int TabletType;
	int TabletShape;
	int StudyStep;
	double TabletLength;
	double TabletWidth;
	double TabletThick;
	double TabletSideThick;
	int EngraveType;
	int EngravePos;
	int PrintBrightness;
	int BoundaryLeft[SYSTEM_TOTAL_CAMERA_COUNT];
	int BoundaryTop[SYSTEM_TOTAL_CAMERA_COUNT];
	int BoundaryRight[SYSTEM_TOTAL_CAMERA_COUNT];
	int BoundaryBottom[SYSTEM_TOTAL_CAMERA_COUNT];
	int ShutterSpeed[SYSTEM_TOTAL_CAMERA_COUNT];
  int DigitalGainV[SYSTEM_TOTAL_CAMERA_COUNT];
  
	int ProcessingStep;
	AnsiString TabletColorCode;
	AnsiString PrintColorCode;
	int MotorSpeedList[MAX_SERVO_MOTOR_COUNT][MOTOR_SPEED_STEP_COUNT_FOR_PRODUCT];
  int StudyMotorSpeedList[MAX_SERVO_MOTOR_COUNT][MOTOR_SPEED_STEP_COUNT_FOR_PRODUCT];
	int ProductionCount;
	TDateTime LastInspectionTime;
	bool PlateTablet;
	int TabletLayerCount;
	TColor MultiLayeredTabletColor[MAX_TABLET_LAYER_COUNT];
	int ThresholdFor3D[SYSTEM_TOTAL_CAMERA_COUNT];

	int StudiedSensor1Length;
	int StudiedSensor2Length;
	int StudiedSensorIntervalA;
	int StudiedSensorIntervalB;
	double NCMotorPos[MAX_STEP_MOTOR_COUNT];
	int RotatingGuideKind;
	int FixedGuideKind;
	int VerticalGate2Kind;
	bool Arrange;
	int SymmetricLineCount;
	TMachineRunOption MachineRunOption;
	int LampKind;

  int SpecialInsCount[6];
  int SpecialInsCheckbox;

  int MarvelingTabletSW;
  //sjm add
  int StudiedSensor3Length;

  int DivisionLineInfo;
  int SubSamplingMode; // 0 : 640 , 1 : 1280 

  int ExposureTime3D[2];
  int AnalogGain3D[2];

  // Quali
  int LastDischargeCountSetValue;
  int DischargeCountSetValue;
  int DischargeCount;
  int MisejectActiveLimitCount;

  int SimpleMotorSpeedList[MAX_SERVO_MOTOR_COUNT][MOTOR_SPEED_STEP_COUNT_FOR_PRODUCT]; // 카메라 불안정으로 인한 제한적속도 지정
  int SimpleStudyMotorSpeedList[MAX_SERVO_MOTOR_COUNT][MOTOR_SPEED_STEP_COUNT_FOR_PRODUCT];

  int FatTabletCapture;
  int CurvedSurfaceTabletSW;
  int Disk1ThreeDImageCenterXForLaser;
  int Disk1ThreeDImageCenterYForLaser;
  int Disk2ThreeDImageCenterXForLaser;
  int Disk2ThreeDImageCenterYForLaser;

  int Disk1ThreeDImageLengthForLaser;
  int Disk2ThreeDImageLengthForLaser;
  
  WideString RecipeName;

  int StudyShutterSpeed[SYSTEM_TOTAL_CAMERA_COUNT];
  int StudyGainV[SYSTEM_TOTAL_CAMERA_COUNT];
} TProductData;

typedef struct
{
	char ProductCode[128];
	char ProductName[128];
	char LOTName[128];
	int TabletType;
	int TabletShape;
	int StudyStep;
	double TabletLength;
	double TabletWidth;
	double TabletThick;
	double TabletSideThick;
	int EngraveType;
	int EngravePos;
	int PrintBrightness;
	int BoundaryLeft[SYSTEM_TOTAL_CAMERA_COUNT];
	int BoundaryTop[SYSTEM_TOTAL_CAMERA_COUNT];
	int BoundaryRight[SYSTEM_TOTAL_CAMERA_COUNT];
	int BoundaryBottom[SYSTEM_TOTAL_CAMERA_COUNT];
	int ShutterSpeed[SYSTEM_TOTAL_CAMERA_COUNT];
		 int DigitalGainV[SYSTEM_TOTAL_CAMERA_COUNT];

	int ProcessingStep;
	char TabletColorCode[128];
	char PrintColorCode[128];
	int MotorSpeedList[MAX_SERVO_MOTOR_COUNT][MOTOR_SPEED_STEP_COUNT_FOR_PRODUCT];
	int ProductionCount;
	bool PlateTablet;
	int TabletLayerCount;

	int StudiedSensor1Length;
	int StudiedSensor2Length;
	int StudiedSensorIntervalA;
	int StudiedSensorIntervalB;
	double NCMotorPos[MAX_STEP_MOTOR_COUNT];
	int RotatingGuideKind;
	int FixedGuideKind;
	int VerticalGate2Kind;
	bool Arrange;
	int SymmetricLineCount;
	int LampKind;

	int SpecialInsCount[6];
	int SpecialInsCheckbox;

	int MarvelingTabletSW;
	//sjm add
	int StudiedSensor3Length;

	int LineScanFrequency[SYSTEM_TOTAL_CAMERA_COUNT];

	int DivisionLineInfo;
	int SubSamplingMode; // 0 : 640 , 1 : 1280 

	int ExposureTime3D[2];
	int AnalogGain3D[2];
	int DischargeCountSetValue;
	int DischargeCount;
} TMESProductData;

//*************************************************************
//	MES(SCADA) Struct
//-----------------------------------------------------------
//	1. Data Type Description
//		1) String(char*) Type
//		2) Long(int) Type
//		3) Double(Word) Type
//-----------------------------------------------------------
//
//*************************************************************

typedef struct
{
	// Product Data
	int TabletType;
	int TabletShape;
	int EngraveType;
	int PrintBrightness;
	double TabletLength;
	double TabletWidth;
	double TabletThick;
	double TabletSideThick;
	char ProductName[128];
	char TabletColorCode[128];
	char PrintColorCode[128];
	bool PlateTablet;

	// Machine Data
	int ShutterSpeed[SYSTEM_TOTAL_CAMERA_COUNT];
	int DigitalGainV[SYSTEM_TOTAL_CAMERA_COUNT];
	int ExposureTime3D[2];
	int AnalogGain3D[2];
	int SuctionDisk1InverterSpeed;
	int SuctionDisk2InverterSpeed;
	int adjustEjectorWindStrength;
	int MachineState;
	double NCMotorPos[MAX_STEP_MOTOR_COUNT];
	unsigned char AirKnifeSpeed;

	// Inspection Data
	int GoodTabletCount;
	int DefectTabletCount;
	int UnInsTabletCount;
	int ProductionCount;
	int DesiredInspectionCount;
	int	MachineStopDPCount;
	int	MachineStopUPCount;
	int ReInspectionType;
	int MachineStopActivated;
	int MachineStopDefectRatio;
	int MachineStopUnInsRatio;
	int TotalTabletCount;
	int CameraEnabled[SYSTEM_TOTAL_CAMERA_COUNT];
	char LOTName[128];

	// Alarm
	char AlarmExist;
	char TotalFull;
}TNFA_MES_Data;


typedef struct
{
	AnsiString OperatorName;
    AnsiString LOTName;
	int TotalTabletCount;
	int GoodTabletCount;
	int DefectTabletCount;
	int UnInsTabletCount;
	
	// unins detail
	int SPBProcessingNCTabletCount;
	int SPBTOTabletCount;
	int SPBUnInsTabletCount;
	int DisapperedTabletCount;
	int InsertedTabletCount;
	int	ClosedTabletUninsCount;
	int	ClosedTabletDefectCount;
    // defect detail

	unsigned int ElapsedTime;
} TInspectionResultData;

typedef struct
{
	bool DSMEnabled;
//	bool OldDataCompress;
//	double BMPMaintainTime;
	double ReduceTime[3];
	int PrimeLotCount[3];
	int PrimeLotMaxDefectCount[3];
	int TrivialLotMaxDefectCount[3];
	int MinDiskSpaceRatio;
	bool DSMAlwaysOn;
  bool MainformDiskSpaceEnabled;  
	TDateTime DSMStartTime;
	TDateTime DSMEndTime;
} TDSMInfo;

void __fastcall SetGrayPalette(Graphics::TBitmap *theBitmap);
void __fastcall Set3DPalette(Graphics::TBitmap *theBitmap);
void __fastcall Set3DPalette_Rotate(Graphics::TBitmap *theBitmap);
double __fastcall Motor_RPM_To_MMPS(int rpm);

bool __fastcall ReadMachineSetupData(AnsiString fileName, TMachineSetupData &machineSetupData);
void __fastcall WriteMachineSetupData(AnsiString fileName, TMachineSetupData &machineSetupData,bool ChangeLaserComplexValue = false);
bool __fastcall ReadMachineParams(AnsiString fileName, TMachineParams &machineParams);		// pc saved params
bool __fastcall WriteMachineParams(AnsiString fileName, TMachineParams &machineParams);		// pc saved params
bool __fastcall ReadCameraMapData(AnsiString fileName, TCameraMapInfo *cameraMapInfo);
bool __fastcall WriteCameraMapData(AnsiString fileName, TCameraMapInfo *cameraMapInfo);
bool __fastcall ReadSPBSystemSetupData(AnsiString fileName, TSPBSystemSetupData *spbSystemSetupData,
	TCameraMapInfo *cameraMapInfo);
bool __fastcall WriteSPBSystemSetupData(AnsiString fileName, TSPBSystemSetupData *spbSystemSetupData);
//bool __fastcall ReadServoMotorInfo(AnsiString fileName, TServoMotorInfo *servoMotorInfo);
//void __fastcall WriteServoMotorInfo(AnsiString fileName, TServoMotorInfo *servoMotorInfo);
bool __fastcall ReadMachineOperationInfo(AnsiString fileName, TMachineOperationInfo &machineOperationInfo, TMachineSetupData &machineSetupData);		// read recent operation info
void __fastcall WriteMachineOperationInfo(AnsiString fileName, TMachineOperationInfo &machineOperationInfo);		// write recent operation info
bool __fastcall ReadDSMInfo(AnsiString fileName, TDSMInfo &dsmInfo);
void __fastcall WriteDSMInfo(AnsiString fileName, TDSMInfo &dsmInfo);

bool __fastcall ReadProductData(AnsiString fileName, TProductData &productData, TMachineParams &machineParams,
	TMachineSetupData &machineSetupData);
bool __fastcall ReadLightProductData(AnsiString fileName, TProductData &productData);
bool __fastcall WriteProductData(AnsiString fileName, TProductData &productData);
bool __fastcall IsLargeTablet(TProductData &productData);

bool __fastcall SetProgramPath(TProgramPath &path);

bool __fastcall LoadGradeData(AnsiString gradeFileName, TTabletGradeData &GradeData);
bool __fastcall SaveGradeData(AnsiString gradeFileName, TTabletGradeData &GradeData);

bool __fastcall LoadStudyData(AnsiString studyFileName, TTabletStudyResultData &StudyData);
bool __fastcall SaveStudyData(AnsiString studyFileName, TTabletStudyResultData &StudyData);

void __fastcall MakeTabletCharacterData(TProductData *productData, TTabletCharacter *tabletCharacter, TMachineParams *machineParams);

bool __fastcall SaveShutterSpeedInfo(AnsiString fileName, AnsiString colorCodeName, TColor bgrColor, int *shutterSpeedList, unsigned int validCameraMask,int*Gain);
AnsiString __fastcall LoadShutterSpeedInfo(AnsiString fileName, AnsiString colorCodeName, TColor bgrColor, int *shutterSpeedList, unsigned int validCameraMask,int*Gain);
AnsiString __fastcall Load3DParameterInfo(AnsiString fileName, AnsiString colorCodeName, TColor bgrColor, int *exposureTimeList, int *thresholdList, unsigned int validCameraMask);

WideString __fastcall GetDefectSeriesStr(int series);

WideString __fastcall TabletKindStr(int tabletKind);
WideString __fastcall TabletShapeStr(int tabletShape);
WideString __fastcall TabletEngraveKindStr(int engraveKind);
WideString __fastcall TabletEngravePosStr(int engravePos);
WideString __fastcall LampKindStr(int lampKind);

bool __fastcall ReadUserMachineEnvData(AnsiString fileName, TUserMachineEnv &userMachineEnv);
bool __fastcall WriteUserMachineEnvData(AnsiString fileName, TUserMachineEnv &userMachineEnv);

void __fastcall InitCommon_PC(void);
int __fastcall DefectSizePixelToMili(int pixel);
int __fastcall GetDefaultGuideKind(int guideIndex, double tabletWidth);
int __fastcall GetDefaultVGateKind(int gateIndex, double tabletWidth);
int __fastcall GetDefaultAirKnifeSpeed(void);
int __fastcall GetDefaultSuctionSpeed(TProductData &productData, int &suctionSpeed1, int &suctionSpeed2);
void __fastcall GetDefaultNCPosition(TProductData &productData, double *ncMotorPos, double interlockAValue);

void __fastcall ImageConversion_3D(Graphics::TBitmap *DestBitmap, int destWidth, int destHeight, byte *srcBitmap, int srcWidth, int srcHeight);
void __fastcall ImageConversion_3D_Reverse(Graphics::TBitmap *DestBitmap, int destWidth, int destHeight, byte *srcBitmap, int srcWidth, int srcHeight);

int __fastcall GetMSTabletTypeIndex(int tabletType);
int __fastcall GetMSTabletShapeIndex(int tabletShape);

unsigned short Generate_CRC16(unsigned char *data, int len);

void __fastcall CopyProductData(TProductData &dest, TProductData &src);

void __fastcall ReadDiskLineScanFrequency(AnsiString fileName);
void __fastcall WriteDiskLineScanFrequency(AnsiString fileName);

void __fastcall ReadSystem2DCamAnalogGain(AnsiString fileName);
void __fastcall WriteSystem2DCamAnalogGain(AnsiString fileName);

void __fastcall ReadCameraWhiteBalanceColorInfo(AnsiString fileName, int cameraIndex);
void __fastcall WriteCameraWhiteBalanceColorInfo(AnsiString fileName, int cameraIndex, int rgbIndex);
void __fastcall ApplyWhiteBalance(int cameraIndex, Graphics::TBitmap *srcImage, Graphics::TBitmap *dstImage);
void __fastcall SetCameraGain(int cameraIndex, int AnalogGain, int DigitalGain1, int DigitalGain2);
void __fastcall Set3DCamera_CaptureParameter(int cameraIndex, int AnalogGain,int ExposureTime);
bool __fastcall RequestCameraCommand(int cameraIndex, char *sendData, char *receivedData, unsigned int txDataLength, unsigned int rxDataLength);

bool __fastcall ReadSystemUserAuthorityInformation(AnsiString fileName);
bool __fastcall WriteSystemUserAuthorityInformation(AnsiString fileName);
void __fastcall MakeSystemUserAuthorityInitInformation();

// 기존 데이터 파일 구조 리뉴얼 전 NFA_DATA_REPORT(952byte) + NFA_DATA_REPORT_GRADE(252byte) + NFA_DATA_REPORT_DEFECT_SERIES_COUNT(200byte) + NFA_DATA_REPORT_SUB(46byte);
// 가장 초기를 0으로
#define INSPECTION_REPORT_DATA_VER 1

typedef struct
{
  unsigned char ChunkID[4]; // "INSR" in ASCII ( fmt + space )
  unsigned int ChunkSize;   // value = 16 fixed , 아래
  unsigned short Version; // increment by 1 ,
  unsigned char Dummy[14];
}NFA_DATA_FMT;  // 사이즈 고정

typedef struct
{
  unsigned char ChunkID[4]; // "RD  " in ASCII ( RD + space+space )
  unsigned int ChunkSize;   //  Version 0 ~ 1 : 1032byte

  int TotalTabletCount;
	int GoodTabletCount;
	int DefectTabletCount;
	int UnInsTabletCount;
  int SPBProcessingNCTabletCount;
  int SPBTOTabletCount;
  int SPBUnInsTabletCount;
  int DisappearedTabletCount;
  int InsertedTabletCount;
  int	ClosedTabletUninsCount;
  int	ClosedTabletDefectCount;
  unsigned int ElapsedTime;
  unsigned int reserved;
  double InspectionStartTime;
  double InspectionEndTime;
  int ProductionCount;
  int DefectDataCount;
  int ClosedTabletCount;
  char ProductName[64];
  char OperatorName[32];
  char IsReIns;
  char dummyChar1[3];
  int UnPrintTabletCount;
  int WrongNumberTabletCount;
  int NumberUndefTabletCount;
  int CaptureNotReadyTabletCount;
  int BufferFullTabletCount;
  int CaptureTimoutTabletCount;
  int ProcessingTimoutTabletCount;
  int CPBFullTabletCount;
  int ProcessingErrorTabletCount;
  int UnInsTabletPositionCount;
  int UnInsBrightnessDropCount;
  int UnInsBrightnessChaseCount;
  int Sensor1MisFeedingTabletCount;
  int Sensor2MisFeedingTabletCount;
  int Sensor1MultiTabletCount;
  int Sensor2MultiTabletCount;
  int NozzErrorUnInsTabletCount;
  int CounterSensorTabletCount;
  int MisejectActiveCount;
  int GoodTabletLostCount;
  int MisejectTabletInsertCount;
  int MisejectDefectTabletCount;
  int MisejectUnInsTabletCount;
  int FRMisMatchTabletCount;
  int PrintMisMatchCount;
  int NozzErrorDefectTabletCount;
  int LastDisStep;
  char dummyChar2[744];

}NFA_DATA_REPORT;

typedef struct
{
  unsigned char ChunkID[4]; // "RGD " in ASCII ( RGD + space )
  unsigned int ChunkSize;   //  Version 0  : 256byte , Version 1 : 561byte
  int ColorGrade;
	int FrontNormalDirtyGrade;
	int FrontPrintDirtyGrade;
	int FrontStainGrade;
	int FrontEdgeGrade;
	int OptionFrontStickingGrade_Type1;
	int SideDirtyGrade;
	int SideStainGrade;
	int SideEdgeGrade;
	int OptionBreakingGrade;
	int OptionPrintMarkGrade;
	int PrintEraseGrade;
	int PrintSpreadGrade;
	int FrontEdgeDirtyGrade;
	int FrontColorDirtyGrade;
	int SideHeightGrade;
	int SideColorDirtyGrade;
	int ThreeDHeightMinusLimit;
	int ThreeDHeightPlusLimit;
	int FrontNormalDirtySize;
	int FrontEdgeDirtySize;
	int FrontStainSize;
	int FrontEdgeSize;
	int FrontColorDirtySize;
	int SideDirtySize;
	int SideStainSize;
	int SideHeightSize;
	int OptionBreakingSize;
	int OptionFrontStickingSize_Type1;
  int SideColorDirtySize;
  int EngraveDistinguishGradeFor2D;
  int EngraveDistinguishGradeFor3D;
  int Side_Edge_Neighbor_Intensity;
  int Side_Edge_Neighbor_Defect_Size;
  bool EngravePositionDefectCheckSW;
  int Side_Edge_Dark_Intensity;
  int Side_Edge_Dark_Defect_Size;
  int Side_Edge_Bright_Intensity;
  int Side_Edge_Bright_Defect_Size;
  int Side_Edge_Neighbor_Break_Intensity;
  int Side_Edge_Neighbor_Break_Size;

  int OptionFrontStickingGrade_Type2;
  int OptionFrontStickingSize_Type2;
	char dummyChar[392];
}NFA_DATA_REPORT_GRADE;

typedef struct
{
  unsigned char ChunkID[4]; // "RDDS" in ASCII
  //  Version 0 :  MAX_DEFECT_SERIES_COUNT(49) + 1 = 200byte
  //  Version 1 :  MAX_DEFECT_SERIES_COUNT(99) + 1 = 400byte
  unsigned int ChunkSize;
  int DefectSeriesCount[MAX_DEFECT_SERIES_COUNT + 1];
}NFA_DATA_REPORT_DEFECT_SERIES_COUNT;

// 예비용 , 이력서에 필요한 내용은 위에 NFA_DATA_REPORT 구조체에 Dummy사용
typedef struct
{
  unsigned char ChunkID[4]; // "RDS " in ASCII ( RDS + space )
  //  Version 0 : 48 byte
  //  Version 1 : 168 byte
  unsigned int ChunkSize;

  int BatchEndFlag[1];
  char EndOperatorName[32];
  int InDiskSpeed;
  int RotateGuideSpeed;
  int SucktionDiskSpeed;
  char dummy[120];
}NFA_DATA_REPORT_SUB;

typedef struct
{
  NFA_DATA_FMT  Fmt;
  NFA_DATA_REPORT Data;
  NFA_DATA_REPORT_GRADE GradeData;
  NFA_DATA_REPORT_DEFECT_SERIES_COUNT DefectSeriesCount;
  NFA_DATA_REPORT_SUB SubData;
}NFA_INSPECTION_REPORT_STRUCT;


void Create_Report_Data(NFA_INSPECTION_REPORT_STRUCT Report,AnsiString FileName);
bool Read_InspectionReportData(AnsiString inspectionReportFileName , NFA_INSPECTION_REPORT_STRUCT & Report);
///int ConvertCameraIndex(int globalCameraIndex, AnsiString ConvertString);
AnsiString ConvertCameraIndex(int globalCameraIndex);
int ComponentReposition(int type, int Left1, int Left2, int Width);
void __fastcall ReadSystemCameraOffsetImage(int *gainlist);
void __fastcall SetScreenPosition(TTntForm *tempForm);
void __fastcall ReadTPB_BoardExistInfo();
#endif

