/* Copyright (c) 2010 MJ Rutter 
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA  02110-1301, USA.
 */ 

#include <stdio.h>
#include <stdlib.h>

#include "bmp2eps.h"

/* PPM reader
 *
 * MJR 3/02
 */
void pnmadata(FILE *pnm,int n,unsigned char *data);

void ppmread(FILE *ppm, struct bitmap *image_out, int binary)
{
  int i,debug;

  unsigned int width,height,data_len;
  unsigned int maxval;
  unsigned char *image;
  unsigned int data[3];

  debug=image_out->flags&DEBUG_MASK;
  if (debug) fprintf(stderr,"PPM file detected\n");
  
  pnmheader(ppm,3,data);

  width=data[0];
  height=data[1];
  maxval=data[2];

  if(maxval>255){
    fprintf(stderr,"ppm file is not 24 bit, but has maxval=%d\n",data[2]);
    exit(1);
  }

  if(debug)fprintf(stderr,"Image width=%d, height=%d\n",width,height);

  /* Read the whole file */

  if (!(image=malloc(3*height*width))){
    fprintf(stderr,"Error in malloc\n");
    exit(1);
  }

  data_len=3*height*width;

  if (binary){
    i=fread(image,1,data_len,ppm);
    if (i!=data_len){
      fprintf(stderr,"Error reading file: %d bytes read, %d expected\n",
	      i,data_len);
      exit(1);
    }
  }
  else pnmadata(ppm,data_len,image);

  if (maxval<255)
    for(i=0;i<data_len;i++)
      image[i]=(unsigned char)((image[i]*255)/maxval);

  image_out->data=image;
  image_out->data_len=data_len;
  image_out->height=height;
  image_out->width=width;
  image_out->depth=24;
  image_out->type=BMP;
  image_out->colour=RGB;

}

