#include "bmpdecoder.h"
#include "jpgdecoder.h"
#include <iostream>
#include <cmath>

using namespace std ;
using namespace Colosseum ;

int Usage (int argc, char *argv [])
{
   cerr << "Usage: " << (argc > 0 ? argv [0] : "JPGQUALITY")
        << " file1.bmp file2.jpg " << endl 
        << "square-of-differences differences max-difference" << endl ;
   return 1 ;
}

int main (int argc, char *argv [])
{
  if (argc != 3)
    return Usage (argc, argv) ;


  BitmapImage image1 ;
  BitmapImage image2 ;
  BmpDecoder decoder1 ;
  JpegDecoder decoder2 ;

  try
  {
    decoder1.readImageFile (argv [1], image1) ;
  }
  catch (exception &ee)
  {
    cerr << ee.what () << " " << argv [1] << endl ;
    return 1 ;
  }
  try
  {
    decoder2.readImageFile (argv [2], image2) ;
  }
  catch (exception &ee)
  {
    cerr << ee.what () << " " << argv [2] << endl ;
    return 1 ;
  }

  if (image1.getWidth () != image2.getWidth ()
      || image1.getHeight () != image2.getHeight ())
  {
    cerr << "Images do not have the same dimensions" << endl ;
    return 1 ;
  }

  unsigned int range = image1.getWidth () * image1.getHeight () ;
  double variance = 0.0 ;
  double deviation = 0.0 ;
  unsigned int maxvariance = 0 ;
  for (unsigned int ii = 0 ; ii < range ; ++ ii)
  {
    int difference ;
    int differencesum = 0 ;
    difference = image1 [ii].red - image2 [ii].red ;
    differencesum += difference * difference ;
    deviation += abs (difference) ;
    difference = image1 [ii].green - image2 [ii].green ;
    differencesum += difference * difference ;
    deviation += abs (difference) ;
    difference = image1 [ii].blue - image2 [ii].blue ;
    differencesum += difference * difference ;
    deviation += abs (difference) ;
    variance += differencesum ;
    if (differencesum > maxvariance)
      maxvariance = differencesum ;
  }
  variance /= range ;
  deviation /= range ;
  cout << variance << " " << deviation << " " << sqrt (maxvariance) << endl ;
  return 0 ;
}
