% ::::::::::::::::::::::::::::::::::::::::::::::::::::::: %
% Solution proposal to programming exercises week 7       %
%                                                         %
% INF2310, spring 2017                                    %
%                                                         %
% Ole-Johan Skrede, 18.02.2017                            %
% ::::::::::::::::::::::::::::::::::::::::::::::::::::::: %

function conv_im = convolution2d(in_im, filter_kernel)
  nbh_size_v = (size(filter_kernel)(1) - 1)/2;
  nbh_size_h = (size(filter_kernel)(2) - 1)/2;
  conv_im = zeros(size(in_im));
  [m,n] = size(in_im);
  new_val = 0;
  filter_val = 0;
  orig_im_val = 0;
  im_i = 0;
  im_j = 0;
  
  for conv_i = 1:m
    for conv_j = 1:n
      for filter_i = -nbh_size_v:nbh_size_v
        if conv_i - filter_i < 1
          im_i = conv_i + filter_i - 1;
        elseif conv_i - filter_i > m
          im_i = conv_i + filter_i + 1;
        else
          im_i = conv_i - filter_i;
        end
        for filter_j = -nbh_size_h:nbh_size_h
          if conv_j - filter_j < 1
            im_j = conv_j + filter_j - 1;
          elseif conv_j - filter_j > n
            im_j = conv_j + filter_j + 1;
          else
            im_j = conv_j - filter_j;
          end
          filter_val = filter_kernel(filter_i + nbh_size_v + 1,
                                     filter_j + nbh_size_h + 1);
          orig_im_val = double(in_im(im_i, im_j));
          new_val = new_val + filter_val * orig_im_val;
        end
      end
      conv_im(conv_i, conv_j) = new_val;
      new_val = 0;
    end
  end

end
