function blurred = blur(M, ulr, ulc, lrr, lrc, span)
% blur(M,ulr,ulc,lrr,lrc,span) - Implement blurring effect in image region
%  M - an image matrix (R,G,B format)
%  ulr, ulc = coordinates of upper-left corner of rectangle (row, column)
%  lrr, lrc = coordinates of lower-right corner of rectangle (row,column)
%  span = radius of pixels to average over 
[ rows cols depth ] = size(M);
blurred = M;   % initialize output matrix to input matrix, whatever it is...
% Check for row/col out of bounds
if ulr - span < 0 | lrr + span > rows | ulc - span < 0 | lrc + span > cols...
        | ulr >= lrr | ulc >= lrc
    disp('Invalid rectangle coordinates -- image unchanged.');
elseif depth ~= 3
    disp('Invalid image matrix -- unchanged.');
else  % dimensions are acceptable - proceed with computation
    npixels = (2*span+1)^2;  % # pixels summed to get average
    %
    for row = ulr:lrr;       % for each row in the region
      for col = ulc:lrc;     % for each column in the region
         % initialize sums for average computation
         rsum = uint32(0);   % making these values uint32 makes
         gsum = uint32(0);   % the program run MUCH faster!
         bsum = uint32(0);
         % now compute the average value of each color around each pixel
         for pixr = row-span:row+span;
            for pixc = col-span:col+span;
                rsum = rsum + uint32(M(pixr,pixc,1));
                gsum = gsum + uint32(M(pixr,pixc,2));
                bsum = bsum + uint32(M(pixr,pixc,3));
            end
         end
         blurred(row,col,1) = rsum / npixels;
         blurred(row,col,2) = gsum / npixels;
         blurred(row,col,3) = bsum / npixels;
      end
    end
end

