/*
 * Set one pixel in an image
 *
 * $Date$
 * $Revision$
 *
 */

#include <iostream>
#include <stdexcept>
#include <cstring>
#include <cstdio>
#include <Wave.hh>

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

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

  char *infile;
  char *outfile;
  Image *image = NEW (StillImage ());
  coeff value;
  int xpos, ypos;
  bool readonly = false;

  if (argc < 5 || argc > 6)
    {
      cerr << "Usage: pxmpixel <infile> <value> <xpos> <ypos> [<outfile>]"
           << endl 
           << "       Set <value> to \"?\" to only read and display the value"
           << endl;
      return 1;
    }

  infile = argv[1];
  if (strcmp (argv[2], "?") == 0)
    {
      readonly = true;
    }
  else if (sscanf (argv[2], "%lf", &value) != 1)
    {
      cerr << "Invalid value: " << argv[2] << endl;
      return 1;
    }
  if (sscanf (argv[3], "%d", &xpos) != 1 || xpos < 0)
    {
      cerr << "Invalid xpos: " << argv[3] << endl;
      return 1;
    }
  if (sscanf (argv[4], "%d", &ypos) != 1 || ypos < 0)
    {
      cerr << "Invalid ypos: " << argv[4] << endl;
      return 1;
    }
  if (argc == 6)
    {
      outfile = argv[5];
    }
  else
    {
      outfile = infile;
    }

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

  if (readonly)
    {
      cout << "Image " << infile << " at (" << xpos << ", " << ypos << "): " 
           << image->at (ypos, xpos) << endl;
    }
  else
    {
      cout << "Replacing value " << image->at (ypos, xpos) << " at (" 
           << xpos << ", " << ypos << ") by " << value << endl;

      image->to (ypos, xpos, value);

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

  DELETE (image);
  
  return 0;
}

