//<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 <stdio.h>

extern "C" {
#include "jpeg/jpeglib.h"
}
//#include "jpeg/cdjpeg.h"

#include <hyperg/utils/hgraster.h>

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

#include <InterViews/bitmap.h>
#include <InterViews/raster.h>
#include <InterViews/tiff.h>

// char HyperGHgRasterWhat[] = "@(#)[Hyper-G] [HG-LIB] HgRaster\t1.0 [Hyper-G Raster Library] [Peter Pichler, Bernhard Marschall]";

// **********************************************************
// externals
extern int GifLoad(FILE*, Raster*&, Bitmap*&,
                   RasterAction*, boolean);
extern int JpegLoad(FILE*, Raster*&, 
                    RasterAction*, boolean);
extern JSAMPLE transparent_red, transparent_green, transparent_blue;

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

int HgRaster::load(const char* filename,
                   Raster*& raster, Bitmap*& bitmap,
                   RasterAction* progress,
                   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;
  }

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

  if (!strncmp(buf, "P6", 2) || !strncmp(buf, "P5", 2)) {   // PPM
    cerr << "HgRaster: PPM not yet supported " << endl;
    return 0;
  }

  if (!strncmp(buf, "PICT", 4)) {   // PAC
    cerr << "HgRaster: PAC not yet supported " << endl;
    return 0;
  }

  if (!strncmp(buf, "GIF", 3)) {   // GIF
    return GifLoad(fp, raster, bitmap, progress, dither);
  }

  if ((unsigned char)buf[0] == 0xff && 
      (unsigned char)buf[1] == 0xd8 &&
      (unsigned char)buf[2] == 0xff) {   // JPEG
    return JpegLoad(fp, raster, progress, dither);
  }

  if (!strncmp(buf,"#define",7)) {   // X Bitmap (XBM)
    fclose(fp);
    if (bitmap = Bitmap::open(filename))
      return 1;
    else
      return 0;
  }

  else {   // TIFF
    fclose(fp);
    raster = nil;
    bitmap = nil;
    return TIFFRaster::load(filename, raster, bitmap, false, progress, dither);
  }
}
