/*!\file convolutions.c
 *
 * \brief filtres de convolution adaptés à SDL2
 * \author Farès BELHADJ, amsi@ai.univ-paris8.fr
 * \date February 13 2014
 */

//AJOUTEZ VOS #include ici

/*!\brief réalise \a n fois un simple filtre de flou sur l'image
 * décrite dans \a img. 
 *
 * Le flou réalisé ici est de masque statique 3x3 contenant que des
 * 1. Il est à usage pédagogique.
 *
 * \param img est la surface SDL décrivant l'image, elle doît être 4 bytes par pixel.
 * \param n est le nombre d'itérations de flou.
 */
void convolutionSimpleBlur(SDL_Surface * img, int n) {
  int i, j, k, l, y, x, in;
  Uint32 * ppixels = img->pixels, * tpixels = NULL, mr, mg, mb;
  Uint8 r, g, b;
  assert(img->format->BytesPerPixel == 4);
  tpixels = malloc(img->w * img->h * sizeof * tpixels);
  assert(tpixels);
  while(n-- > 0) {
    for(i = 0; i < img->h; i++) {
      for(j = 0; j < img->w; j++) {
	for(in = mr = mg = mb = 0, k = -1; k <= 1; k++) {
	  for(l = -1; l <= 1; l++) {
	    y = i + k;
	    x = j + l;
	    if(y >= 0 && x >= 0 && y < img->h && x < img->w) {
	      SDL_GetRGB(ppixels[(y * img->w + x)], img->format, &r, &g, &b);
	      mr += r;
	      mg += g;
	      mb += b;
	      in++;
	    }
	  }
	}
	tpixels[(i * img->w + j)] = SDL_MapRGB(img->format, mr / in, mg / in, mb / in);
      }
    }
    memcpy(ppixels, tpixels, img->w * img->h * sizeof * tpixels);
  }
  free(tpixels);
}

