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

#include <vcl.h>
#pragma hdrstop

#include "PreviewInspection_Form.h"
#include "Message_Form.h"
#include "MultiLanguage.h"
#include "Waiting_Form.h"

#include <inifiles.hpp>

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

void __fastcall TPreviewInspectionForm::FormCreate(TObject *Sender)
{
  defectColorList[0] = clMaroon;
  defectColorList[1] = clGreen;
  defectColorList[2] = clOlive;
  defectColorList[3] = 0x004080FF;
  defectColorList[4] = clPurple;
  defectColorList[5] = clTeal;
  defectColorList[6] = clGray;
  defectColorList[7] = clLime;
  defectColorList[8] = clYellow;
  defectColorList[9] = clWhite;
  defectColorList[10] = clAqua;
  defectColorList[11] = clFuchsia;
  defectColorList[12] = clSkyBlue;
  defectColorList[13] = clBlue;
  defectColorList[14] = clRed;
  defectColorList[15] = 0x00C080FF;

  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    if(SystemLinkCameraInfo[globalCameraIndex] != 0)
    {
      TTntShape *DefectCameraShape = (TTntShape *)FindComponent("DefectCameraShape" + IntToStr(globalCameraIndex + 1));
      if(DefectCameraShape)
      {
        DefectCameraShape->Brush->Color = defectColorList[globalCameraIndex];
      }
    }
  }

  ComponentQueueStartIndex = ComponentQueueEndIndex = 0;
  memset(ComponentTabletNumber, 0, sizeof(int) * MAKE_COMPONENT_QUEUE_SIZE);
  
  Panel1->DoubleBuffered = true;
  ImageGroupPanel->DoubleBuffered = true;
  InspectionImagePanel->DoubleBuffered = true;
  ProcessingResultPanel1->DoubleBuffered = true;
  ProcessingResultPanel2->DoubleBuffered = true;

  InspectionImageType = IMAGE_TYPE_NORMAL;

  bEnabledCameraAll = true;
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    bEnabledInspectionCamera[globalCameraIndex] = true;

    if (CameraMapInfo[globalCameraIndex].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[globalCameraIndex] == 0)
    {
      bEnabledInspectionCamera[globalCameraIndex] = false;
    }
    else if(ProductData.TabletType == TABLET_TYPE_SUGAR_COATED)
    {
      if(globalCameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
          globalCameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1 ||
          globalCameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
          globalCameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1)
      {
        bEnabledInspectionCamera[globalCameraIndex] = false;
      }
    }
  }

  PreviewLOTName = "";

  inspectedLOTCount = 0;
  SetLOTInformation();

  RefreshImageSelectMenu();
  RefreshCameraSelectMenu();
  RefreshCameraAllSelectMenu();
  InitDesignedComponents();

  IsScrollImageMouseDown = false;
  IsStringGridMouseDown = false;
  LastStringGridMouseDownTime = 0; 

  ScrollImage->Picture->Bitmap->Width = ScrollImage->Width;
	ScrollImage->Picture->Bitmap->Height = ScrollImage->Height;
	ScrollImage->Picture->Bitmap->PixelFormat = pf24bit;
	for (int y = 0; y < ScrollImage->Height; y++)
	{
		byte *pBitmap = (byte *)ScrollImage->Picture->Bitmap->ScanLine[y];
		byte colorB = 0xFF - abs(y - ScrollImage->Height / 2) * 0x4F / (ScrollImage->Height / 2);
		byte colorG = 0x7F - abs(y - ScrollImage->Height / 2) * 0x1F / (ScrollImage->Height / 2);
		byte colorR = 0x7F - abs(y - ScrollImage->Height / 2) * 0x1F / (ScrollImage->Height / 2);
		if (y % 10 == 0)
		{
			colorB = colorG = colorR = 0;
		}

		for (int x = 0; x < ScrollImage->Width; x++)
		{
			pBitmap[x * 3] = colorB;
			pBitmap[x * 3 + 1] = colorG;
			pBitmap[x * 3 + 2] = colorR;
		}
	}

  ImageGroupPanel->Height = DESIGNED_IMAGE_BOX_HEIGHT;
  currentImageIndex = 0;
  ProgressBar->Position = 0;

  bStop = false;
  bInspectionStart = false;
  PreviewInspectionStopBtn->Enabled = false;

  memset(&PreviewResultCount, 0, sizeof(TPreviewResultCount));
  RefreshResultCountInfo();
  RefreshDefectStringGrid(DEFECT_LIST_CONTROL_OPTION_CLEAR, NULL, NULL, NULL);

  lastScrollTabletNumber = 0;

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

      ConvertString = ConvertCameraIndex(globalCameraIndex);

      CameraEnablePanel->Caption = ConvertString;
      CameraShapeLabel->Caption = ConvertString;
    }
  }


  if(GlobalProgramID == PROGRAM_ID_150P)
  {
    // SELMA150TP
    int MoveD = ComponentReposition(4,0,0,CameraEnablePanel3->Width);
    int MoveD1 = ComponentReposition(3,DefectCameraShape1->Top, DefectCameraShape2->Top, 0);
    for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      AnsiString ConvertString;
      TTntPanel *CameraEnablePanel = (TTntPanel *)FindComponent("CameraEnablePanel" + IntToStr(globalCameraIndex+1));
      TTntShape *DefectCameraShape = (TTntShape *)FindComponent("DefectCameraShape" + IntToStr(globalCameraIndex+1));
      TTntLabel *CameraShapeLabel = (TTntLabel *)FindComponent("CameraShapeLabel" + IntToStr(globalCameraIndex+1));
      if(SystemLinkCameraInfo[globalCameraIndex] == 0)
      {
        CameraEnablePanel->Visible = false;
        DefectCameraShape->Visible = false;
        CameraShapeLabel->Visible = false;
      }
      else
      {
        if(globalCameraIndex+1 == 2 || globalCameraIndex+1 == 4 ||
        globalCameraIndex+1 == 10 || globalCameraIndex+1 == 12 )
        {
          CameraEnablePanel->Left += MoveD;
        }

        if(globalCameraIndex+1 == 1 || globalCameraIndex+1 == 2 || globalCameraIndex+1 == 4 ||
        globalCameraIndex+1 == 9 || globalCameraIndex+1 == 10 || globalCameraIndex+1 == 12  )
        {
          DefectCameraShape->Top += MoveD1;
          CameraShapeLabel->Top += MoveD1;
        }
      }
    }
    Label5->Left += MoveD;
  }
  else if(ProductData.TabletType == TABLET_TYPE_SUGAR_COATED)
  {
    // sugar coat
    for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if(globalCameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
          globalCameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1 ||
          globalCameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX - 1 ||
          globalCameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX - 1)
      {
        TTntPanel *CameraEnablePanel = (TTntPanel *)FindComponent("CameraEnablePanel" + IntToStr(globalCameraIndex+1));
        TTntShape *DefectCameraShape = (TTntShape *)FindComponent("DefectCameraShape" + IntToStr(globalCameraIndex+1));
        TTntLabel *CameraShapeLabel = (TTntLabel *)FindComponent("CameraShapeLabel" + IntToStr(globalCameraIndex+1));

        CameraEnablePanel->Visible = false;
        DefectCameraShape->Visible = false;
        CameraShapeLabel->Visible = false;
      }
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::ImageSelectPanel1Click(
      TObject *Sender)
{
  TTntPanel *thePanel = (TTntPanel *)Sender;

  /*
  if(thePanel->Tag == IMAGE_TYPE_DEFECT)
  {
    MessageDlgFA("Not supported", mtConfirmation, TMsgDlgButtons() << mbOK);
    return;
  }
  */

	InspectionImageType = thePanel->Tag;

  InspectionLOTSettingGroupBox->Visible = false;
  if(InspectionImageType == IMAGE_TYPE_DEFECT)
  {
    if(ProductData.LOTName.IsEmpty() || inspectedLOTCount == 0)
    {
      InspectionImageType = IMAGE_TYPE_NORMAL;

      MessageDlgFA(PREVIEWINSPECTIN_FORM_TEXT_11, mtConfirmation, TMsgDlgButtons() << mbOK);
    }
    else
    {
      if(PreviewLOTName.IsEmpty())
      {
        // 초기값이 존재하지 않은 경우에만
        // 기존에 다른 LOT를 선택한적이 있다면 그상태로 값이 설정될것
        PreviewLOTName = ProductData.LOTName;
      }

      for(int itemIndex = 0; itemIndex < inspectedLOTCount; itemIndex++)
      {
        if(LOTInformation[itemIndex].LOTName == PreviewLOTName)
        {
          LOTComboBox1->ItemIndex = itemIndex;
          break;
        }
      }

      InspectionLOTSettingGroupBox->Visible = true;
    }
  }

  RefreshImageSelectMenu();
  RefreshCurrentLOTInfo();
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::RefreshImageSelectMenu(void)
{
  for (int typeIndex = 0; typeIndex < 2; typeIndex++)
	{
		TTntPanel *typePanel = (TTntPanel *)FindComponent("ImageSelectPanel" + IntToStr(typeIndex + 1));
		typePanel->Color = clWhite;
		typePanel->Font->Color = clBlack;
		typePanel->Font->Style = typePanel->Font->Style >> fsBold;
	}

	TTntPanel *selectedPanel = (TTntPanel *)FindComponent("ImageSelectPanel" + IntToStr(InspectionImageType + 1));

	if (selectedPanel)
	{
		selectedPanel->Color = clBlue;
		selectedPanel->Font->Color = clWhite;
		selectedPanel->Font->Style = selectedPanel->Font->Style << fsBold;
	}
}

//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::RefreshCameraSelectMenu(void)
{
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
	{
		TTntPanel *typePanel = (TTntPanel *)FindComponent("CameraEnablePanel" + IntToStr(globalCameraIndex + 1));

    if (CameraMapInfo[globalCameraIndex].CameraInspectPosition < CAMERA_POSITION_DISCONNECT && SystemLinkCameraInfo[globalCameraIndex] != 0)
    {
      if(bEnabledInspectionCamera[globalCameraIndex])
      {
        typePanel->Color = clBlue;
        typePanel->Font->Color = clWhite;
        typePanel->Font->Style = typePanel->Font->Style << fsBold;
      }
      else
      {
        typePanel->Color = clWhite;
        typePanel->Font->Color = clBlack;
        typePanel->Font->Style = typePanel->Font->Style >> fsBold;
      }
    }
    else
    {
      typePanel->Color = clDkGray;
      typePanel->Font->Color = clBlack;
      typePanel->Font->Style = typePanel->Font->Style >> fsBold;
    }
	}
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::CameraEnablePanel1Click(
      TObject *Sender)
{
  TTntPanel *thePanel = (TTntPanel *)Sender;
	int selectedCameraIndex = thePanel->Tag;

  bEnabledInspectionCamera[selectedCameraIndex] = !bEnabledInspectionCamera[selectedCameraIndex];

  if (CameraMapInfo[selectedCameraIndex].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[selectedCameraIndex] == 0)
  {
    bEnabledInspectionCamera[selectedCameraIndex] = false;
  }

  RefreshCameraSelectMenu();
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::RefreshCurrentLOTInfo(void)
{
  CurrentLOTNameLabel->Caption = PreviewLOTName;
}

//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::SetLOTInformation()
{
  memset(LOTInformation, 0, sizeof(TLOTInformation) * 2000);

  TSearchRec sr, sr2;
  int iAttributes = faAnyFile;

  AnsiString resultDir = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\Result";
  if (FindFirst(resultDir + "\\*.dat", iAttributes, sr) == 0)
  {
    do
    {
      inspectedLOTCount++;
    }while (FindNext(sr) == 0);

    FindClose(sr);
  }

  if(inspectedLOTCount > 2000)
    inspectedLOTCount = 2000;

  if(inspectedLOTCount)
  {
    if (FindFirst(resultDir + "\\*.dat", iAttributes, sr2) == 0)
    {
      int lotIndex;
      lotIndex = 0;

      do
      {
        AnsiString inspectionReportFileName = resultDir + "\\" + sr2.Name;

        NFA_INSPECTION_REPORT_STRUCT Report;
        Read_InspectionReportData(inspectionReportFileName,Report);

        if(sr2.Name.SubString(0, sr2.Name.Length() - 4) == "123456_7891011") continue;

        LOTInformation[lotIndex].LOTName = sr2.Name.SubString(0, sr2.Name.Length() - 4);
        LOTInformation[lotIndex].InspectionEndTime.Val = Report.Data.InspectionEndTime;
        LOTInformation[lotIndex].goodProductCount = Report.Data.GoodTabletCount;
        LOTInformation[lotIndex].defectProductCount = Report.Data.DefectTabletCount;

        if(Report.Data.TotalTabletCount > 0)
          LOTInformation[lotIndex].ProductionDefectRatio = Report.Data.GoodTabletCount * 100.0 / (Report.Data.TotalTabletCount - Report.Data.UnInsTabletCount);
        else
          LOTInformation[lotIndex].ProductionDefectRatio = 0;

        lotIndex++;

      }while (FindNext(sr2) == 0);

      // Item을 최근 검사 순으로 재배열
      TLOTInformation rearrangeInformation;
      for(int i = 0; i < inspectedLOTCount - 1; i++)
      {
        for(int j = i + 1; j < inspectedLOTCount; j++)
        {
          if(LOTInformation[i].InspectionEndTime.Val < LOTInformation[j].InspectionEndTime.Val)
          {
            rearrangeInformation.LOTName = LOTInformation[i].LOTName;
            rearrangeInformation.InspectionEndTime.Val = LOTInformation[i].InspectionEndTime.Val;
            rearrangeInformation.goodProductCount = LOTInformation[i].goodProductCount;
            rearrangeInformation.defectProductCount = LOTInformation[i].defectProductCount;
            rearrangeInformation.ProductionDefectRatio = LOTInformation[i].ProductionDefectRatio;

            LOTInformation[i].LOTName = LOTInformation[j].LOTName;
            LOTInformation[i].InspectionEndTime.Val = LOTInformation[j].InspectionEndTime.Val;
            LOTInformation[i].goodProductCount = LOTInformation[j].goodProductCount;
            LOTInformation[i].defectProductCount = LOTInformation[j].defectProductCount;
            LOTInformation[i].ProductionDefectRatio = LOTInformation[j].ProductionDefectRatio;

            LOTInformation[j].LOTName = rearrangeInformation.LOTName;
            LOTInformation[j].InspectionEndTime.Val = rearrangeInformation.InspectionEndTime.Val;
            LOTInformation[j].goodProductCount = rearrangeInformation.goodProductCount;
            LOTInformation[j].defectProductCount = rearrangeInformation.defectProductCount;
            LOTInformation[j].ProductionDefectRatio = rearrangeInformation.ProductionDefectRatio;
          }
        }
      }

      // 재배열된 데이터를 comboBox에 순서대로 삽입
      LOTComboBox1->Items->Clear();
      for(int itemIndex = 0; itemIndex < inspectedLOTCount; itemIndex++)
      {
        LOTComboBox1->Items->Add(LOTInformation[itemIndex].LOTName);
      }
      
      LOTComboBox1->ItemIndex = 0;
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::LOTComboBox1Click(TObject *Sender)
{
  int itemIndex;
  itemIndex = LOTComboBox1->ItemIndex;

  PreviewLOTName = LOTInformation[itemIndex].LOTName;

  RefreshCurrentLOTInfo();  
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::CloseBtnClick(TObject *Sender)
{
  ReleaseComponent();
  AllRemoveResultComponents();
  
  AnsiString pathName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\Preview";

  TSearchRec sr;
  int iAttributes = faAnyFile;
  if (DirectoryExists(pathName))
  {
    if (FindFirst(pathName + "\\*.*", iAttributes, sr) == 0)
    {
      do
      {
        if (sr.Name == "." || sr.Name == "..") continue;
        DeleteFile(pathName + "\\" + sr.Name);
      } while (FindNext(sr) == 0);
      FindClose(sr);
    }
      
    RemoveDir(pathName);
  }

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

void __fastcall TPreviewInspectionForm::CameraAllControlPanelClick(
      TObject *Sender)
{
  bEnabledCameraAll = !bEnabledCameraAll;

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

  RefreshCameraSelectMenu();
  RefreshCameraAllSelectMenu();
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::RefreshCameraAllSelectMenu(void)
{
  if(bEnabledCameraAll)
  {
    CameraAllControlPanel->Color = clBlue;
    CameraAllControlPanel->Font->Color = clWhite;
    CameraAllControlPanel->Font->Style = CameraAllControlPanel->Font->Style << fsBold;
  }
  else
  {
    CameraAllControlPanel->Color = clWhite;
    CameraAllControlPanel->Font->Color = clBlack;
    CameraAllControlPanel->Font->Style = CameraAllControlPanel->Font->Style >> fsBold;
  }
}

//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::ScrollImageMouseDown(
      TObject *Sender, TMouseButton Button, TShiftState Shift, int X,
      int Y)
{
  if (!IsScrollImageMouseDown)
	{
    if(bInspectionStart) return;

		ScrollImageMouseDownPos.x = X;
		ScrollImageMouseDownPos.y = Y;
		ScrollImageMouseMovePos.x = X;
		ScrollImageMouseMovePos.y = Y;
    
		IsScrollImageMouseDown = true;
	}
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::ScrollImageMouseMove(
      TObject *Sender, TShiftState Shift, int X, int Y)
{  
	if (Y < 0 || Y >= ScrollImage->Height) return;

  int mouseDownTabletNumber;
	if (IsScrollImageMouseDown)
	{
    IsScrollImageMouseDown = false;

		ScrollImageMouseMovePos.x = X;
		ScrollImageMouseMovePos.y = Y;
		int shiftHeight = ScrollImageMouseDownPos.y - Y;

    if(prevDefectTabletNumber)
    {
      TTntPanel *prevResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(prevDefectTabletNumber));

      if(prevResultPanel)
      {
        prevResultPanel->Color = 0x00313131;
      }

      prevDefectTabletNumber = 0;
    }

		if (shiftHeight != 0)
		{
			for (int y = 0; y < ScrollImage->Height; y++)
			{
				byte *pBitmap = (byte *)ScrollImage->Picture->Bitmap->ScanLine[y];
				byte colorB = 0xFF - abs(y - Y) * 0x4F / (ScrollImage->Height / 2);
		    byte colorG = 0x7F - abs(y - Y) * 0x1F / (ScrollImage->Height / 2);
		    byte colorR = 0x7F - abs(y - Y) * 0x1F / (ScrollImage->Height / 2);
				if (y % 10 == 0)
				{
					colorB = colorG = colorR = 0;
				}

				for (int x = 0; x < ScrollImage->Width; x++)
				{
					pBitmap[x * 3] = max(0, colorB);
					pBitmap[x * 3 + 1] = max(0, colorG);
					pBitmap[x * 3 + 2] = max(0, colorR);
				}
			}

			ScrollImage->Repaint();
		}

    int shiftTabletNumber = shiftHeight / MAX_DEFAULT_RESULT_VIEW_COUNT;

    mouseDownTabletNumber = lastScrollTabletNumber;
    int displayTabletNumber = lastScrollTabletNumber - shiftTabletNumber;

    if(displayTabletNumber < 1) displayTabletNumber = 1;
    if(displayTabletNumber > currentImageIndex) displayTabletNumber = currentImageIndex;

    if(displayTabletNumber >= 1 && displayTabletNumber <= currentImageIndex)
    {
      ReleaseComponent();
      MakeResultComponents(displayTabletNumber);
      recentScrollTabletNumber = lastScrollTabletNumber;
      lastScrollTabletNumber = mouseDownTabletNumber;
    }

    IsScrollImageMouseDown = true;
	}
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::ScrollImageMouseUp(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
  if(IsScrollImageMouseDown)
  {
    lastScrollTabletNumber = recentScrollTabletNumber;
  }
  
  IsScrollImageMouseDown = false;

	for (int y = 0; y < ScrollImage->Height; y++)
	{
		byte *pBitmap = (byte *)ScrollImage->Picture->Bitmap->ScanLine[y];
		byte colorB = 0xFF - abs(y - ScrollImage->Height / 2) * 0x4F / (ScrollImage->Height / 2);
		byte colorG = 0x7F - abs(y - ScrollImage->Height / 2) * 0x1F / (ScrollImage->Height / 2);
		byte colorR = 0x7F - abs(y - ScrollImage->Height / 2) * 0x1F / (ScrollImage->Height / 2);

		if (y % 10 == 0)
		{
			colorB = colorG = colorR = 0;
		}

		for (int x = 0; x < ScrollImage->Width; x++)
		{
			pBitmap[x * 3] = colorB;
			pBitmap[x * 3 + 1] = colorG;
			pBitmap[x * 3 + 2] = colorR;
		}
	}
	ScrollImage->Repaint();
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::PreviewInspectionStartBtnClick(
      TObject *Sender)
{
  ReleaseComponent();
  
  char *validContainer;
  validContainer = NULL;
  
  AllRemoveResultComponents();
  InitDesignedComponents();
  currentImageIndex = 0;
  ProgressBar->Position = 0;

  memset(&PreviewResultCount, 0, sizeof(TPreviewResultCount));
  RefreshResultCountInfo();

  bStop = false;
  bInspectionStart = true;
  PreviewInspectionStopBtn->Enabled = true;

  RefreshDefectStringGrid(DEFECT_LIST_CONTROL_OPTION_CLEAR, NULL, NULL, NULL);
  
  SetPCEnableEvent();
  
  MessageDlgFA(PREVIEWINSPECTIN_FORM_TEXT_12, mtConfirmation, TMsgDlgButtons() << mbOK);
  
  if(InspectionImageType == IMAGE_TYPE_NORMAL)
  {
    // 촬영된 이미지
    int maxImageCount = 100;
    int EnabledCameraCount = 0;
    for(int globalCameraIndex = 1; globalCameraIndex <= SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if(bEnabledInspectionCamera[globalCameraIndex - 1])
      {
        EnabledCameraCount++;
      }
    }

    processingCount = 0;
    ProgressBar->Max = maxImageCount * EnabledCameraCount;
    ProcessingCountPanel->Caption = IntToStr(processingCount) + " / " + IntToStr(ProgressBar->Max);
    
    if(EnabledCameraCount == 0)
    {
      MessageDlgFA(PREVIEWINSPECTIN_FORM_TEXT_13, mtConfirmation, TMsgDlgButtons() << mbOK);

      bStop = false;
      bInspectionStart = false;
      PreviewInspectionStopBtn->Enabled = false;

      SetPCEnableEvent();
      return;
    }

    for(int autoImageIndex = 1; autoImageIndex <= maxImageCount; autoImageIndex++)
    {
      for(int globalCameraIndex = 1; globalCameraIndex <= SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
      {
        if(bEnabledInspectionCamera[globalCameraIndex - 1])
        {
          processingCount++;
          ProgressBar->Position++;

          if(ImageLoad(autoImageIndex, globalCameraIndex))
          {
            currentImageIndex++;

            if(currentImageIndex > MAX_INSPECTION_COUNT - 1)
            {
              MessageDlgFA(PREVIEWINSPECTIN_FORM_TEXT_14, mtConfirmation, TMsgDlgButtons() << mbOK);
              bStop = true;
              break;
            }

            if(globalCameraIndex != SD1_3D_FRONT_FACE_CAMERA_INDEX && globalCameraIndex != SD2_3D_FRONT_FACE_CAMERA_INDEX)
            {
              DoProcessing(globalCameraIndex);
            }
            else
            {
              DoProcessingFor3D(globalCameraIndex);
            }

            if(currentImageIndex > DESIGNED_IMAGE_COMPONENTS_COUNT)
            {
              MakeResultComponents(0);
            }

            SetProcessingResult(globalCameraIndex);
            RefreshResultCountInfo();

            if(DefectSW)
            {
              RefreshDefectStringGrid(DEFECT_LIST_CONTROL_OPTION_ADD, currentImageIndex, globalCameraIndex, DefectInformation.defectSeries);
            }

            if(currentImageIndex > MAX_DEFAULT_RESULT_VIEW_COUNT)
            {
              RemoveImageComponent(0);
            }

            lastScrollTabletNumber = ((currentImageIndex - 1) / MAX_DEFAULT_RESULT_VIEW_COUNT) * MAX_DEFAULT_RESULT_VIEW_COUNT + 1;
          }

          Application->ProcessMessages();
        }

        ProcessingCountPanel->Caption = IntToStr(processingCount) + " / " + IntToStr(ProgressBar->Max);

        if(bStop)
          break;
      }

      if(bStop)
        break;
    }
  }
  else
  {
    // 불량 이미지
    AnsiString DefectFolderPath;
    DefectFolderPath = ProgramPath.Defect + "\\" + ProductData.ProductName + "\\" + PreviewLOTName + "\\";
    int defectDataCount = 0;
    TIniFile *iniFile = new TIniFile(DefectFolderPath + "DBInfor.ini");
    if (iniFile)
    {
      defectDataCount = iniFile->ReadInteger("Information", "Data Count", 0);
      delete iniFile;
    }

    if(defectDataCount == 0)
    {
      processingCount = 0;
      ProgressBar->Max = 0;
      ProcessingCountPanel->Caption = "0 / 0";

      MessageDlgFA(PREVIEWINSPECTIN_FORM_TEXT_15, mtConfirmation, TMsgDlgButtons() << mbOK);

      bStop = false;
      bInspectionStart = false;
      PreviewInspectionStopBtn->Enabled = false;

      SetPCEnableEvent();
      return;
    }

    int EnabledCameraCount = 0;
    for(int globalCameraIndex = 1; globalCameraIndex <= SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      if(bEnabledInspectionCamera[globalCameraIndex - 1])
      {
        EnabledCameraCount++;
      }
    }

    if(EnabledCameraCount == 0)
    {
      processingCount = 0;
      ProgressBar->Max = 0;
      ProcessingCountPanel->Caption = "0 / 0";

      MessageDlgFA(PREVIEWINSPECTIN_FORM_TEXT_13, mtConfirmation, TMsgDlgButtons() << mbOK);

      bStop = false;
      bInspectionStart = false;
      PreviewInspectionStopBtn->Enabled = false;

      SetPCEnableEvent();
      return;
    }

    WaitingPanel->Caption = MAINFORM_MSG_13;
    WaitingPanel->Visible = true;
    this->Enabled = false;

    validContainer = new char [defectDataCount + 1];
    memset(validContainer, 0, sizeof(char) * (defectDataCount + 1));

    int maxImageCount = 0;
    AnsiString DefectDataFileName;
    for(int dataIndex = 0; dataIndex < defectDataCount; dataIndex++)
    {
      DefectDataFileName = GetDefectDataContainerFileName(dataIndex, ProductData.ProductName, PreviewLOTName);
      if (!FileExists(DefectDataFileName)) continue;

      AnsiString dataName = "Data" + IntToStr(dataIndex + 1) + ".dat";

      TFileContainer fileContainer;
      if (fileContainer.Open(DefectDataFileName))
      {
        if (fileContainer.FileContains(dataName))
        {
          TDefectFileData defectFileData;
          if (fileContainer.ExtractData(dataName, &defectFileData, sizeof(TDefectFileData)))
          {
            int DefectCameraIndex = defectFileData.DefectData.GlobalCameraIndex;

            if(bEnabledInspectionCamera[DefectCameraIndex])
            {
              maxImageCount++;
              validContainer[dataIndex] = DefectCameraIndex + 1;
            }
          }
        }
      }

      Application->ProcessMessages();
    }

    this->Enabled = true;
    WaitingPanel->Visible = false;

    if(maxImageCount == 0)
    {
      processingCount = 0;

      ProgressBar->Max = 0;
      ProcessingCountPanel->Caption = "0 / 0";

      MessageDlgFA(PREVIEWINSPECTIN_FORM_TEXT_15, mtConfirmation, TMsgDlgButtons() << mbOK);

      bStop = false;
      bInspectionStart = false;
      PreviewInspectionStopBtn->Enabled = false;

      SetPCEnableEvent();
      return;
    }

    processingCount = 0;
    ProgressBar->Max = maxImageCount;
    ProcessingCountPanel->Caption = IntToStr(processingCount) + " / " + IntToStr(ProgressBar->Max);

    for(int dataIndex = 0; dataIndex < defectDataCount; dataIndex++)
    {
      int globalCameraIndex = validContainer[dataIndex];

      if(validContainer[dataIndex])
      {
        processingCount++;
        ProgressBar->Position++;

        if(DefectImageLoad(dataIndex, globalCameraIndex))
        {
          currentImageIndex++;

          if(currentImageIndex > MAX_INSPECTION_COUNT - 1)
          {
            MessageDlgFA(PREVIEWINSPECTIN_FORM_TEXT_14, mtConfirmation, TMsgDlgButtons() << mbOK);
            bStop = true;
            break;
          }

          if(globalCameraIndex != SD1_3D_FRONT_FACE_CAMERA_INDEX && globalCameraIndex != SD2_3D_FRONT_FACE_CAMERA_INDEX)
          {
            DoProcessing(globalCameraIndex);
          }
          else
          {
            DoProcessingFor3D(globalCameraIndex);
          }

          if(currentImageIndex > DESIGNED_IMAGE_COMPONENTS_COUNT)
          {
            MakeResultComponents(0);
          }

          SetProcessingResult(globalCameraIndex);
          RefreshResultCountInfo();

          if(DefectSW)
          {
            RefreshDefectStringGrid(DEFECT_LIST_CONTROL_OPTION_ADD, currentImageIndex, globalCameraIndex, DefectInformation.defectSeries);
          }

          if(currentImageIndex > MAX_DEFAULT_RESULT_VIEW_COUNT)
          {
            RemoveImageComponent(0);
          }

          lastScrollTabletNumber = ((currentImageIndex - 1) / MAX_DEFAULT_RESULT_VIEW_COUNT) * MAX_DEFAULT_RESULT_VIEW_COUNT + 1;
        }
      }

      Application->ProcessMessages();

      ProcessingCountPanel->Caption = IntToStr(processingCount) + " / " + IntToStr(ProgressBar->Max);

      if(bStop)
        break;
    }
  }

  RemoveImageComponent(1);
  
  MessageDlgFA("Complete", mtConfirmation, TMsgDlgButtons() << mbOK);

  SetComponentQueue();
  
  bStop = false;
  bInspectionStart = false;
  PreviewInspectionStopBtn->Enabled = false;

  SetPCEnableEvent();

  if(validContainer) delete validContainer;
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::MakeResultComponents(int targetIndex)
{
  if(currentImageIndex <= DESIGNED_IMAGE_COMPONENTS_COUNT) return;

  const int DesignedPanelDistance = 376;
  int parentIndex;
  int panelLine;

  if(bInspectionStart)
  {
    if(currentImageIndex % 2 == 0)
    {
      parentIndex = 2;
    }
    else
    {
      parentIndex = 1;
    }

    panelLine = ((currentImageIndex - 1) / 2) % 4;

    TTntPanel *parentResultPanel;
    TTntLabel *parentCameraNumberLabel;
    TTntLabel *parentTabletNumberLabel;
    TTntLabel *parentInspectionResultLabel;
    TTntImage *parentResultImage;
    TShape *parantShape;

    parentResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(parentIndex));
    parentCameraNumberLabel = (TTntLabel *)FindComponent("CameraNumberLabel" + IntToStr(parentIndex));
    parentTabletNumberLabel = (TTntLabel *)FindComponent("TabletNumberLabel" + IntToStr(parentIndex));
    parentInspectionResultLabel = (TTntLabel *)FindComponent("InspectionResultLabel" + IntToStr(parentIndex));
    parentResultImage = (TTntImage *)FindComponent("ResultImage" + IntToStr(parentIndex));
    parantShape = (TShape *)FindComponent("InspectionResultShape" + IntToStr(parentIndex));
  
    TTntPanel *newResultPanel = new TTntPanel(this);
    newResultPanel->Visible = false;
    newResultPanel->Name = "ProcessingResultPanel" + IntToStr(currentImageIndex);
    newResultPanel->Parent = ImageGroupPanel;
    newResultPanel->Left = parentResultPanel->Left;
    newResultPanel->Top = parentResultPanel->Top + DesignedPanelDistance * panelLine;
    newResultPanel->Width = parentResultPanel->Width;
    newResultPanel->Height = parentResultPanel->Height;
    newResultPanel->Color = parentResultPanel->Color;
    newResultPanel->Caption = "";
    newResultPanel->DoubleBuffered = true;

    TTntImage *newResultImage = new TTntImage(this);
    newResultImage->Name = "ResultImage" + IntToStr(currentImageIndex);
    newResultImage->Parent = newResultPanel;
    newResultImage->Left = parentResultImage->Left;
    newResultImage->Top = parentResultImage->Top;
    newResultImage->Width = parentResultImage->Width;
    newResultImage->Height = parentResultImage->Height;
    newResultImage->Stretch = parentResultImage->Stretch;
    newResultImage->Visible = true;
    newResultImage->Refresh();

    TShape *newShape = new TShape(this);
    newShape->Name = "InspectionResultShape" + IntToStr(currentImageIndex);
    newShape->Parent = newResultPanel;
    newShape->Left = parantShape->Left;
    newShape->Top = parantShape->Top;
    newShape->Width = parantShape->Width;
    newShape->Height = parantShape->Height;
    newShape->Brush = parantShape->Brush;
    newShape->Shape = parantShape->Shape;
    newShape->Visible = true;

    TTntLabel *newCameraNumberLabel = new TTntLabel(this);
    newCameraNumberLabel->Name = "CameraNumberLabel" + IntToStr(currentImageIndex);
    newCameraNumberLabel->Parent = newResultPanel;
    newCameraNumberLabel->Left = parentCameraNumberLabel->Left;
    newCameraNumberLabel->Top = parentCameraNumberLabel->Top;
    newCameraNumberLabel->Width = parentCameraNumberLabel->Width;
    newCameraNumberLabel->Height = parentCameraNumberLabel->Height;
    newCameraNumberLabel->Font = parentCameraNumberLabel->Font;
    newCameraNumberLabel->Color = clBlack;
    newCameraNumberLabel->Visible = true;

    TTntLabel *newTabletNumberLabel = new TTntLabel(this);
    newTabletNumberLabel->Name = "TabletNumberLabel" + IntToStr(currentImageIndex);
    newTabletNumberLabel->Parent = newResultPanel;
    newTabletNumberLabel->Left = parentTabletNumberLabel->Left;
    newTabletNumberLabel->Top = parentTabletNumberLabel->Top;
    newTabletNumberLabel->Width = parentTabletNumberLabel->Width;
    newTabletNumberLabel->Height = parentTabletNumberLabel->Height;
    newTabletNumberLabel->Font = parentTabletNumberLabel->Font;
    newTabletNumberLabel->Color = clBlack;
    newTabletNumberLabel->Visible = true;

    TTntLabel *newInspectionResultLabel = new TTntLabel(this);
    newInspectionResultLabel->Name = "InspectionResultLabel" + IntToStr(currentImageIndex);
    newInspectionResultLabel->Parent = newResultPanel;
    newInspectionResultLabel->Left = parentInspectionResultLabel->Left;
    newInspectionResultLabel->Top = parentInspectionResultLabel->Top;
    newInspectionResultLabel->Width = parentInspectionResultLabel->Width;
    newInspectionResultLabel->Height = parentInspectionResultLabel->Height;
    newInspectionResultLabel->Font = parentInspectionResultLabel->Font;
    newInspectionResultLabel->Color = clBlack;
    newInspectionResultLabel->Visible = true;

    newResultPanel->Visible = true;
  }
  else
  {
    ProcessingResultPanel1->Visible = false;
    ProcessingResultPanel2->Visible = false;

    int startIndex = ((targetIndex - 1) / MAX_DEFAULT_RESULT_VIEW_COUNT) * MAX_DEFAULT_RESULT_VIEW_COUNT + 1;
    int endIndex = min(startIndex + (MAX_DEFAULT_RESULT_VIEW_COUNT - 1), currentImageIndex);

    lastScrollTabletNumber = startIndex;

    for(int componentIndex = startIndex; componentIndex <= endIndex; componentIndex++)
    {
      if(componentIndex % 2 == 0)
      {
        parentIndex = 2;
      }
      else
      {
        parentIndex = 1;
      }

      panelLine = ((componentIndex - 1) / 2) % 4;

      TTntPanel *parentResultPanel;
      TTntLabel *parentCameraNumberLabel;
      TTntLabel *parentTabletNumberLabel;
      TTntLabel *parentInspectionResultLabel;
      TTntImage *parentResultImage;
      TShape *parantShape;

      parentResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(parentIndex));
      parentCameraNumberLabel = (TTntLabel *)FindComponent("CameraNumberLabel" + IntToStr(parentIndex));
      parentTabletNumberLabel = (TTntLabel *)FindComponent("TabletNumberLabel" + IntToStr(parentIndex));
      parentInspectionResultLabel = (TTntLabel *)FindComponent("InspectionResultLabel" + IntToStr(parentIndex));
      parentResultImage = (TTntImage *)FindComponent("ResultImage" + IntToStr(parentIndex));
      parantShape = (TShape *)FindComponent("InspectionResultShape" + IntToStr(parentIndex));

      if(componentIndex > DESIGNED_IMAGE_COMPONENTS_COUNT)
      {
        TTntPanel *prevResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(componentIndex));
        if(prevResultPanel)
        {
          delete prevResultPanel;
        }
        TTntPanel *newResultPanel = new TTntPanel(this);
        newResultPanel->Visible = false;

        newResultPanel->Name = "ProcessingResultPanel" + IntToStr(componentIndex);
        newResultPanel->Parent = ImageGroupPanel;
        newResultPanel->Left = parentResultPanel->Left;
        newResultPanel->Top = parentResultPanel->Top + DesignedPanelDistance * panelLine;
        newResultPanel->Width = parentResultPanel->Width;
        newResultPanel->Height = parentResultPanel->Height;
        newResultPanel->Color = parentResultPanel->Color;
        newResultPanel->Caption = "";
        newResultPanel->BringToFront();
        newResultPanel->DoubleBuffered = true;

        TShape *prevShape = (TShape *)FindComponent("InspectionResultShape" + IntToStr(componentIndex));
        if(prevShape)
        {
          delete prevShape;
        }
        TShape *newShape = new TShape(this);
        newShape->Name = "InspectionResultShape" + IntToStr(componentIndex);
        newShape->Parent = newResultPanel;
        newShape->Left = parantShape->Left;
        newShape->Top = parantShape->Top;
        newShape->Width = parantShape->Width;
        newShape->Height = parantShape->Height;
        newShape->Brush = parantShape->Brush;
        newShape->Shape = parantShape->Shape;
        newShape->Visible = true;

        TTntLabel *prevCameraNumberLabel = (TTntLabel *)FindComponent("CameraNumberLabel" + IntToStr(componentIndex));
        if(prevCameraNumberLabel)
        {
          delete prevCameraNumberLabel;
        }
        TTntLabel *newCameraNumberLabel = new TTntLabel(this);
        newCameraNumberLabel->Name = "CameraNumberLabel" + IntToStr(componentIndex);
        newCameraNumberLabel->Parent = newResultPanel;
        newCameraNumberLabel->Left = parentCameraNumberLabel->Left;
        newCameraNumberLabel->Top = parentCameraNumberLabel->Top;
        newCameraNumberLabel->Width = parentCameraNumberLabel->Width;
        newCameraNumberLabel->Height = parentCameraNumberLabel->Height;
        newCameraNumberLabel->Font = parentCameraNumberLabel->Font;
        newCameraNumberLabel->Color = clBlack;
        newCameraNumberLabel->Visible = true;

        TTntLabel *prevTabletNumberLabel = (TTntLabel *)FindComponent("TabletNumberLabel" + IntToStr(componentIndex));
        if(prevTabletNumberLabel)
        {
          delete prevTabletNumberLabel;
        }
        TTntLabel *newTabletNumberLabel = new TTntLabel(this);
        newTabletNumberLabel->Name = "TabletNumberLabel" + IntToStr(componentIndex);
        newTabletNumberLabel->Parent = newResultPanel;
        newTabletNumberLabel->Left = parentTabletNumberLabel->Left;
        newTabletNumberLabel->Top = parentTabletNumberLabel->Top;
        newTabletNumberLabel->Width = parentTabletNumberLabel->Width;
        newTabletNumberLabel->Height = parentTabletNumberLabel->Height;
        newTabletNumberLabel->Font = parentTabletNumberLabel->Font;
        newTabletNumberLabel->Color = clBlack;
        newTabletNumberLabel->Visible = true;

        TTntLabel *prevInspectionResultLabel = (TTntLabel *)FindComponent("InspectionResultLabel" + IntToStr(componentIndex));
        if(prevInspectionResultLabel)
        {
          delete prevInspectionResultLabel;
        }
        TTntLabel *newInspectionResultLabel = new TTntLabel(this);
        newInspectionResultLabel->Name = "InspectionResultLabel" + IntToStr(componentIndex);
        newInspectionResultLabel->Parent = newResultPanel;
        newInspectionResultLabel->Left = parentInspectionResultLabel->Left;
        newInspectionResultLabel->Top = parentInspectionResultLabel->Top;
        newInspectionResultLabel->Width = parentInspectionResultLabel->Width;
        newInspectionResultLabel->Height = parentInspectionResultLabel->Height;
        newInspectionResultLabel->Font = parentInspectionResultLabel->Font;
        newInspectionResultLabel->Color = clBlack;
        newInspectionResultLabel->Visible = true;

        TTntImage *prevResultImage = (TTntImage *)FindComponent("ResultImage" + IntToStr(componentIndex));
        if(prevResultImage)
        {
          delete prevResultImage;
        }
        TTntImage *newResultImage = new TTntImage(this);
        newResultImage->Name = "ResultImage" + IntToStr(componentIndex);
        newResultImage->Parent = newResultPanel;
        newResultImage->Left = parentResultImage->Left;
        newResultImage->Top = parentResultImage->Top;
        newResultImage->Width = parentResultImage->Width;
        newResultImage->Height = parentResultImage->Height;
        newResultImage->Stretch = parentResultImage->Stretch;
        newResultImage->SendToBack();
        newResultImage->Visible = true;

        AnsiString pathName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\Preview";

        if (!DirectoryExists(pathName))
        {
          CreateDir(pathName);
        }

        AnsiString FileName = pathName + "\\ResultImage" + IntToStr(componentIndex) + ".bmp";

        if(FileExists(FileName))
        {
          newResultImage->Picture->Bitmap->LoadFromFile(FileName);
        }
        
        newResultImage->Refresh();
        newResultPanel->Visible = true;

        newTabletNumberLabel->Caption = "Tablet Number : " + IntToStr(ResultTable[componentIndex].TabletNumber);
        newCameraNumberLabel->Caption = "Camera Number : " + ConvertCameraIndex(ResultTable[componentIndex].CameraNumber - 1);//IntToStr(ResultTable[componentIndex].CameraNumber);
        newShape->Brush->Color = ResultTable[componentIndex].Color;

        if(ResultTable[componentIndex].DefectSW)
        {
          WideString DefectSizeStr;
          if(ResultTable[componentIndex].DefectSeries == FAT_TALBET || ResultTable[componentIndex].DefectSeries == THIN_TALBET)
            DefectSizeStr = FloatToStr((float)ResultTable[componentIndex].DefectSize*30/1000.0) +" mm";
          else if(ResultTable[componentIndex].DefectSeries == DEFECT_3D_PRINT_ERASE)
            DefectSizeStr = FloatToStr(ResultTable[componentIndex].DefectSize) + " %";
          else if(ResultTable[componentIndex].DefectSeries == DEFECT_FRONT_WHITE_ENGRAVE)
            DefectSizeStr = IntToStr(ResultTable[componentIndex].DefectSize) + " Grade";
          else if(ResultTable[componentIndex].DefectSeries == DEFECT_PRINT_POSITION_ERROR)
            DefectSizeStr = FloatToStr(ResultTable[componentIndex].DefectSize * 0.04) + " mm";
          else if(ResultTable[componentIndex].DefectSeries == DEFECT_PRINT_ROTATION_ERROR)
            DefectSizeStr = IntToStr(ResultTable[componentIndex].DefectSize) + " Degree";
          else
            DefectSizeStr = FloatToStr(DefectSizePixelToMili(ResultTable[componentIndex].DefectSize) / 100.0) + "mm";
    
          if(ResultTable[componentIndex].DefectSW == 1)
          {
            newInspectionResultLabel->Caption = "Result : Defect (" + GetDefectSeriesStr(ResultTable[componentIndex].DefectSeries) + " / " + DefectSizeStr + ")";
          }
          else
          {
            newInspectionResultLabel->Caption = "Result : Uninspect (" + GetDefectSeriesStr(ResultTable[componentIndex].DefectSeries) + " / " + DefectSizeStr + ")";
          }
        }
        else
        {
          newInspectionResultLabel->Caption = "Result : Good";
        }

        ComponentTabletNumber[ComponentQueueEndIndex] = componentIndex;
        ComponentQueueEndIndex = (ComponentQueueEndIndex + 1) & MAKE_COMPONENT_QUEUE_MASK;
      }
      else
      {
        TTntPanel *ResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(componentIndex));
        ResultPanel->Visible = true;
        ResultPanel->BringToFront();
      }
    }

    ImageGroupPanel->Refresh();
  }
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::AllRemoveResultComponents(void)
{
  TTntPanel *madeResultPanel;
  TTntLabel *madeCameraNumberLabel;
  TTntLabel *madeTabletNumberLabel;
  TTntLabel *madeInspectionResultLabel;
  TTntImage *madeResultImage;
  TShape *madeShape;

  for(int componentsIndex = currentImageIndex; componentsIndex >= DESIGNED_IMAGE_COMPONENTS_COUNT + 1; componentsIndex--)
  {
    madeResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(componentsIndex));
    if(madeResultPanel) delete madeResultPanel;

    madeCameraNumberLabel = (TTntLabel *)FindComponent("CameraNumberLabel" + IntToStr(componentsIndex));
    if(madeCameraNumberLabel) delete madeCameraNumberLabel;

    madeTabletNumberLabel = (TTntLabel *)FindComponent("TabletNumberLabel" + IntToStr(componentsIndex));
    if(madeTabletNumberLabel) delete madeTabletNumberLabel;

    madeInspectionResultLabel = (TTntLabel *)FindComponent("InspectionResultLabel" + IntToStr(componentsIndex));
    if(madeInspectionResultLabel) delete madeInspectionResultLabel;

    madeResultImage = (TTntImage *)FindComponent("ResultImage" + IntToStr(componentsIndex));
    if(madeResultImage) delete madeResultImage;

    madeShape = (TShape *)FindComponent("InspectionResultShape" + IntToStr(componentsIndex));
    if(madeShape) delete madeShape;
  }

  ImageGroupPanel->Top = 0;
  ImageGroupPanel->Height = DESIGNED_IMAGE_BOX_HEIGHT;
  ImageGroupPanel->Refresh();
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::InitDesignedComponents(void)
{
  TTntPanel *ResultPanel;
  TTntLabel *madeCameraNumberLabel;
  TTntLabel *madeTabletNumberLabel;
  TTntLabel *madeInspectionResultLabel;
  TTntImage *madeResultImage;
  TShape *madeShape;
  
  for(int componentsIndex = 1; componentsIndex <= DESIGNED_IMAGE_COMPONENTS_COUNT; componentsIndex++)
  {
    ResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(componentsIndex));
    if(ResultPanel)
    {
      ResultPanel->Color = 0x00313131;
      ResultPanel->Visible = true;
      ResultPanel->Refresh();
    }

    madeCameraNumberLabel = (TTntLabel *)FindComponent("CameraNumberLabel" + IntToStr(componentsIndex));
    if(madeCameraNumberLabel)
    {
      madeCameraNumberLabel->Caption = "Camera Number : N/A";
      madeCameraNumberLabel->Refresh();
    }

    madeTabletNumberLabel = (TTntLabel *)FindComponent("TabletNumberLabel" + IntToStr(componentsIndex));
    if(madeTabletNumberLabel)
    {
      madeTabletNumberLabel->Caption = "Tablet Number : N/A";
      madeTabletNumberLabel->Refresh();
    }

    madeInspectionResultLabel = (TTntLabel *)FindComponent("InspectionResultLabel" + IntToStr(componentsIndex));
    if(madeInspectionResultLabel)
    {
      madeInspectionResultLabel->Caption = "Result : N/A";
      madeInspectionResultLabel->Refresh();
    }

    madeResultImage = (TTntImage *)FindComponent("ResultImage" + IntToStr(componentsIndex));
    if(madeResultImage)
    {
      madeResultImage->Canvas->Brush->Color = 0x00313131;
	    madeResultImage->Canvas->Brush->Style = bsSolid;
      madeResultImage->Picture->Bitmap->PixelFormat = pf24bit;
      madeResultImage->Picture->Bitmap->Width = SYSTEM_CAMERA_WIDTH;
      madeResultImage->Picture->Bitmap->Height = SYSTEM_CAMERA_HEIGHT;
	    madeResultImage->Canvas->FillRect(Rect(0, 0, SYSTEM_CAMERA_WIDTH, SYSTEM_CAMERA_HEIGHT));
      madeResultImage->Refresh();
    }

    madeShape = (TShape *)FindComponent("InspectionResultShape" + IntToStr(componentsIndex));
    if(madeShape)
    {
      madeShape->Brush->Color = clWhite;
      madeShape->Refresh();
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::PreviewInspectionStopBtnClick(
      TObject *Sender)
{
  bStop = true;
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::SetPCEnableEvent(void)
{
  if(bInspectionStart)
  {
    InspectionImageSettingGroupBox->Enabled = false;
    InspectionLOTSettingGroupBox->Enabled = false;
    CameraSettingGroupBox->Enabled = false;
    PreviewInspectionStartBtn->Enabled = false;
    CloseBtn->Enabled = false;
    ScrollImage->Enabled = false;
    DefectListStringGrid->Enabled = false;
    UpListShiftPanel->Enabled = false;
    DownListShiftPanel->Enabled = false;
  }
  else
  {
    InspectionImageSettingGroupBox->Enabled = true;
    InspectionLOTSettingGroupBox->Enabled = true;
    CameraSettingGroupBox->Enabled = true;
    PreviewInspectionStartBtn->Enabled = true;
    CloseBtn->Enabled = true;
    ScrollImage->Enabled = true;
    DefectListStringGrid->Enabled = true;
    UpListShiftPanel->Enabled = true;
    DownListShiftPanel->Enabled = true;
  }

  if(CameraSettingGroupBox->Enabled)
  {
    RefreshCameraSelectMenu();
    RefreshCameraAllSelectMenu();
  }
  else
  {
    for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
    {
      TTntPanel *typePanel = (TTntPanel *)FindComponent("CameraEnablePanel" + IntToStr(globalCameraIndex + 1));

      typePanel->Color = clDkGray;
      typePanel->Font->Color = clBlack;
      typePanel->Font->Style = typePanel->Font->Style >> fsBold;
    }

    CameraAllControlPanel->Color = clDkGray;
    CameraAllControlPanel->Font->Color = clBlack;
    CameraAllControlPanel->Font->Style = CameraAllControlPanel->Font->Style >> fsBold;
  }

  if(InspectionImageSettingGroupBox->Enabled)
  {
    RefreshImageSelectMenu();
  }
  else
  {
    for (int typeIndex = 0; typeIndex < 2; typeIndex++)
    {
      TTntPanel *typePanel = (TTntPanel *)FindComponent("ImageSelectPanel" + IntToStr(typeIndex + 1));
      typePanel->Color = clDkGray;
      typePanel->Font->Color = clBlack;
      typePanel->Font->Style = typePanel->Font->Style >> fsBold;
    }
  }

  if(InspectionLOTSettingGroupBox->Enabled)
  {
    InspectionLOTSettingGroupBox->Visible = false;
    if(InspectionImageType == IMAGE_TYPE_DEFECT)
    {
      if(!(ProductData.LOTName.IsEmpty() || inspectedLOTCount == 0))
      {
        InspectionLOTSettingGroupBox->Visible = true;
      }
    }
  }
  else
  {
    InspectionLOTSettingGroupBox->Visible = false;
  }

  if(ScrollImage->Enabled)
  {
    ScrollImage->Picture->Bitmap->Width = ScrollImage->Width;
    ScrollImage->Picture->Bitmap->Height = ScrollImage->Height;
    ScrollImage->Picture->Bitmap->PixelFormat = pf24bit;
    for (int y = 0; y < ScrollImage->Height; y++)
    {
      byte *pBitmap = (byte *)ScrollImage->Picture->Bitmap->ScanLine[y];
      byte colorB = 0xFF - abs(y - ScrollImage->Height / 2) * 0x4F / (ScrollImage->Height / 2);
      byte colorG = 0x7F - abs(y - ScrollImage->Height / 2) * 0x1F / (ScrollImage->Height / 2);
      byte colorR = 0x7F - abs(y - ScrollImage->Height / 2) * 0x1F / (ScrollImage->Height / 2);
      if (y % 10 == 0)
      {
        colorB = colorG = colorR = 0;
      }

      for (int x = 0; x < ScrollImage->Width; x++)
      {
        pBitmap[x * 3] = colorB;
        pBitmap[x * 3 + 1] = colorG;
        pBitmap[x * 3 + 2] = colorR;
      }
    }

    ScrollImage->Refresh();
  }
  else
  {
    ScrollImage->Picture->Bitmap->Width = ScrollImage->Width;
    ScrollImage->Picture->Bitmap->Height = ScrollImage->Height;
    ScrollImage->Picture->Bitmap->PixelFormat = pf24bit;
    for (int y = 0; y < ScrollImage->Height; y++)
    {
      byte *pBitmap = (byte *)ScrollImage->Picture->Bitmap->ScanLine[y];
      byte colorB = 0x7F - abs(y - ScrollImage->Height / 2) * 0x1F / (ScrollImage->Height / 2);
      byte colorG = 0x7F - abs(y - ScrollImage->Height / 2) * 0x1F / (ScrollImage->Height / 2);
      byte colorR = 0x7F - abs(y - ScrollImage->Height / 2) * 0x1F / (ScrollImage->Height / 2);
      if (y % 10 == 0)
      {
        colorB = colorG = colorR = 0;
      }

      for (int x = 0; x < ScrollImage->Width; x++)
      {
        pBitmap[x * 3] = colorB;
        pBitmap[x * 3 + 1] = colorG;
        pBitmap[x * 3 + 2] = colorR;
      }
    }

    ScrollImage->Refresh();
  }

  if(UpListShiftPanel->Enabled)
  {
    UpListShiftPanel->Font->Color = clWhite;
  }
  else
  {
    UpListShiftPanel->Font->Color = clDkGray;
  }

  if(DownListShiftPanel->Enabled)
  {
    DownListShiftPanel->Font->Color = clWhite;
  }
  else
  {
    DownListShiftPanel->Font->Color = clGray;
  }

  if(DefectListStringGrid->Enabled)
  {
    DefectListStringGrid->FixedColor = 0x00646464;
    DefectListStringGrid->Font->Color = clWhite;
  }
  else
  {
    DefectListStringGrid->FixedColor = 0x00313131;
    DefectListStringGrid->Font->Color = clGray;
  }
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::DoProcessing(int cameraIndex)
{
  if (!ReadSetupData(&TabletSetupData))
	{
    MessageDlgFA(DEFECTINFOFORM_MSG_01, mtConfirmation, TMsgDlgButtons() << mbOK);
	}

	if (!ReadStudyData(&TabletStudyData))
	{
    MessageDlgFA(DEFECTINFOFORM_MSG_02, mtConfirmation, TMsgDlgButtons() << mbOK);
	}

	//AnsiString gradeFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".grd";
	//LoadGradeData(gradeFileName, TabletGradeData);
  memcpy(&TabletGradeData, &previewSrcGradeData, sizeof(TTabletGradeData));

	InspectionOrStudy = INSPECTION_MODE;

	MakeTabletCharacterData(&ProductData, &TabletCharacter, &MachineParams);
  
  SetSideFaceDataAddress(&tempSideData[0]);

  int SDNum;
	if (cameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX)
  {
		SDNum = SUCTION_DISK_NUM1;
    FrontFaceSetUpDataTransForm(FRONT_FACE, SDNum);
  }
	else if (cameraIndex == SD2_2D_FRONT_FACE_CAMERA_INDEX)
  {
		SDNum = SUCTION_DISK_NUM2;
    FrontFaceSetUpDataTransForm(FRONT_FACE, SDNum);
  }

	switch (cameraIndex)
	{
	case SD1_2D_FRONT_FACE_CAMERA_INDEX:
	case SD2_2D_FRONT_FACE_CAMERA_INDEX:

		InspectionKind = FRONT_FACE;
		ProcessingStartForFrontFace(InspectionOrStudy, cameraIndex, InspectionImageType);
		break;

	case SD1_2D_SIDE_FACE_P45_CAMERA_INDEX:
	case SD2_2D_SIDE_FACE_P45_CAMERA_INDEX:
	case SD1_2D_OTHER_SIDE_FACE_P45_CAMERA_INDEX:
	case SD2_2D_OTHER_SIDE_FACE_P45_CAMERA_INDEX:
		InspectionKind = SIDE_FACE_P45;
		ProcessingStartForSideFace_P45(InspectionOrStudy, cameraIndex, InspectionImageType);
		break;

	case SD1_2D_SIDE_FACE_00_CAMERA_INDEX:
	case SD2_2D_SIDE_FACE_00_CAMERA_INDEX:
	case SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX:
	case SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX:
		InspectionKind = SIDE_FACE_0;
		ProcessingStartForSideFace_0(InspectionOrStudy, cameraIndex, InspectionImageType);
		break;

	case SD1_2D_SIDE_FACE_M45_CAMERA_INDEX:
	case SD2_2D_SIDE_FACE_M45_CAMERA_INDEX:
	case SD1_2D_OTHER_SIDE_FACE_M45_CAMERA_INDEX:
	case SD2_2D_OTHER_SIDE_FACE_M45_CAMERA_INDEX:
		InspectionKind = SIDE_FACE_M45;
		ProcessingStartForSideFace_M45(InspectionOrStudy, cameraIndex, InspectionImageType);
		break;
	}
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::DoProcessingFor3D(int cameraIndex)
{
	if (!ReadStudyData(&TabletStudyData))
	{
    MessageDlgFA(DEFECTINFOFORM_MSG_02, mtConfirmation, TMsgDlgButtons() << mbOK);
	}

	if (!ReadSetupData(&TabletSetupData))
	{
    MessageDlgFA(DEFECTINFOFORM_MSG_01, mtConfirmation, TMsgDlgButtons() << mbOK);
	}

	if (!Read3DSetupData(&Tablet3DSetupData))
	{
    MessageDlgFA(DEFECTINFOFORM_MSG_01, mtConfirmation, TMsgDlgButtons() << mbOK);
	}

	InspectionOrStudy = INSPECTION_MODE;

	//AnsiString gradeFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".grd";
	//LoadGradeData(gradeFileName, TabletGradeData);
  memcpy(&TabletGradeData, &previewSrcGradeData, sizeof(TTabletGradeData));

	InspectionKind = FRONT_FACE_SPECIAL;

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

	int SDNum;
	if (cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX)
		SDNum = SUCTION_DISK_NUM1;
	else
		SDNum = SUCTION_DISK_NUM2;

	CPBCommonVariableInitial();
	SetUpDataTransFormForThreeD(InspectionKind, SDNum);

	ProcessingStartForFrontFace_3D(InspectionOrStudy, cameraIndex, InspectionImageType + 1);
}
//---------------------------------------------------------------------------

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

bool __fastcall TPreviewInspectionForm::ImageLoad(int imageIndex, int cameraIndex)
{
  return ExtractBayerImage(BayerImage, imageIndex, cameraIndex);
}
//---------------------------------------------------------------------------
bool __fastcall TPreviewInspectionForm::Read3DSetupData(TTablet3DSetupData *tablet3DSetupData)
{
	AnsiString setupDataFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".sdt_3D";
	if (FileExists(setupDataFileName))
	{
		TFileStream *fileStream = new TFileStream(setupDataFileName, fmOpenRead);
		if (fileStream)
		{
			fileStream->Read(tablet3DSetupData, sizeof(TTablet3DSetupData));
			delete fileStream;
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::setPosSetupData(TTabletSetupData *pTabletSetupData)
{
	// modify disk base height position
	for (int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
	{
    pTabletSetupData->cameraZoom[globalCameraIndex] = MachineParams.CameraResolution[globalCameraIndex];
    
		pTabletSetupData->ImageCutStartX[globalCameraIndex] = ProductData.BoundaryLeft[globalCameraIndex] / 4 * 4;
		pTabletSetupData->ImageCutEndX[globalCameraIndex] = ProductData.BoundaryRight[globalCameraIndex] / 4 * 4;
		pTabletSetupData->ImageCutStartY[globalCameraIndex] = ProductData.BoundaryTop[globalCameraIndex] / 4 * 4;
		pTabletSetupData->ImageCutEndY[globalCameraIndex] = ProductData.BoundaryBottom[globalCameraIndex] / 4 * 4;

		pTabletSetupData->DiskBaseHeightPosition[globalCameraIndex] = MachineParams.DiscCenterPos[globalCameraIndex] / 4 * 4;
	}

	WriteSetupData(pTabletSetupData);
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::WriteSetupData(TTabletSetupData *tabletSetupData)
{
	AnsiString setupDataFileName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\" + ProductData.ProductCode + ".sdt";

	if (FileExists(setupDataFileName))
	{
		TFileStream *fileStream = new TFileStream(setupDataFileName, fmOpenWrite);
		if (fileStream)
		{
			fileStream->Write(tabletSetupData, sizeof(TTabletSetupData));
			delete fileStream;
		}
	}
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::SetProcessingResult(int cameraIndex)
{
  TTntPanel *ResultPanel;
  TTntLabel *CameraNumberLabel;
  TTntLabel *TabletNumberLabel;
  TTntLabel *InspectionResultLabel;
  TTntImage *ResultImage;
  TShape *InspectionResultShape;

  ResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(currentImageIndex));
  CameraNumberLabel = (TTntLabel *)FindComponent("CameraNumberLabel" + IntToStr(currentImageIndex));
  TabletNumberLabel = (TTntLabel *)FindComponent("TabletNumberLabel" + IntToStr(currentImageIndex));
  InspectionResultLabel = (TTntLabel *)FindComponent("InspectionResultLabel" + IntToStr(currentImageIndex));
  ResultImage = (TTntImage *)FindComponent("ResultImage" + IntToStr(currentImageIndex));
  InspectionResultShape = (TShape *)FindComponent("InspectionResultShape" + IntToStr(currentImageIndex));

  Byte *ptr;
  int tempAddress;
  int areaValue;

  Graphics::TBitmap *img1;
  img1 = new Graphics::TBitmap();
  img1->Width =  MAX_IMAGE_WIDTH;
  img1->Height =  MAX_IMAGE_HEIGHT;
  img1->PixelFormat = pf24bit;

  if(cameraIndex == SD1_3D_FRONT_FACE_CAMERA_INDEX ||
      cameraIndex == SD2_3D_FRONT_FACE_CAMERA_INDEX)
  {
    unsigned char tempDPImage[MAX_IMAGE_WIDTH * MAX_IMAGE_HEIGHT * 3];
	  memset(tempDPImage, 0, MAX_IMAGE_WIDTH * MAX_IMAGE_HEIGHT * 3);

    for (int i = 0; i < ImageHeight; i++)
    {
      for (int j = 0; j < ImageWidth; j++)
      {
        tempAddress = MAX_IMAGE_WIDTH * i + j;

        areaValue = InspectionArea[tempAddress];

        tempDPImage[tempAddress * 3 + 0] = AdjustThreeD_Data[tempAddress];
        tempDPImage[tempAddress * 3 + 1] = AdjustThreeD_Data[tempAddress];
        tempDPImage[tempAddress * 3 + 2] = AdjustThreeD_Data[tempAddress];

        if(InspectionArea[tempAddress] == PRINT_AREA)
        {
          tempDPImage[tempAddress * 3 + 0] = AdjustThreeD_Data[tempAddress] / 2;
          tempDPImage[tempAddress * 3 + 1] = AdjustThreeD_Data[tempAddress];
          tempDPImage[tempAddress * 3 + 2] = min(255, AdjustThreeD_Data[tempAddress] * 2);
        }
        else if(InspectionArea[tempAddress] == FRONT_SHAPE_EDGE)
        {
          tempDPImage[tempAddress * 3 + 0] = AdjustThreeD_Data[tempAddress];
          tempDPImage[tempAddress * 3 + 1] = 255;
          tempDPImage[tempAddress * 3 + 2] = AdjustThreeD_Data[tempAddress] / 2;
        }
        else if(InspectionArea[tempAddress] == FRONT_SHAPE_EDGE_NEIGHBOR)
        {
          tempDPImage[tempAddress * 3 + 0] = 255;
          tempDPImage[tempAddress * 3 + 1] = (threeDShellImage[tempAddress] * 41) & 0xFF; // shell
          tempDPImage[tempAddress * 3 + 2] = AdjustThreeD_Data[tempAddress] / 2;
        }
        else if(InspectionArea[tempAddress])
        {
          tempDPImage[tempAddress * 3 + 0] = AdjustThreeD_Data[tempAddress] / 2;
          tempDPImage[tempAddress * 3 + 1] = AdjustThreeD_Data[tempAddress] / 2;
          tempDPImage[tempAddress * 3 + 2] = AdjustThreeD_Data[tempAddress];
        }

        if(LabelImage_Virtual[tempAddress])
        {
          tempDPImage[tempAddress * 3 + 0] = (LabelImage_Virtual[tempAddress] * 17) & 0xFF;
          tempDPImage[tempAddress * 3 + 1] = (LabelImage_Virtual[tempAddress] * 41) & 0xFF;
          tempDPImage[tempAddress * 3 + 2] = (LabelImage_Virtual[tempAddress] * 73) & 0xFF;
        }
      }
    }

    for (int i = 0; i < ImageHeight; i++)
    {
      ptr = (byte*)img1->ScanLine[i];
      for (int j = 0; j < ImageWidth; j++)
      {
        tempAddress = MAX_IMAGE_WIDTH * i + j;

        ptr[3 * j + 0] = tempDPImage[tempAddress * 3 + 0];
        ptr[3 * j + 1] = tempDPImage[tempAddress * 3 + 1];
        ptr[3 * j + 2] = tempDPImage[tempAddress * 3 + 2];
      }
    }

    ResultImage->Picture->Bitmap->Assign(img1);
    ResultImage->Refresh();
  }
  else if(cameraIndex == SD1_2D_FRONT_FACE_CAMERA_INDEX ||
          cameraIndex == SD2_2D_FRONT_FACE_CAMERA_INDEX)
  {
    for(int y = 0; y < ImageHeight; y++)
    {
      ptr = (byte*) img1->ScanLine[y];
      for(int x = 0; x < ImageWidth; x++)
      {
        tempAddress =  MAX_IMAGE_WIDTH*y + x;
        areaValue = InspectionArea[tempAddress];
        if(areaValue != 0)
        {
          if(areaValue == FRONT_SHAPE_EDGE_NEIGHBOR)
          {
            ptr[3*x] =  min(255, ColorSourceImage[ (tempAddress)*3+0] + 60);
            ptr[3*x+1] = ColorSourceImage[ (tempAddress)*3+1];
            ptr[3*x+2] = 255;
          }
          else if(areaValue ==  FRONT_SHAPE_EDGE)
          {
            ptr[3*x] = 255;
            ptr[3*x+1] = ColorSourceImage[ (tempAddress)*3+1];
            ptr[3*x+2] = min(255, ColorSourceImage[ (tempAddress)*3+2] + 60);
          }
          else if(areaValue ==  NORMAL_INPECTION_AREA)
          {
            ptr[3*x] =  ColorSourceImage[ (tempAddress)*3+0];
            ptr[3*x+1] = min(ColorSourceImage[ (tempAddress)*3+1] + 60, 255);
            ptr[3*x+2] = ColorSourceImage[ (tempAddress)*3+2];
          }
          else if(areaValue == PRINT_AREA || areaValue == FRONT_FACE_SPLIT_AREA)
          {
            ptr[3*x] = min(ColorSourceImage[ (tempAddress)*3+0] + 40, 255);
            ptr[3*x+1] = min(ColorSourceImage[ (tempAddress)*3+1] + 40, 255);
            ptr[3*x+2] = 0;
          }
          else if(areaValue == PRINT_NEIGHBOR_SHORT)
          {
            ptr[3*x] = 0;
            ptr[3*x+1] = min(ColorSourceImage[ (tempAddress)*3+1] + 70, 255);
            ptr[3*x+2] = min(ColorSourceImage[ (tempAddress)*3+2] + 70, 255);
          }
          else if(areaValue == PRINT_NEIGHBOR_LONG)
          {
            ptr[3*x] = min(ColorSourceImage[ (tempAddress)*3+0] + 50, 255);
            ptr[3*x+1] = 0;
            ptr[3*x+2] = min(ColorSourceImage[ (tempAddress)*3+2] + 20, 255);
          }
          else if(areaValue == FRONT_SHAPE_EDGE_AND_PRINT_SHORT || areaValue == FRONT_SHAPE_EDGE_AND_PRINT_LONG)
          {
            ptr[3*x] = min(ColorSourceImage[ (tempAddress)*3+0] + 70, 255);
            ptr[3*x+1] = 0;
            ptr[3*x+2] = 0;
          }
          else if(areaValue == FRONT_MASKING_AREA)
          {
            ptr[3*x] = 255;
            ptr[3*x+1] = ColorSourceImage[(tempAddress)*3+1];
            ptr[3*x+2] = ColorSourceImage[(tempAddress)*3+2];
          }
          else
          {
            ptr[3*x] =  ColorSourceImage[ (tempAddress)*3+0];
            ptr[3*x+1] = ColorSourceImage[ (tempAddress)*3+1] ;
            ptr[3*x+2] = ColorSourceImage[ (tempAddress)*3+2] ;
          }

          if(DefectSW && (DefectInformation.defectSeries == DEFECT_PRINT_SPREAD || DefectInformation.defectSeries == DEFECT_PRINT_ERASE))
          {
            if(LabelImage_Virtual[tempAddress])
            {
              ptr[3*x] = 0;
              ptr[3*x+1] = 0;
              ptr[3*x+2] = 255;
            }
          }
          else
          {
            if(LabelImage_Virtual[tempAddress])
            {
              ptr[3*x] = (LabelImage_Virtual[tempAddress] * 17) & 0xFF;
              ptr[3*x+1] = (LabelImage_Virtual[tempAddress] * 41) & 0xFF;
              ptr[3*x+2] = (LabelImage_Virtual[tempAddress] * 73) & 0xFF;
            }
          }
        }
        else
        {
          ptr[3*x] =  ColorSourceImage[ (tempAddress)*3+0];
          ptr[3*x+1] = ColorSourceImage[ (tempAddress)*3+1];
          ptr[3*x+2] = ColorSourceImage[ (tempAddress)*3+2];
        }
      }
    }

    ResultImage->Picture->Bitmap->Assign(img1);
    ResultImage->Refresh();
  }
  else if(cameraIndex == SD1_2D_SIDE_FACE_P45_CAMERA_INDEX ||
          cameraIndex == SD2_2D_SIDE_FACE_P45_CAMERA_INDEX ||
          cameraIndex == SD1_2D_OTHER_SIDE_FACE_P45_CAMERA_INDEX ||
          cameraIndex == SD2_2D_OTHER_SIDE_FACE_P45_CAMERA_INDEX ||
          cameraIndex == SD1_2D_SIDE_FACE_M45_CAMERA_INDEX ||
          cameraIndex == SD2_2D_SIDE_FACE_M45_CAMERA_INDEX ||
          cameraIndex == SD1_2D_OTHER_SIDE_FACE_M45_CAMERA_INDEX ||
          cameraIndex == SD2_2D_OTHER_SIDE_FACE_M45_CAMERA_INDEX ||
          cameraIndex == SD1_2D_SIDE_FACE_00_CAMERA_INDEX ||
          cameraIndex == SD2_2D_SIDE_FACE_00_CAMERA_INDEX ||
          cameraIndex == SD1_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX ||
          cameraIndex == SD2_2D_OTHER_SIDE_FACE_00_CAMERA_INDEX)
  {
    for(int y = 0; y < ImageHeight; y++)
    {
      ptr = (byte*) img1->ScanLine[y];
      for(int x = 0; x < ImageWidth; x++)
      {
        tempAddress =  MAX_IMAGE_WIDTH*y + x;
        areaValue = InspectionArea[tempAddress];

        if(areaValue == SIDE_SHAPE_BOTTOM_EDGE_SHORT_NEIGHBOR)
        {
          ptr[3*x] = 255;
          ptr[3*x+1] = ColorSourceImage[(tempAddress)*3+1];
          ptr[3*x+2] = 255;
        }
        else if(areaValue == SIDE_SHAPE_BOTTOM_EDGE_LONG_NEIGHBOR)
        {
          ptr[3*x] = ColorSourceImage[(tempAddress)*3+0];
          ptr[3*x+1] = 255;
          ptr[3*x+2] = 255;
        }
        else if (areaValue == SIDE_SHAPE_TOP_NORMAL_BOUNDARY_AREA)
        {
          ptr[3 * x] = 0;
          ptr[3 * x + 1] = min(ColorSourceImage[(tempAddress) * 3 + 1] + 60, 255);
          ptr[3 * x + 2] = min(ColorSourceImage[(tempAddress) * 3 + 2] + 60, 255);
        }
        else if (areaValue == SIDE_SHAPE_UNINSPECTION_AREA)
        {
          ptr[3 * x] = min(ColorSourceImage[(tempAddress) * 3 + 0] + 60, 255);
          ptr[3 * x + 1] = min(ColorSourceImage[(tempAddress) * 3 + 1] + 60, 255);
          ptr[3 * x + 2] = 0;
        }
        else if(areaValue == SIDE_SHAPE_TOP_EDGE_UPPER_NEIGHBOR)
        {
          ptr[3*x] = ColorSourceImage[(tempAddress)*3+0];
          ptr[3*x+1] = ColorSourceImage[(tempAddress)*3+1];
          ptr[3*x+2] = min(ColorSourceImage[(tempAddress)*3+2] + 60, 255);
        }
        else if(areaValue == NORMAL_INPECTION_AREA)
        {
          ptr[3*x] = ColorSourceImage[(tempAddress)*3+0];
          ptr[3*x+1] = ColorSourceImage[(tempAddress)*3+1];
          ptr[3*x+2] = min(ColorSourceImage[(tempAddress)*3+2] + 60, 255);
        }
        else if(areaValue == NORMAL_INPECTION_AREA2)
        {
          ptr[3*x] = ColorSourceImage[(tempAddress)*3+0];
          ptr[3*x+1] = min(ColorSourceImage[(tempAddress)*3+1] + 60, 255);
          ptr[3*x+2] = ColorSourceImage[(tempAddress)*3+2];
        }
        else if(areaValue == SIDE_SHAPE_MULTI_TABLET_BOUNDARY_AREA)
        {
          ptr[3 * x] = 0;
          ptr[3 * x + 1] = min(ColorSourceImage[(tempAddress) * 3 + 1] + 60, 255);
          ptr[3 * x + 2] = min(ColorSourceImage[(tempAddress) * 3 + 0] + 60, 255);
        }
        else
        {
          ptr[3*x] = ColorSourceImage[(tempAddress)*3+0];
          ptr[3*x+1] = ColorSourceImage[(tempAddress)*3+1];
          ptr[3*x+2] = ColorSourceImage[(tempAddress)*3+2];
        }

        if(LabelImage_Virtual[tempAddress])
        {
          ptr[3*x] = 0;
          ptr[3*x+1] = 0;
          ptr[3*x+2] = 255;
        }
      }
    }

    ResultImage->Picture->Bitmap->Assign(img1);
    ResultImage->Refresh();
  }

  PreviewResultCount.TotalCount++;
  
  if(DefectSW)
  {
    ResultImage->Canvas->Pen->Width = 2;
    ResultImage->Canvas->Pen->Color = clRed;
    ResultImage->Canvas->Brush->Style = bsClear;
    ResultImage->Canvas->Rectangle(DefectInformation.defectPositionStartX, DefectInformation.defectPositionStartY, DefectInformation.defectPositionEndX, DefectInformation.defectPositionEndY);

    WideString DefectSizeStr;
    if(DefectInformation.defectSeries == FAT_TALBET || DefectInformation.defectSeries == THIN_TALBET)
      DefectSizeStr = FloatToStr((float)DefectInformation.size*30/1000.0) +" mm";
    else if(DefectInformation.defectSeries == DEFECT_3D_PRINT_ERASE)
      DefectSizeStr = FloatToStr(DefectInformation.size) + " %";
    else if(DefectInformation.defectSeries == DEFECT_FRONT_WHITE_ENGRAVE)
      DefectSizeStr = IntToStr(DefectInformation.size) + " Grade";
    else if(DefectInformation.defectSeries == DEFECT_PRINT_POSITION_ERROR)
      DefectSizeStr = FloatToStr(DefectInformation.size * 0.04) + " mm";
    else if(DefectInformation.defectSeries == DEFECT_PRINT_ROTATION_ERROR)
      DefectSizeStr = IntToStr(DefectInformation.size) + " Degree";
    else
      DefectSizeStr = FloatToStr(DefectSizePixelToMili(DefectInformation.size) / 100.0) + "mm";
    
    if(DefectSW == 1)
    {
      InspectionResultLabel->Caption = "Result : Defect (" + GetDefectSeriesStr(DefectInformation.defectSeries) + " / " + DefectSizeStr + ")";
      InspectionResultShape->Brush->Color = clRed;

      PreviewResultCount.DefectCount++;
    }
    else
    {
      InspectionResultLabel->Caption = "Result : Uninspect (" + GetDefectSeriesStr(DefectInformation.defectSeries) + " / " + DefectSizeStr + ")";
      InspectionResultShape->Brush->Color = clYellow;

      PreviewResultCount.UninsCount++;
    }
  }
  else
  {
    InspectionResultLabel->Caption = "Result : Good";
    InspectionResultShape->Brush->Color = clLime;

    PreviewResultCount.GoodCount++;
  }

  if(DefectSW)
  {
    PreviewResultCount.CameraDefectRate[cameraIndex - 1]++;
  }

  CameraNumberLabel->Caption = "Camera Number : " + ConvertCameraIndex(cameraIndex - 1);//IntToStr(cameraIndex);
  TabletNumberLabel->Caption = "Tablet Number : " + IntToStr(currentImageIndex);
  ResultPanel->Color = 0x00313131;

  ResultPanel->Refresh();
  CameraNumberLabel->Refresh();
  TabletNumberLabel->Refresh();
  InspectionResultLabel->Refresh();
  ResultImage->Refresh();
  InspectionResultShape->Refresh();

  ResultTable[currentImageIndex].TabletNumber = currentImageIndex;
  ResultTable[currentImageIndex].CameraNumber = cameraIndex;
  ResultTable[currentImageIndex].DefectSW = DefectSW;
  ResultTable[currentImageIndex].DefectSeries = DefectInformation.defectSeries;
  ResultTable[currentImageIndex].DefectSize = DefectInformation.size;
  ResultTable[currentImageIndex].Color = InspectionResultShape->Brush->Color;
  
  AnsiString pathName = ProgramPath.Product + "\\" + ProductData.ProductCode + "\\Preview";

  if (!DirectoryExists(pathName))
  {
    CreateDir(pathName);
  }

  AnsiString FileName = pathName + "\\ResultImage" + IntToStr(currentImageIndex) + ".bmp";
  ResultImage->Picture->Bitmap->SaveToFile(FileName);

  delete(img1);
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::RefreshResultCountInfo()
{
  TotalTabletCountLabel->Caption = IntToStr(PreviewResultCount.TotalCount);
  GoodTabletCountLabel->Caption = IntToStr(PreviewResultCount.GoodCount);
  DefectTabletCountLabel->Caption = IntToStr(PreviewResultCount.DefectCount);
  UnInsTabletCountLabel->Caption = IntToStr(PreviewResultCount.UninsCount);

  InspectionChart->Series[0]->Clear();
  InspectionChart->Series[0]->Add(PreviewResultCount.GoodCount, "Good", clLime);
  InspectionChart->Series[0]->Add(PreviewResultCount.DefectCount, "Defect", clRed);
	InspectionChart->Series[0]->Add(PreviewResultCount.UninsCount, "Un-Ins", clYellow);

  DefectChart->Series[0]->Clear();
  for(int globalCameraIndex = 0; globalCameraIndex < SYSTEM_TOTAL_CAMERA_COUNT; globalCameraIndex++)
  {
    if(PreviewResultCount.CameraDefectRate[globalCameraIndex])
    {
      DefectChart->Series[0]->Add(PreviewResultCount.CameraDefectRate[globalCameraIndex], "CAM" + IntToStr(globalCameraIndex + 1), defectColorList[globalCameraIndex]);
    }
  }
}

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

void __fastcall TPreviewInspectionForm::RefreshDefectStringGrid(int option, int tabletNumber, int cameraNumber, int DefectSeries)
{
  DefectListStringGrid->Cells[0][0] = "Tablet No.";
	DefectListStringGrid->Cells[1][0] = "Defect Info";
	DefectListStringGrid->Cells[2][0] = "Camera No.";

  DefectListStringGrid->ColWidths[0] = 80;
  DefectListStringGrid->ColWidths[2] = 80;
  DefectListStringGrid->ColWidths[1] = max(0, DefectListStringGrid->Width - 30 - 80 - 80);

  if(option == DEFECT_LIST_CONTROL_OPTION_CLEAR)
  {
    prevDefectTabletNumber = 0;

    DefectListStringGrid->Cells[0][1] = "";
    DefectListStringGrid->Cells[1][1] = "";
	  DefectListStringGrid->Cells[2][1] = "";
    
    DefectListStringGrid->Row = 1;
    DefectListStringGrid->RowCount = 2;
  }
  else if(option == DEFECT_LIST_CONTROL_OPTION_ADD)
  {
    DefectListStringGrid->Cells[0][DefectListStringGrid->RowCount - 1] = IntToStr(tabletNumber);
    DefectListStringGrid->Cells[1][DefectListStringGrid->RowCount - 1] = GetDefectSeriesStr(DefectSeries);

	  //DefectListStringGrid->Cells[2][DefectListStringGrid->RowCount - 1] = IntToStr(cameraNumber);
    AnsiString ConvertString = ConvertCameraIndex(cameraNumber-1);
    DefectListStringGrid->Cells[2][DefectListStringGrid->RowCount - 1] = ConvertString;

    DefectListStringGrid->RowCount++;

    DefectListStringGrid->Cells[0][DefectListStringGrid->RowCount - 1] = "";
    DefectListStringGrid->Cells[1][DefectListStringGrid->RowCount - 1] = "";
	  DefectListStringGrid->Cells[2][DefectListStringGrid->RowCount - 1] = "";
  }

  DefectListStringGrid->Refresh();
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::DefectListStringGridClick(
      TObject *Sender)
{
  if(DefectListStringGrid->Row > 0)
  {
    if(!DefectListStringGrid->Cells[0][DefectListStringGrid->Row].IsEmpty())
    {
      int tabletNumber = StrToInt(DefectListStringGrid->Cells[0][DefectListStringGrid->Row]);

      if(tabletNumber)
      {
        int DefectIndex = DefectListStringGrid->Row - 1;

        if(prevDefectTabletNumber)
        {
          TTntPanel *prevResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(prevDefectTabletNumber));

          if(prevResultPanel)
          {
            prevResultPanel->Color = 0x00313131;
          }
        }

        ReleaseComponent();
        MakeResultComponents(tabletNumber);
        
        TTntPanel *ResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(tabletNumber));
        if(ResultPanel)
        {
          ResultPanel->Color = clRed;

          prevDefectTabletNumber = tabletNumber;
        }
      }
    }
  }
}
//---------------------------------------------------------------------------


void __fastcall TPreviewInspectionForm::UpListShiftPanelMouseDown(
      TObject *Sender, TMouseButton Button, TShiftState Shift, int X,
      int Y)
{
  if(!IsStringGridMouseDown)
  {
    if(DefectListStringGrid->Row > 1)
    {
      DefectListStringGrid->Row--;
    }
    IsStringGridMouseDown = true;
    LastStringGridMouseDownTime = GetTickCount();
  }
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::DownListShiftPanelMouseDown(
      TObject *Sender, TMouseButton Button, TShiftState Shift, int X,
      int Y)
{
  if(!IsStringGridMouseDown)
  {
    if(DefectListStringGrid->Row < DefectListStringGrid->RowCount - 1)
    {
      DefectListStringGrid->Row++;
    }
    IsStringGridMouseDown = true;
    LastStringGridMouseDownTime = GetTickCount();
  }
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::UpListShiftPanelMouseUp(
      TObject *Sender, TMouseButton Button, TShiftState Shift, int X,
      int Y)
{
  IsStringGridMouseDown = false;
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::DownListShiftPanelMouseUp(
      TObject *Sender, TMouseButton Button, TShiftState Shift, int X,
      int Y)
{
  IsStringGridMouseDown = false;
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::UpListShiftPanelMouseMove(
      TObject *Sender, TShiftState Shift, int X, int Y)
{
  if(IsStringGridMouseDown)
  {
    unsigned int currentTime = GetTickCount();

    if(currentTime - LastStringGridMouseDownTime > 200)
    {
      if(DefectListStringGrid->Row > 1)
      {
        DefectListStringGrid->Row--;
      }

      LastStringGridMouseDownTime = GetTickCount();
    }
  }
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::DownListShiftPanelMouseMove(
      TObject *Sender, TShiftState Shift, int X, int Y)
{
  if(IsStringGridMouseDown)
  {
    unsigned int currentTime = GetTickCount();

    if(currentTime - LastStringGridMouseDownTime > 200)
    {
      if(DefectListStringGrid->Row < DefectListStringGrid->RowCount - 1)
      {
        DefectListStringGrid->Row++;
      }

      LastStringGridMouseDownTime = GetTickCount();
    }
  }
}
//---------------------------------------------------------------------------

bool __fastcall TPreviewInspectionForm::DefectImageLoad(int dataIndex, int globalCameraIndex)
{
  bool bReturn = true;
  AnsiString DefectImageFileName;
  AnsiString BitmapName;
  DefectImageFileName = GetDefectImageContainerFileName(dataIndex, ProductData.ProductName, PreviewLOTName);

  if (FileExists(DefectImageFileName))
  {
    Graphics::TBitmap *img1;
    img1 = new Graphics::TBitmap();

    BitmapName = "Image" + IntToStr(dataIndex + 1) + ".fbm";
    if (!ReadSetupData(&TabletSetupData))
    {
      MessageDlgFA(DEFECTINFOFORM_MSG_01, mtConfirmation, TMsgDlgButtons() << mbOK);
      return false;
    }

    if(!ExtractImageFromContainer(img1, DefectImageFileName, BitmapName, TabletSetupData.ImageOffSetSW[globalCameraIndex - 1], TabletSetupData.referenceImageForOffset[globalCameraIndex - 1], ProductData.SubSamplingMode))
    {
      bReturn = false;
    }
    else
    {
      int ImageWidth = img1->Width;
      int ImageHeight = img1->Height;

      if(globalCameraIndex != SD1_3D_FRONT_FACE_CAMERA_INDEX && globalCameraIndex != SD2_3D_FRONT_FACE_CAMERA_INDEX)
      {
        for (int y = 0; y < ImageHeight; y++)
        {
          Byte *ptr = (Byte*)img1->ScanLine[y];
          for (int x = 0; x < ImageWidth; x++)
          {
            int tempAddress = ImageWidth * y + x;

            BayerImage[tempAddress * 3 + 0] = ptr[3 * x + 0];
            BayerImage[tempAddress * 3 + 1] = ptr[3 * x + 1];
            BayerImage[tempAddress * 3 + 2] = ptr[3 * x + 2];
          }
        }
      }
      else
      {
        for (int y = 0; y < ImageHeight; y++)
        {
          Byte *ptr = (Byte*)img1->ScanLine[y];
          for (int x = 0; x < ImageWidth; x++)
          {
            ThreeD_Data[ImageWidth * y + x] = ptr[x];
          }
        }
      }
    }

    //ResultImage1->Picture->Bitmap->Assign(img1);
    //ResultImage1->Refresh();

    delete img1;
  }
  else
  {
    bReturn = false;
  }

  return bReturn;
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::FormActivate(TObject *Sender)
{
  SetScreenPosition(this);
  
  UpListShiftPanel->Height = ListControlPanel->Height / 2;
  
  WaitingPanel->Caption = MAINFORM_MSG_13;

  WaitingPanel->Visible = true;
  this->Enabled = false;

  Application->ProcessMessages();

  if (!ReadSetupData(&TabletSetupData))
  {
    MessageDlgFA(DEFECTINFOFORM_MSG_01, mtConfirmation, TMsgDlgButtons() << mbOK);
  }

  if (!ReadStudyData(&TabletStudyData))
  {
    MessageDlgFA(DEFECTINFOFORM_MSG_02, mtConfirmation, TMsgDlgButtons() << mbOK);
  }

  if (!CPBSetupInfo.InspectionSetupDataValid)
  {
    setPosSetupData(&TabletSetupData);
  }

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

  SideFaceSetUpDataTransForm_For_PCSIM(tempSideData);

  this->Enabled = true;
  WaitingPanel->Visible = false;
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::RemoveImageComponent(int unusedAll)
{
  TTntPanel *madeResultPanel;
  TTntLabel *madeCameraNumberLabel;
  TTntLabel *madeTabletNumberLabel;
  TTntLabel *madeInspectionResultLabel;
  TTntImage *madeResultImage;
  TShape *madeShape;

  int startIndex = (currentImageIndex - MAX_DEFAULT_RESULT_VIEW_COUNT);
  int endIndex = ((currentImageIndex - 1) / MAX_DEFAULT_RESULT_VIEW_COUNT) * MAX_DEFAULT_RESULT_VIEW_COUNT;

  if(unusedAll)
  {
    for(int targetIndex = startIndex; targetIndex <= endIndex; targetIndex++)
    {
      if(targetIndex >= 1 && targetIndex <= currentImageIndex)
      {
        if(targetIndex > DESIGNED_IMAGE_COMPONENTS_COUNT)
        {
          madeCameraNumberLabel = (TTntLabel *)FindComponent("CameraNumberLabel" + IntToStr(targetIndex));
          if(madeCameraNumberLabel) delete madeCameraNumberLabel;

          madeTabletNumberLabel = (TTntLabel *)FindComponent("TabletNumberLabel" + IntToStr(targetIndex));
          if(madeTabletNumberLabel) delete madeTabletNumberLabel;

          madeInspectionResultLabel = (TTntLabel *)FindComponent("InspectionResultLabel" + IntToStr(targetIndex));
          if(madeInspectionResultLabel) delete madeInspectionResultLabel;

          madeResultImage = (TTntImage *)FindComponent("ResultImage" + IntToStr(targetIndex));
          if(madeResultImage) delete madeResultImage;

          madeShape = (TShape *)FindComponent("InspectionResultShape" + IntToStr(targetIndex));
          if(madeShape) delete madeShape;

          madeResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(targetIndex));
          if(madeResultPanel) delete madeResultPanel;
        }
        else
        {
          madeResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(targetIndex));
          if(madeResultPanel) madeResultPanel->Visible = false;
        }
      }
    }
  }
  else
  {
    int targetIndex = (currentImageIndex - MAX_DEFAULT_RESULT_VIEW_COUNT);

    if(targetIndex >= 1 && targetIndex <= currentImageIndex)
    {
      if(targetIndex > DESIGNED_IMAGE_COMPONENTS_COUNT)
      {
        madeCameraNumberLabel = (TTntLabel *)FindComponent("CameraNumberLabel" + IntToStr(targetIndex));
        if(madeCameraNumberLabel) delete madeCameraNumberLabel;

        madeTabletNumberLabel = (TTntLabel *)FindComponent("TabletNumberLabel" + IntToStr(targetIndex));
        if(madeTabletNumberLabel) delete madeTabletNumberLabel;

        madeInspectionResultLabel = (TTntLabel *)FindComponent("InspectionResultLabel" + IntToStr(targetIndex));
        if(madeInspectionResultLabel) delete madeInspectionResultLabel;

        madeResultImage = (TTntImage *)FindComponent("ResultImage" + IntToStr(targetIndex));
        if(madeResultImage) delete madeResultImage;

        madeShape = (TShape *)FindComponent("InspectionResultShape" + IntToStr(targetIndex));
        if(madeShape) delete madeShape;

        madeResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(targetIndex));
        if(madeResultPanel) delete madeResultPanel;
      }
      else
      {
        madeResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(targetIndex));
        if(madeResultPanel) madeResultPanel->Visible = false;
      }
    }
  }

}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::SetComponentQueue(void)
{
  for(int ComponentIndex = DESIGNED_IMAGE_COMPONENTS_COUNT + 1; ComponentIndex <= currentImageIndex; ComponentIndex++)
  {
    TTntPanel *madeResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(ComponentIndex));

    if(madeResultPanel)
    {
      ComponentTabletNumber[ComponentQueueEndIndex] = ComponentIndex;
      ComponentQueueEndIndex = (ComponentQueueEndIndex + 1) & MAKE_COMPONENT_QUEUE_MASK;
    }
  }
}
//---------------------------------------------------------------------------
void __fastcall TPreviewInspectionForm::ReleaseComponent(void)
{
  TTntPanel *madeResultPanel;
  TTntLabel *madeCameraNumberLabel;
  TTntLabel *madeTabletNumberLabel;
  TTntLabel *madeInspectionResultLabel;
  TTntImage *madeResultImage;
  TShape *madeShape;

  int ReleaseCount = 0;
  
  while(1)
  {
    if(ComponentQueueStartIndex != ComponentQueueEndIndex)
    {
      int componentIndex = ComponentTabletNumber[ComponentQueueStartIndex];

      madeCameraNumberLabel = (TTntLabel *)FindComponent("CameraNumberLabel" + IntToStr(componentIndex));
      if(madeCameraNumberLabel) delete madeCameraNumberLabel;

      madeTabletNumberLabel = (TTntLabel *)FindComponent("TabletNumberLabel" + IntToStr(componentIndex));
      if(madeTabletNumberLabel) delete madeTabletNumberLabel;

      madeInspectionResultLabel = (TTntLabel *)FindComponent("InspectionResultLabel" + IntToStr(componentIndex));
      if(madeInspectionResultLabel) delete madeInspectionResultLabel;

      madeResultImage = (TTntImage *)FindComponent("ResultImage" + IntToStr(componentIndex));
      if(madeResultImage) delete madeResultImage;

      madeShape = (TShape *)FindComponent("InspectionResultShape" + IntToStr(componentIndex));
      if(madeShape) delete madeShape;

      madeResultPanel = (TTntPanel *)FindComponent("ProcessingResultPanel" + IntToStr(componentIndex));
      if(madeResultPanel) delete madeResultPanel;

      ComponentQueueStartIndex = (ComponentQueueStartIndex + 1) & MAKE_COMPONENT_QUEUE_MASK;

      ReleaseCount++;
    }
    else
    {
      break;
    }
  }

  if(ReleaseCount != 8)
  {
    int k = 0;
  }
}
//---------------------------------------------------------------------------

void __fastcall TPreviewInspectionForm::GetDefaultString()
{
  PreviewInspectionStartBtn->Caption = PREVIEWINSPECTIN_FORM_TEXT_01;
  PreviewInspectionStopBtn->Caption = PREVIEWINSPECTIN_FORM_TEXT_02;
  InspectionImageSettingGroupBox->Caption = PREVIEWINSPECTIN_FORM_TEXT_03;
  ImageSelectPanel1->Caption = PREVIEWINSPECTIN_FORM_TEXT_04;
  ImageSelectPanel2->Caption = PREVIEWINSPECTIN_FORM_TEXT_05;
  InspectionLOTSettingGroupBox->Caption = PREVIEWINSPECTIN_FORM_TEXT_06;
  Label1->Caption = PREVIEWINSPECTIN_FORM_TEXT_07;
  Label2->Caption = PREVIEWINSPECTIN_FORM_TEXT_08;
  CameraSettingGroupBox->Caption = PREVIEWINSPECTIN_FORM_TEXT_09;
  CloseBtn->Caption = PREVIEWINSPECTIN_FORM_TEXT_10;
}
//---------------------------------------------------------------------------
