#include "pcfx.h"
#include "rainbow.h"
#include "king.h"
#include "interrupt.h"

#include "jpegdecoder.h"

// These coefficient lengths + data tables are broken and wrong :(

  static const uint8 dc_luminance[] =
    { 0, 0, 0, 7, 1, 0, 1, 2, 0, 16, 0, 0, 0, 0, 0, 0,
      0x00, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x01,
      0x08, 0x09, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14,
      0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C,
      0x1D, 0x1E, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00 
    };

  static const uint8 ac_luminance[] =
    { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d,

      0x01, 0x02, 0x03, 0x04, 0x11, 0x05, 0x12, 0x21, 
      0x00, 0x06, 0x31, 0x41, 0x51, 0x13, 0x22, 0x61, 
      0x07, 0x71, 0x09, 0x19, 0x29, 0x39, 0x49, 0x59,
      0x69, 0x79, 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 
      0xE9, 0xF9, 0x08, 0x14, 0x15, 0x16, 0x17, 0x18,
      0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x32, 0x33, 
      0x34, 0x35, 0x36, 0x37, 0x38, 0x42, 0x43, 0x44,
      0x45, 0x46, 0x47, 0x48, 0x52, 0x53, 0x54, 0x55, 
      0x56, 0x57, 0x58, 0x62, 0x63, 0x64, 0x65, 0x66,
      0x67, 0x68, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 
      0x78, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
      0x88, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 
      0x98, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
      0xA8, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 
      0xB8, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
      0xC8, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 
      0xD8, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 
      0xE8, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 
      0xF8, 0x10
    };

static const uint8 dc_chrominance[] =
    { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
      0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

static const uint8 ac_chrominance[] =
{ 
  0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77,
  0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  0xf9, 0xfa 
};


static uint8 DecodeBuffer[2][0x2000 * 4];
static int DecodeFormat[2]; // The format each buffer is in(0 = palettized 8-bit, 1 = YUV)
static uint8 QuantBuffer[2][64];

static uint32 DecodeBufferWhichRead;

static int32 RasterReadPos;
static uint32 BlockCount;
static uint16 Control;
static uint16 Meow, Meow2, Meow3, Meow4;

static uint32 SideScroll;

// RAINBOW base I/O port address: 0x200

#define REGSETBOFW(_reg, _data, _wb) { (_reg) &= ~(0xFF << ((_wb) * 8)); (_reg) |= (_data) << ((_wb) * 8); }
#define REGSETBOFH REGSETBOFW

// Endoku 1st, 16, 3, 80, 00, 00, 00
// Into train 01 80
void RAINBOW_Write8(uint32 A, uint8 V)
{
 //printf("RAINBOW Wr8: %08x %04x\n", A, V);
 switch(A & 0x1C)
 {
  case 0x00: REGSETBOFW(SideScroll, V, A & 0x3); break;
  case 0x04: REGSETBOFH(Control, V, A & 0x3); break;
  case 0x08: REGSETBOFH(Meow, V, A & 0x3); break;
  case 0x0C: REGSETBOFH(Meow2, V, A & 0x3); break;
  case 0x10: REGSETBOFH(Meow3, V, A & 0x3); break;
  case 0x14: REGSETBOFH(Meow4, V, A & 0x3); break;
 }
 //MDFN_DispMessage((UTF8*)"%08x %04x %04x %04x %04x %04x", SideScroll, Control, Meow, Meow2, Meow3, Meow4);
}
void RAINBOW_Write16(uint32 A, uint16 V)
{
 int msh = A & 0x2;

 switch(A & 0x1C)
 {
  case 0x00: REGSETHW(SideScroll, V, msh); break; // Side scroll?
  case 0x04: REGSETHW(Control, V, msh); break; // Control?
  case 0x08: REGSETHW(Meow, V, msh); break; // ??
  case 0x0C: REGSETHW(Meow2, V, msh); break; // ??
  case 0x10: REGSETHW(Meow3, V, msh); break; // ??
  case 0x14: REGSETHW(Meow4, V, msh); break; // ??
 }
 //MDFN_DispMessage((UTF8*)"%08x %04x %04x %04x %04x %04x", SideScroll, Control, Meow, Meow2, Meow3, Meow4);
}

void RAINBOW_Write32(uint32 A, uint32 V)
{
 RAINBOW_Write16(A, V & 0xFFFF);
 RAINBOW_Write16(A | 2, V >> 16);
}

void RAINBOW_TransferStart(uint32 blocks)
{
 DecodeBufferWhichRead = 0;
 RasterReadPos = 0;
 BlockCount = blocks;
}

int RAINBOW_FetchRaster(uint8 *ptr)
{
 if(!RasterReadPos)
 {
  if(BlockCount) // Yay, decode the block!
  {
   uint8 block_type;
   int32 block_size;
   unsigned int plt_shift;
   unsigned int crl_mask;

   KING_RB_Fetch(); // Should be 0xFF
   block_type = KING_RB_Fetch();
   block_size = KING_RB_Fetch() << 8;
   block_size |= KING_RB_Fetch();
   block_size -= 2;
   //printf("Type: %02x, %d\n", block_type, block_size);

   switch(block_type)
   {
    default:
    case 0xF0: plt_shift = 4; crl_mask = 0xF; break; // 16 color
    case 0xF1: plt_shift = 3; crl_mask = 0x7; break; // 32 color
    case 0xF2: plt_shift = 2; crl_mask = 0x3; break; // 64 color
    case 0xF3: plt_shift = 1; crl_mask = 0x1; break; // 128 color
   }

   if(block_type == 0xf8 || block_type == 0xff)
    DecodeFormat[DecodeBufferWhichRead] = 1;
   else
    DecodeFormat[DecodeBufferWhichRead] = 0;

   int x = 0;

   if(block_type == 0xF8 || block_type == 0xFF)
   {
    uint8 FancyBuffer[block_size];
    int32 BS = block_size;

    while(block_size > 0)
    {
     uint8 data = KING_RB_Fetch();
     block_size--;

     FancyBuffer[x++] = data;
    }

    #ifdef MOO
    jpeg_decoder *sexy_decoder = new jpeg_decoder();

    if(block_type == 0xFF)
    {
     memcpy(QuantBuffer[0], FancyBuffer, 64);
     memcpy(QuantBuffer[1], FancyBuffer + 64, 64);
     sexy_decoder->set_in_buffer(FancyBuffer + 128, BS - 128);
    }
    else
    {
     sexy_decoder->set_in_buffer(FancyBuffer + 4, BS - 4);
    }
    sexy_decoder->set_huffman(0, dc_luminance);
    sexy_decoder->set_huffman(1, ac_luminance);
    sexy_decoder->set_huffman(2, dc_chrominance);
    sexy_decoder->set_huffman(3, ac_chrominance);

    sexy_decoder->set_quant(0, QuantBuffer[0]);
    sexy_decoder->set_quant(1, QuantBuffer[1]);
    
    sexy_decoder->set_sof(256, 16, 2, 2, 0, 1, 1, 1, 1, 1, 1);
    sexy_decoder->set_sos(0, 1, 2, 3, 2, 3);
    sexy_decoder->begin();

    for(int y = 0; y < 16; y++)
    {
     uint32 line_len;
     void *slo;

     //sexy_decoder->decode(&slo, &line_len);
     //memcpy(&DecodeBuffer[DecodeBufferWhichRead][y * 256 * 4], slo, 256 * 4);
    }
    delete sexy_decoder;
    #endif
   }
   else while(block_size > 0)
   {
    uint8 boot = KING_RB_Fetch();
    block_size--;
    unsigned int rle_count;

    if(boot == 0xFF)
    {
     KING_RB_Fetch();
     block_size--;
    }

    if(!(boot & crl_mask)) // Expand mode?
    {
     rle_count = KING_RB_Fetch();
     block_size--;
     if(rle_count == 0xFF) 
     {
      KING_RB_Fetch();
      block_size--;
     }
     rle_count++;
    }
    else
     rle_count = boot & crl_mask;

    //if(BlockCount == 15)
    // printf("%d %d\n", BlockCount, rle_count);
    for(int i = 0; i < rle_count; i++)
    {
     if(x >= 0x2000) 
     {
      //puts("Oops");
      break; // Don't overflow our decode buffer!
     }
     DecodeBuffer[DecodeBufferWhichRead][x] = (boot >> plt_shift);
     x++;
    }
   }
   //printf("Meow: %d\n", x);
   for(int i = 0; i < 8 + block_size; i++)
    KING_RB_Fetch();
   BlockCount--;
   if(!BlockCount)
   {
    //if(Meow & 0x80)
    {
     //PCFXIRQ_Assert(8, TRUE);
     //puts("RAINBOW End");
    }
   }
  }
  else
  {
   memset(DecodeBuffer[DecodeBufferWhichRead], 0, 0x2000);
  }
  DecodeBufferWhichRead ^= 1;
 }
 int ret = DecodeFormat[DecodeBufferWhichRead];

 if(ptr)
 {
  if(DecodeFormat[DecodeBufferWhichRead] == 1)
  {
   memcpy(ptr, &DecodeBuffer[DecodeBufferWhichRead][RasterReadPos * 256 * 4], 256 * 4);
   //for(int x = 0; x < 1024; x++) ((uint8 *)ptr)[x] = 20; //rand();
   //puts("OK");
   //for(int x = 0; x < 256 * 4; x++) ptr[x] = rand();
  }
  else
  {
   if(Control & 0x2)
   {
    uint32 tmpss = SideScroll & 0xFF;

    memcpy(ptr, &DecodeBuffer[DecodeBufferWhichRead][RasterReadPos * 256] + tmpss, 256 - tmpss);
    memcpy(ptr + 256 - tmpss, &DecodeBuffer[DecodeBufferWhichRead][RasterReadPos * 256], tmpss);
   }
   else
   {
    uint32 tmpss = SideScroll;
    uint8 *out_ptr = ptr;
    uint8 *in_ptr = &DecodeBuffer[DecodeBufferWhichRead][RasterReadPos * 256];

    for(int x = 0; x < 256; x++)
    {
     if(tmpss < 256)
      out_ptr[x] = in_ptr[tmpss];
     else
      out_ptr[x] = 0;
     tmpss++;
    }
   }
  }
 }
 RasterReadPos = (RasterReadPos + 1) % 16;

 return(ret);
}

int RAINBOW_StateAction(StateMem *sm, int load, int data_only)
{
 SFORMAT StateRegs[] =
 {
   SFVAR(SideScroll),
   SFVAR(Control),
   SFVAR(RasterReadPos),
   SFVAR(DecodeBufferWhichRead),
   SFEND
 };

 int ret = MDFNSS_StateAction(sm, load, data_only, StateRegs, "RBOW");

 if(load)
 {
  RasterReadPos &= 0xF;
 }
 return(ret);
}

