/*!\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 filtre décrit par \a M sur l'image
 * décrite dans \a img. 
 *
 * \param img est la surface SDL décrivant l'image, elle doît être 4 bytes par pixel.
 * \param M la matrice de convolution
 * \param mW la largeur de la matrice de convolution
 * \param mH la hauteur de la matrice de convolution
 * \param n est le nombre d'itérations du filtre.
 */
void convolutionGeneric(SDL_Surface * img, float * M, int mW, int mH, int n) {
  int i, j, k, l, m, y, x;
  float p, mr, mg, mb;
  Uint32 * ppixels = img->pixels, * tpixels = NULL;
  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++) {
	p = 0.0; mr = mg = mb = 0;
	for(k = -(mH >> 1), m = 0; k <= (mH >> 1); k++) {
	  for(l = -(mW >> 1); l <= (mW >> 1); l++) {
	    x = j + l; y = i + k;
	    if(x >= 0 && y >= 0 && x <= img->w && y <= img->h) {
	      SDL_GetRGB(ppixels[(y * img->w + x)], img->format, &r, &g, &b);
	      mr += r * M[m];
	      mg += g * M[m];
	      mb += b * M[m];
	      p  += M[m];
	    }
	    m++;
	  }
	}
	mr = mr / p;
	mg = mg / p;
	mb = mb / p;
	mr = MIN(MAX(mr, 0), 255);
	mg = MIN(MAX(mg, 0), 255);
	mb = MIN(MAX(mb, 0), 255);
	tpixels[(i * img->w + j)] = SDL_MapRGB(img->format, (Uint8)mr, (Uint8)mg, (Uint8)mb);
      }
    }
    memcpy(ppixels, tpixels, img->w * img->h * sizeof * tpixels);
  }
  free(tpixels);
}

