/*
 * Equalize an image
 *
 * $Date$
 * $Revision$
 *
 */

#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <cmath>
#include <cassert>
#include <WImage.hh>

#if !(defined __WATCOMC__ && __WATCOMC__ < 1230)
using namespace std;
#endif

int
main (int argc, char *argv[])
{
  cout << "pgmequalize version " << WAVE_VERSION << " (c) 2001-2004 by Herbert"
#ifdef PFI
       << " (pfi support enabled)"
#endif
       << endl;

  char *infile;
  char *outfile;
  Image *image = NEW (StillImage ());
  int yoffs = 0;
  int xoffs = 0;
  int ysize = 0;
  int xsize = 0;

  if (argc < 3 && argc != 7)
    {
      cerr << "Usage: pgmequalize <infile> <outfile> "
           << "[<yoffs> <xoffs> <ysize> <xsize>]" 
           << endl;
      return 1;
    }

  infile = argv[1];
  outfile = argv[2];

  if (argc == 7)
    {
      if (sscanf (argv[3], "%d", &yoffs) != 1)
        {
          cerr << "Invalid yoffs: " << argv[3] << endl;
          return 1;
        }
      if (sscanf (argv[4], "%d", &xoffs) != 1)
        {
          cerr << "Invalid xoffs: " << argv[4] << endl;
          return 1;
        }
      if (sscanf (argv[5], "%d", &ysize) != 1)
        {
          cerr << "Invalid ysize: " << argv[5] << endl;
          return 1;
        }
      if (sscanf (argv[6], "%d", &xsize) != 1)
        {
          cerr << "Invalid xsize: " << argv[6] << endl;
          return 1;
        }
    }

  try
    {
      image->read (infile);
    }
  catch (const exception &error)
    {
      cerr << "Reading image: " << error.what () << endl;
      return 1;
    }

  image->histEqualization (yoffs, xoffs, ysize, xsize);

  try
    {
      image->write (outfile);
    }
  catch (const exception &error)
    {
      cerr << "Writing image: " << error.what () << endl;
      return 1;
    }

  DELETE (image);
  
  return 0;
}

