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


//<file>
//
//
// Name :       hgraster.C
//
// Purpose :    Implementation of class HgRaster
//
// Created :    12 Apr 94    Peter Pichler
// Modified :   10 Nov 94    Bernhard Marschall
//
//
// Description:
//
//</file>


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

#include "hgraster.h"
#include "hgrastercb.h"
#include "rimage.h"
#include "gifimage.h"
#include "jpegimage.h"
#include "pngimage.h"
#include "tiffimage.h"

#include <InterViews/bitmap.h>
#include <InterViews/raster.h>
#include <IV-X11/xraster.h>


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

int HgRaster::load(const char* filename,
                   Raster*& raster, Bitmap*& bitmap,
                   HgRasterCallback* callback,
                   boolean dither)
{
  // return 0 on failure, 1 otherwise
  raster = nil;
  bitmap = nil;
   
  FILE* fp = fopen(filename, "r");
  if (!fp) {
    cerr << "HgRaster: cannot open file \"" << filename << "\"" << endl;
    return 0;
  }

  // identify file format
  char buf[20];
  if (fread(buf, 20, 1, fp) < 1) {
    fclose(fp);
    return 0;
  }
  rewind(fp);

  RasterImage* rimage = nil;

  int ret = 0;

  GraphicFormat format = identifyGraphicFormat(buf);
  switch (format) {
    case GF_Unknown:
      if (callback)
        callback->error("HgRaster: Error: Unknown graphic file format");
      break;

    case GF_PPM:
      if (callback)
        callback->error("HgRaster: Sorry, PPM not implemented yet");
      break;

    case GF_PAC:
      if (callback)
        callback->error("HgRaster: Sorry, PAC not implemented yet");
      break;

    case GF_Bitmap:
      if (bitmap = Bitmap::open(filename))
        ret = 1;
      break;

    case GF_GIF:
      rimage = new GifImage(fp, filename, raster, callback, dither);
      break;

    case GF_JPEG:
      rimage = new JpegImage(fp, filename, raster, callback, dither);
      break;

    case GF_TIFF:
      rimage = new TiffImage(fp, filename, raster, callback, dither);
      break;

    case GF_PNG:
      rimage = new PngImage(fp, filename, raster, callback, dither);
      break;
  }

  if (rimage) {
    rimage->finishDecode();
    // when writing directly to Raster's data pointer, we have to
    // modify the Raster explicitly!
    if (raster)
      raster->modified();
    delete rimage;
    ret = 1;
  }

  fclose(fp);

  return ret;
}
