function [ output_args ] = board_detect( y )
% Detects the positions of the board squares
% in the given input image; the board is assumed to be
% aligned horizontally and vertically in the image parallel to the image
% boundaries

% Detect the orizintal and vertical edges
BH = edge(y,'prewitt','horizontal');
BV = edge(y,'prewitt','vertical');

[H, W] = size(y);

XX = get_profile(H, W, BH);

XXm = medfilt1(XX, 3);
LocMaxX=peakdet(XXm,20);
locMaxSize = size(LocMaxX,1);
difX = zeros(1, locMaxSize);

for i=2:locMaxSize;
    difX(i-1) = LocMaxX(i)-LocMaxX(i-1);
end;


medDifX = median(difX);

k=0;
pozX = zeros(1,9);
for i = 1:(size(difX,2))
    if (abs(difX(i)- medDifX)< (medDifX*25/100))
        k=k+1; 
        pozX(k) = LocMaxX(i);
    else
        if (k==8)
            k=k+1; 
            pozX(k) = LocMaxX(i);
        end;
    end;
end;


YY = get_profile(W,H, BV');

YYm = medfilt1(YY, 3);
LocMaxY= peakdet(YYm,20);
locMaxSize = size(LocMaxY,1);
difY = zeros(1, locMaxSize);

for i=2:locMaxSize
    difY(i-1) = LocMaxY(i)-LocMaxY(i-1);
end;

medDifY = median(difY);
pozY = zeros(1,9);

kY=0;
for i = 1:(size(difY,2))  % merg de la mijloc spre capete
    if (abs(difY(i)- medDifY)< (medDifY*25/100))
        kY=kY+1;
        pozY(kY) = LocMaxY(i);
    else
        if (kY==8)
            kY=kY+1;
            pozY(kY) = LocMaxY(i);
        end;
    end;
end;



% % afisare date
% figure(1); imshow(y);
% figure(3); imshow(BH);
% figure(4); imshow(BV);
% figure(5); plot(XXm);
% hold on;
% plot(LocMaxX(:,1), LocMaxX(:,2), 'g*');
% 
% figure(6);
% plot(YYm);
% hold on;
% plot(LocMaxY(:,1), LocMaxY(:,2), 'g*');
% figure(1)
% 
% for i=1:kY
%     for j=1:k
%     hold on;
%     plot(pozY(i), pozX(j), 'r*');
%     end;
% end;

output_args = int16([pozY' pozX' ]);
end

function [ profile ] = get_profile(h, w, Edges)

profile = zeros(1,h);
for ih=1:h
    profile(ih)=0;
    for jw=1:w
        if (Edges(ih,jw))
            profile(ih)=profile(ih)+1;
        end
    end
end

end