#include "pnginputstream.h"
#include "crc32.h"

namespace Colosseum
{
bool PngInputStream::getNextChunk ()
{
  chunk_length = readChunkLength () ;

  readChunkData (chunk_length + sizeof (chunk_length), chunk_data) ;
  UBYTE4 filecrc = readCrc () ;
  Crc32 crc ;

  crc.update (reinterpret_cast<const char*>(chunk_data),
             static_cast<unsigned int>(chunk_length + sizeof (chunk_length))) ;
  UBYTE4 crcvalue = crc.value () ;
  if (filecrc != crcvalue)
    throw StreamError ("Invalid Chunk CRC") ;
  chunk_type [0] = *chunk_data ; ++ chunk_data ;
  chunk_type [1] = *chunk_data ; ++ chunk_data ;
  chunk_type [2] = *chunk_data ; ++ chunk_data ;
  chunk_type [3] = *chunk_data ; ++ chunk_data ;

  current_byte = chunk_data ;
  buffer_limit = &chunk_data [chunk_length] ;
  return true ;
}

void PngInputStream::fillBuffer ()
{
  if (! getNextChunk ())
    throw StreamError ("Premature End of File") ;
  if (memcmp (chunk_type, "IDAT", sizeof (chunk_type)) != 0)
    throw StreamError ("Missing IDAT Chunk") ;
  current_byte = chunk_data ;
  buffer_limit = &chunk_data [chunk_length] ;
  return ;
}


} // End Namespace Colosseum


