#include <iostream.h>
#include <qimage.h>
#include <qstring.h>
#include <qcolor.h>
#include <stdio.h> 

int main(int argc, char **argv) {
  
  // manual of the command
  if (argc == 1) {
  err:
    printf("-------------------------------------------------------\n"
	   "diffpn : Difference two image into two positive images\n\n"
	   "usage : diffpn A B O1 O2\n\n"
	   "\tA      : Input image A\n"
	   "\tB      : Input image B\n"	   
	   "\tO1     : Output positive image\n"
	   "\tO2     : Output negative image\n");
    return 0;
  }

  // main parameters
  QString inputA("");
  QString inputB("");
  QString output1("");
  QString output2("");

  // ----- Feed the parameter -----
  int count = 1;
  int ob_param = 0; // parametre obligatoire
  while (count < argc) {
    switch (ob_param) {
    case 0: inputA = argv[count];
    case 1: inputB = argv[count];	    
    case 2: output1 = argv[count];
    case 3: output2 = argv[count];     
    }
    ob_param++;
    count++;
  }
  
  if (ob_param != 4) goto err;


  // ----- Algorithm -----
  QImage inA, inB, out1, out2;
  if (inA.load(inputA) == false || inB.load(inputB) == false) {
    printf("Cannot load image\n");
    return 1;
  }


  if (!(inA.width() == inB.width() && inB.height() == inB.height())) {
    printf("Two input images must have the same size.\n");
    return 1;
  }
    

  int maxX = inA.width();
  int maxY = inA.height();

  out1 = QImage(maxX, maxY, 32);
  out2 = QImage(maxX, maxY, 32);

  int x, y; 

  QRgb color1, color2;
  int gray1, gray2;

  for (x = 0; x < maxX; x++) { 
    for (y = 0; y < maxY; y++) {
      color1 = inA.pixel(x, y);
      color2 = inB.pixel(x, y);
      gray1 = qGray(color1);
      gray2 = qGray(color2);
      
      if (gray1 > gray2) {
	out1.setPixel(x, y, qRgb(gray1 - gray2, gray1 - gray2, gray1 - gray2));
	out2.setPixel(x, y, qRgb(0, 0, 0));
      }
      else {
	out1.setPixel(x, y, qRgb(0, 0, 0));
	out2.setPixel(x, y, qRgb(gray2 - gray1, gray2 - gray1, gray2 - gray1));
      }
    }
  }


  out1.save(output1, "BMP", 100);
  out2.save(output2, "BMP", 100);
}

