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

//################################################### Mode2_ProcessLine
void Mode2_ProcessLine(TUSBItem_Line* USBItem)
{
  if(Blit==NULL)
  {
    int Size_nx = _nSample*_nSub/2;
    int Size_ny = 576-3;
    Blit = new TBlit(Size_nx, Size_ny, "0.64 s");
  }

  int iFrame = _State.VSyncCnt&ImgMsk;

  AddToImgArr(USBItem, iFrame);

  int iLine = _iLine;

  iFrame = (iFrame-12)&ImgMsk;

  if(iLine-22>=0 && iLine-22<288 && (iFrame&4)==0)
  {
    TUSBItem_LineEx* Line0 = ImgArr[(iFrame+ 0 + 0*4)&ImgMsk].Img+iLine;
    TUSBItem_LineEx* Line1 = ImgArr[(iFrame+ 0 + 2*4)&ImgMsk].Img+iLine;
    TUSBItem_LineEx* Line2 = ImgArr[(iFrame+ 4 + 0*4)&ImgMsk].Img+iLine;
    TUSBItem_LineEx* Line3 = ImgArr[(iFrame+ 4 + 2*4)&ImgMsk].Img+iLine;
    if(1==2) // VC20
    {
      Line2 = ImgArr[(iFrame+ 0 - 4*4)&ImgMsk].Img+iLine; // -180°
      Line3 = ImgArr[(iFrame+ 0 - 2*4)&ImgMsk].Img+iLine; //  -90°
    }
    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);

        // Luma
        double Y = 0;
        LineToY(Line0, Line2, Phi0, iSample, U, V, &Y);

        int xx = (iSample*_nSub+Line0->xSub)/2;
        int yy = Line0->y;

        DWORD RGB = YUV_to_RGB(Y-_State.RefBlank, U, V);

        Blit->SetPixel(xx, yy, RGB);
      }
    }
  }

  if(iLine==0)
  {
    Blit->DoBlit();
    // Blit->SaveImg();
  }
}
