


#include "image.h"
#include "convolve.h"



inline int in_range(int x, int l, int h)
{
  if (x < l)   return l;
  if (x > h)   return h;
  return x;
}


FloatImage convolveFloatWithFloat(FloatImage img, FloatImage h)
{
  int i_xmin, i_xmax, i_ymin, i_ymax;
  int h_xmin, h_xmax, h_ymin, h_ymax;
  int x, y, i, j;
  FloatImage out;


  if (img == (FloatImage) NULL  ||  h == (FloatImage) NULL) {
    return (FloatImage) NULL;
  }

  i_xmin = imGetXBase(img);
  i_xmax = imGetXMax(img);
  i_ymin = imGetYBase(img);
  i_ymax = imGetYMax(img);

  h_xmin = imGetXBase(h);
  h_xmax = imGetXMax(h);
  h_ymin = imGetYBase(h);
  h_ymax = imGetYMax(h);

  out = (FloatImage) imNewOffset(IMAGE_FLOAT,
                                 i_xmax - i_xmin + 1, i_ymax - i_ymin + 1,
                                 i_xmin, i_ymin);

  if (out == (FloatImage) NULL) {
    return (FloatImage) NULL;
  }


  for (y = i_ymin; y <= i_ymax; y++) {
    for (x = i_xmin; x <= i_xmax; x++) {
      float sum = 0.0;

      for (j = h_ymin; j <= h_ymax; j++) {
	for (i = h_xmin; i <= h_xmax; i++) {
	  int xx, yy;

	  xx = in_range(x + i, i_xmin, i_xmax);
	  yy = in_range(y + j, i_ymin, i_ymax);

	  sum += imRef(img, xx, yy) * imRef(h, i, j);
	}
      }

      imRef(out, x, y) = sum;
    }
  }

  return out;
}
