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

//################################################### Mode5_ProcessLine
void Mode5_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.16 s");
  }

  int iFrame = _State.VSyncCnt&ImgMsk;

  AddToImgArr(USBItem, iFrame);

  int iLine = _iLine;

  iFrame = (iFrame-5)&ImgMsk;
  
  if(iLine-22>=0 && iLine-22<288 && (iFrame&1)==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;
    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);
      if(iLine==100 && 1==2)
      {
        printf("%5i - %i%i%i%i - %5i %5i %5i\n",
               iFrame,
               Line0->Odd, // 0 oder 1
               Line1->Odd, // +0 (keine Änderung zu Line0->Odd erlaubt)
               Line2->Odd, // +0
               Line3->Odd, // +0
               int8_t((Line2->Phi-Line0->Phi)/256),  // 128 +-32 (-> 180°)
               int8_t((Line3->Phi-Line1->Phi)/256),  // 128 +-32 (-> 180°)
               int8_t((Line1->Phi-Line0->Phi)/256)); //  64 +-32 (-> 90°)
      }
      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&1)==0)
  {
    Blit->DoBlit();
    // Blit->SaveImg();
  }
}
