function [ out ] = median_filter( im, neighborhoodSize )
% Create a function that: 
% ? realizes a median filter, 
% ? parameters of this function should be as follows: 
%     ? input1: image matrix, 
%     ? input2: neighborhood size (eg 3 in case of 3x3 neighborhood), 
%     ? output: the matrix of the filtered image, 
% ? it should work with grayscale images (check if this holds), 
% ? rough workaround: 
%     ? go through every pixel of the image (use padarray to create virtual cells), 
%     ? take the input2 x input2 sized neighborhood of it, 
%     ? vectorize this neighborhood (built-in reshape), 
%     ? sort the values (built-in sort), 
%     ? take the middle intensity as the new value of the processed pixel-location.

padding = (neighborhoodSize - 1)/2;
pad_image = padarray(im, [padding padding], 'symmetric');
out = zeros(size(im));

for k = 1:size(im,1) - 1
    for j = 1:size(im,2) - 1
        window = pad_image( k:k+neighborhoodSize-1, j:j+neighborhoodSize-1 );
        out(k,j) = median(window(:));
    end
end

out = uint8(out);

end

