%%
function out=tut7solution(filename)


%% Read it in

I=imread(filename);

if size(I,3)>1
    I=rgb2gray(I);
end
    
%clear
imshow(I);

S = size(I);

%% First canny
BW = edge(I, 'canny', 0.1, 1);

red = cat(3, ones(S), zeros(S), zeros(S));

imshow(I)
hold on
h = imshow(red);

set(h, 'AlphaData', BW);

%% Hough stuff
[H, T, R] = hough(BW);

peaks = houghpeaks(H, 10, 'Threshold', 0.1*max(H(:)));

lines = houghlines(BW, T, R, peaks);

%% Function drawlines
drawlines(I, lines);

%% Draw the lines on the image (borrowed from the "doc houghlines")
function drawlines(I, lines)
figure, imshow(I), hold on
max_len = 0;
for k = 1:length(lines)
    xy = [lines(k).point1; lines(k).point2];
    plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');
    
    % Plot beginnings and ends of lines
    plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');
    plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');
    
    % Determine the endpoints of the longest line segment
    len = norm(lines(k).point1 - lines(k).point2);
    if ( len > max_len)
        max_len = len;
        xy_long = xy;
    end
end

% highlight the longest line segment
plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','blue');




