
#include "stdio.h"
#include "assert.h"
#include "windows.h"
#include "math.h"
#include "Shared.h"

//################################################### Mode3_ProcessLine
void Mode3_ProcessLine(TUSBItem_Line* USBItem)
{
  if(Blit==NULL)
  {
    int Size_nx = 59*32/2;
    int Size_ny = 576-3;
    Blit = new TBlit(Size_nx, Size_ny, "0.32 s");
  }

  int iFrame = _State.VSyncCnt&ImgMsk;

  AddToImgArr(USBItem, iFrame);

  int iLine = _iLine;

  iFrame = (iFrame-7)&ImgMsk;
  
  if(iLine-22>=0 && iLine-22<288)// && (iFrame&7)==2)
  {
    int dx = ((iFrame-1)&4)==0 ? +4 : -4;
    int dy = (iFrame&1)!=0 ? +1 : -1;
    TUSBItem_LineEx* Line0 = ImgArr[(iFrame+0 + 0)&ImgMsk].Img+iLine;
    TUSBItem_LineEx* Line1 = ImgArr[(iFrame+0 +dy)&ImgMsk].Img+iLine;
    TUSBItem_LineEx* Line2 = ImgArr[(iFrame+dx+ 0)&ImgMsk].Img+iLine;
    TUSBItem_LineEx* Line3 = ImgArr[(iFrame+dx+dy)&ImgMsk].Img+iLine;
    for(int iADC=0; iADC<2; iADC++)
    {
      int dADC = iADC*_Config.dADC2;
      InitLine(Line0, Line0, dADC, dADC);
      InitLine(Line0, Line1, dADC, dADC);
      InitLine(Line0, Line2, dADC, dADC);
      InitLine(Line0, Line3, dADC, dADC);
      for(int iSample=0; iSample<_nSample; iSample++)
      {

        int dxColor = _ImageOfs0+_ImageOfs+iSample*_nSub;
        uint16_t Phi0 = uint16_t(dxColor/1e6/_fADCMHz*fPAL*(1+_dPPM_PAL*1e-6)*65536);
        Phi0 += uint16_t(65536*_dphiColor_degree/360);

        // Chroma
        double U = 0;
        double V = 0;
        LineToUV(Line0, Line1, Line2, Line3, Phi0, iSample, &U, &V);

        for(int iSub=0; iSub<1; iSub++)
        {
          // Luma
          TUSBItem_LineEx* DotLine0 = iSub==0 ? Line0 : Line1;
          TUSBItem_LineEx* DotLine2 = iSub==0 ? Line2 : Line3;
          double Y = 0;
          LineToY(DotLine0, DotLine2, Phi0, iSample, U, V, &Y);
          DWORD RGB = YUV_to_RGB(Y-_State.RefBlank, U, V);
          int xx = (iSample*_nSub+DotLine0->xSub)/2;
          int yy = DotLine0->y;
          Blit->SetPixel(xx, yy+0, RGB);
          Blit->SetPixel(xx, yy+1, RGB);
        }
      }
    }
  }
  if(_iLine==0)
  {
    Blit->DoBlit();
    LPCSTR MaskFileName = "s:\\1\\%04ia.bmp";
    // Blit->SaveImg(MaskFileName);
  }
}
