/* Written by Dan Brown, Cornell University, 1996 
 * image.c */

#include 
#include "glimage.h"
#include "image.h"

int load_image(char *filename, int *width, int *height,
	       unsigned char **pixels)
{
  IMAGE *image;
  unsigned short *rbuf,*gbuf,*bbuf;
  unsigned char *p;
  int x,y;
  unsigned short *r,*g,*b;
   
  image = iopen(filename,"r");
  if (!image)
    return 0;
  
  /* print a little info about the image */
  printf("Image x and y size in pixels: %d %d\n",image->xsize,image->ysize);
  printf("Image zsize in channels: %d\n",image->zsize);
  printf("Image pixel min and max: %d %d\n",image->min,image->max);

  if (image->zsize != 3)
    return 0;

  if (image->max > 255)
    return 0;
  
  /* allocate buffers for image data */
  rbuf = (unsigned short *) malloc(sizeof(unsigned short)*image->xsize);
  gbuf = (unsigned short *) malloc(sizeof(unsigned short)*image->xsize);
  bbuf = (unsigned short *) malloc(sizeof(unsigned short)*image->xsize);
  
  *pixels = (unsigned char *)malloc(image->xsize * image->ysize * 3);
  *width = image->xsize;
  *height = image->ysize;
  
  p = *pixels;
  
  for (y=0; yysize; y++)
  {
    getrow(image,rbuf,y,0);
    getrow(image,gbuf,y,1);
    getrow(image,bbuf,y,2);

    r = rbuf;
    g = gbuf;
    b = bbuf;
    
    for (x=0; xxsize; x++)
    {
      *(p++)=*(r++);
      *(p++)=*(g++);
      *(p++)=*(b++);
    }
  }

  free(rbuf);
 free(gbuf);
  free(bbuf);

  iclose(image);

  return 1;
}