/* 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"

/* PGM reader
 *
 * MJR 3/02, 6/10
 */

void pnmadata(FILE *pnm,int n,unsigned char *data);

void pgmread(FILE *pgm, 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,"PGM file detected\n");

  pnmheader(pgm,3,data);
  
  if(data[2]==0){
    fprintf(stderr,"Error: pgm file with maxval=0\n");
    exit(1);
  }

  if(data[2]>255){
    fprintf(stderr,"Error: pgm file greater than 8 bit, with maxval=%d\n",
       data[2]);
    exit(1);
  }

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

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

  /* Read the whole file inefficiently */

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

  data_len=height*width;

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

  image_out->data=image;
  image_out->data_len=data_len;
  image_out->height=height;
  image_out->width=width;
  image_out->depth=8;
  image_out->type=BMP;
  image_out->colour=GREY;

  /* At this point maxval could be anything from 1 to 255.
   * Deal with the simple cases first */

  if (maxval==255){
    image_out->depth=8;
    return;
  }
  else if (maxval>15){
    for(i=0;i<height*width;i++)
      image[i]=(image[i]*255)/maxval;
    image_out->depth=8;
    return;
  }
  else if (maxval==15) image_out->depth=4;
  else if ((maxval<15)&&(maxval>3)){
    for(i=0;i<height*width;i++)
      image[i]=(image[i]*15)/maxval;
    image_out->depth=4;
  }
  else if (maxval==3) image_out->depth=2;
  else if ((maxval==2)){
    for(i=0;i<height*width;i++)
      image[i]=(image[i]*3)/2;
    image_out->depth=2;
  }
  else if (maxval==1) image_out->depth=1;

  /* Make use of existing compaction routine */

  image_out->pal_len=1<<image_out->depth;
  compact(image_out);
  image_out->pal_len=0;

}

