/*
 * Diff two images
 *
 * $Date$
 * $Revision$
 *
 */

#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <WTools.hh>

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

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

  if (argc < 4 || argc > 5)
    {
      cerr << "Usage: pgmdiff <file1> <file2> <outfile> [magnify]" << endl;
      return 1;
    }
  Image *img1 = NEW (StillImage ());
  Image *img2 = NEW (StillImage ());
  coeff magnify = 1;

  if (argc > 4)
    {
      if (sscanf (argv[4], "%lf", &magnify) != 1)
        {
          cerr << "Invalid factor: " << argv[4] << endl;
          return 1;
        }
    }
  
  try 
    {
      img1->read (argv[1]);
    }
  catch (const exception &error)
    {
      cerr << "Error reading " << argv[1] << ": " << error.what () << endl;
      return 1;
    }
  
  try 
    {
      img2->read (argv[2]);
    }
  catch (const exception &error)
    {
      cerr << "Error reading " << argv[2] << ": " << error.what () << endl;
      return 1;
    }

  if (img1->size () != img2->size ())
    {
      cerr << "Error, image dimensions differ." << endl;
      return 1;
    }
  
  ImageComparison *comparison = NEW (ImageComparison (*img1, *img2));
  Image *out = comparison->difference (magnify);
  DELETE (comparison);
  
  try
    {
      out->write (argv[3], true);
    }
  catch (const exception &error)
    {
      cerr << "Error writing " << argv[3] << ": " << error.what () << endl;
      return 1;
    }
  
  return 0;
}
