//<copyright>
//
// Copyright (c) 1995
// Institute for Information Processing and Computer Supported New Media (IICM),
// Graz University of Technology, Austria.
//
//</copyright>


//<file>
//
//
// Name :       rimage.C
//
// Purpose :    Implementation of class RasterImage
//
// Created :    04 Jan 95    Bernhard Marschall
// Modified :   04 Jan 95    Bernhard Marschall
// Modified :   03 Aug 95    Bernhard Marschall
//
//
// Description:
//
//</file>


#include <string.h>
#include <iostream.h>

#include "rimage.h"
#include "hgrastercb.h"

#include <IV-X11/xraster.h>
#include <hyperg/OS/memory.h>

// ************************************************************************

GraphicFormat identifyGraphicFormat(const char* buffer)
{
  if (!strncmp(buffer, "P6", 2) || !strncmp(buffer, "P5", 2))  // PPM
    return GF_PPM;

  if (!strncmp(buffer, "PICT", 4))  // PAC
    return GF_PAC;

  if (!strncmp(buffer, "GIF", 3))  // GIF
    return GF_GIF;

  if ((Byte) buffer[0] == 0xff && 
      (Byte) buffer[1] == 0xd8 &&
      (Byte) buffer[2] == 0xff)  // JPEG
    return GF_JPEG;

  if (buffer[0] == buffer[1] &&
      ((Byte) buffer[2] == 0x00 && (Byte) buffer[3] == 0x2a) ||
      ((Byte) buffer[3] == 0x00 && (Byte) buffer[2] == 0x2a))  // TIFF
    return GF_TIFF;

  if (!strncmp(buffer, "#define", 7))
    return GF_Bitmap;

  if (!strncmp(buffer, "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8))
    return GF_PNG;

  return GF_Unknown;
}

// ************************************************************************

RasterImage::RasterImage(FILE* fp, const char* fname, Raster*& raster,
                         HgRasterCallback* cb, boolean dither)
: raster_(raster)
{
  callback_ = cb;
  file_ = fp;
  filename_ = fname;
  dither_ = dither;
  decoded_ = 0;
  error_ = 0;
}

// ************************************************************************

RasterImage::~RasterImage()
{
}

// ************************************************************************

void RasterImage::finishDecode()
{
  setSize(100, 100);
}

// ************************************************************************

void RasterImage::setSize(int w, int h)
{
  // make raster to store image data
  raster_ = new Raster(w, h, dither_);
  Memory::zero((void*) data(), w*h*3);   // should be done by ivRaster itself - later!

  if (callback_) callback_->readHeader();
}

// ************************************************************************

const Byte* RasterImage::data() const
{
  if (raster_)
    return (const Byte*) raster_->data();
  else
    return nil;
}

const Byte* RasterImage::alpha() const
{
  if (raster_)
    return (const Byte*) raster_->alpha();
  else
    return nil;
}
