#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"
	   "addnoise: Add random noise into image\n\n"
	   "usage : addnoise [-t type] [-p prob] in out\n\n"
	   "\t-t type : Type of noise: 0=pepper & salt, 1=salt, 2=pepper, default 0\n"
	   "\t-p prob : Probability of noise per cent, default 20\n"
	   "\tin      : Input image\n"
	   "\tout     : Output image\n");
    return 0;
  }

  // main parameters
  int type = 0;
  int prob = 20;
  QString input("");
  QString output("");

  // ----- Feed the parameter -----
  int count = 1;
  int ob_param = 0; // parametre obligatoire
  while (count < argc) {
    if (strcmp(argv[count], "-t") == 0) {
      if (count + 1 >= argc) goto err;
      type = atoi(argv[count + 1]);
      if (type < 0 || type > 2) goto err;
      count = count + 2;
    }
    else
      if (strcmp(argv[count], "-p") == 0) {
	if (count + 1 >= argc) goto err;
	prob = atoi(argv[count + 1]);
	if (prob < 0 || prob > 100) goto err; 
	count = count + 2;
      }
      else {
	switch (ob_param) {
	  case 0: input = argv[count];
	  case 1: output = argv[count];
	}
	ob_param++;
	count++;
      }
  }

  if (ob_param != 2) goto err;


  // ----- Algorithm -----
  QImage img;
  if (img.load(input) == false) {
    printf("Cannot load image\n");
    return 1;
  }
  
  int maxX = img.width();
  int maxY = img.height();

  int x, y; 

  for (x = 0; x < maxX; x++) 
    for (y = 0; y < maxY; y++) 
      if ((float(rand()) / RAND_MAX * 100) < prob)  
	if ((type == 0 && rand() < RAND_MAX / 2) || type == 1) 
	  img.setPixel(x, y, qRgb(255, 255, 255));
	else
	  img.setPixel(x, y, qRgb(0, 0, 0));
	
  img.save(output, "BMP", 100);
}

