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

//################################################### Mode4_ProcessLine
void Mode4_ProcessLine(TUSBItem_Line* USBItem)
{
  if(Blit==NULL)
  {
    int Size_nx = 59*32/4;
    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-5)&ImgMsk;
  
  if(iLine-22>=0 && iLine-22<288 && (iFrame&5)==1)
  {
    TUSBItem_LineEx* Line0 = ImgArr[(iFrame+0+0)&ImgMsk].Img+iLine;
    TUSBItem_LineEx* Line1 = ImgArr[(iFrame+0+1)&ImgMsk].Img+iLine;
    TUSBItem_LineEx* Line2 = ImgArr[(iFrame+4+0)&ImgMsk].Img+iLine;
    TUSBItem_LineEx* Line3 = ImgArr[(iFrame+4+1)&ImgMsk].Img+iLine;
    InitLine(Line0, Line0);
    InitLine(Line0, Line1);
    InitLine(Line0, Line2);
    InitLine(Line0, Line3);
    
    // if(iLine==100) printf("%i ", iSub);
    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<2; 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)/4;
        int yy = DotLine0->y;
        Blit->SetPixel(xx, yy+0, RGB);
        Blit->SetPixel(xx, yy+1, RGB);
      }
    }
  }
  if(iLine==0 && (_State.VSyncCnt&0)==0)
  {
    Blit->DoBlit();
    // Blit->SaveImg();
  }
}
