%im1 = im2double(imread('torre.bmp'));  % our first image
im1 = im2double(imread('butterfly.bmp'));  % our first image
[rows, cols, channels] = size(im1);

im2 = im2double(imread('butterfly.bmp')); % target image

figure(1);
imshow(im1);

figure(2);
imshow(im2);


% generate our downsampled target patch
patch = imresize(im2, 0.05, 'bilinear');

tx = 73;
ty = 73;

%patch = im1(tx:tx+20, ty:ty+20,:);


[prows, pcols, pchannels] = size(patch);

figure(3);
imshow(patch);

lowest_dist = 999999999999999;
lowest_dist_x = -1;
lowest_dist_y = -1;

fig1 = figure(1);
imshow(im1);
hold on;

for x = 2 : 1 : cols - pcols - 1
    for y = 2 : 1 : rows - prows - 1
        
%{
        imshow(im1);
        box(x, y, x + pcols - 1, y + prows - 1, 'r');
        drawnow;
%}      
        
        % compute L2 distance in RGB space
        % dist = 0;
        
        diff = abs(im1(y:y+prows-1, x:x+pcols-1,:) - patch);
        diff = diff .* diff;
        dist = sum(sum(sum(diff)));
        %{
        for i = 1 : 1 : pcols
            for j = 1 : 1 : prows
                diff_r = abs(im1(y + j - 1, x + i - 1, 1) - patch(j, i, 1));
                diff_g = abs(im1(y + j - 1, x + i - 1, 2) - patch(j, i, 2));
                diff_b = abs(im1(y + j - 1, x + i - 1, 3) - patch(j, i, 3));
                dist = dist + sqrt(diff_r * diff_r + diff_g * diff_g + diff_b * diff_b);
            end
        end
        %}
   
        % check to see if our current (x, y) is the closest
        if (dist < lowest_dist)
            lowest_dist = dist;
            lowest_dist_x = x;
            lowest_dist_y = y;
            fprintf('new lowest distance: %f at (%i, %i)\n', lowest_dist, lowest_dist_x, lowest_dist_y);
        elseif (dist == lowest_dist)
            fprintf('MULTIPLE BEST MATCHES\n');
        end
    end
    fprintf('x=%i ', x);
end

fprintf('\n');

hold off;
        
figure(1);
%box(lowest_dist_x, lowest_dist_y, lowest_dist_x + pcols - 1, lowest_dist_y + prows - 1, 'r');
hold on;
subimage(lowest_dist_x, lowest_dist_y, patch);
hold off;

        
