/** System include files **/

#include <stdio.h>
#include "image.h"

/** Local include files **/

/** Static functions, structures, and variables **/

/** Public function definitions **/

int main(int argc, char *argv[])
{
  GrayImage pgm;
  FloatImage pfm;
  int x, y, w, h;
  float min;
  float max, val;
  
  pfm = (FloatImage)imLoadF(IMAGE_FLOAT, stdin);
  if (!pfm) 
  {
    fprintf(stderr, "Usage: %s < foo.pfm > foo.pgm\n", argv[0]);
    exit(1);
  }
  w = imGetWidth(pfm);
  h = imGetHeight(pfm);
  pgm = (GrayImage)imNew(IMAGE_GRAY, w, h);
  min = max = imRef(pfm, 0, 0);
  for (y = 0; y < h; y++)
  {
    for (x = 0; x < w; x++)
    {
      val = imRef(pfm, x, y);
      if (val < min) min = val;
      if (val > max) max = val;
    }
  }

  if (argc == 1) 
  {
    for (y = 0; y < h; y++)
    {
      for (x = 0; x < w; x++)
      {
	val = imRef(pfm, x, y);
      imRef(pgm, x, y) = (unsigned char)(255*(val-min)/(max-min));
      }
    } 
  }
  else 
  {
    for (y = 0; y < h; y++)
    {
      for (x = 0; x < w; x++)
      {
	val = imRef(pfm, x, y);
	if (val < 0) val = 0;
	if (val > 255) val = 255;
	imRef(pgm, x, y) = (unsigned char)val;
      }
    } 
  }
  
  imSaveF(pgm, stdout);
  return(0);
}

/** Private function definitions **/
