function [features] = image_features(img,thresh,corners)
% This function takes an image and returns the feature matrix P of it
% according to the threshold. In addition, the corners information will be
% attached to the last column of the matrix P specifying whether a row that
% represents a pixel on the image is a corner or not.

[row, col] = size(img);
features = zeros((row-6)*(col-6), 17);
img = img';

for i = (1+3):(col-3)
    for j = (1+3):(row-3)
        for x = 1:16
            features((i-4)*(row-6) + (j-3),x) = find_state(img, i,j,x, thresh);
        end   
    end
end

if ~isempty(corners)
    num_of_corners = length(corners(:,1));    
    for i = 1:num_of_corners   
        ind = (corners(i,1)-4)*(row-6) + (corners(i,2)-3);
        features(ind,17) = 1;
    end
end

end

function state = find_state(img,i,j, x, thresh)
    state = 0;   
    Ip = img(i,j);
    Ix = 0;
    if x == 1
        Ix = img(i,j-3);
    elseif x==2
        Ix = img(i+1,j-3);
    elseif x==3
        Ix = img(i+2,j-2);
    elseif x==4
        Ix = img(i+3,j-1);
    elseif x==5
        Ix = img(i+3,j);
    elseif x==6
        Ix = img(i+3,j+1);
    elseif x==7
        Ix = img(i+2,j+2);
    elseif x==8
        Ix = img(i+1,j+3);
    elseif x==9
        Ix = img(i,j+3);
    elseif x==10
        Ix = img(i-1,j+3);
    elseif x==11
        Ix = img(i-2,j+2);
    elseif x==12
        Ix = img(i-3,j+1);
    elseif x==13
        Ix = img(i-3,j);
    elseif x==14
        Ix = img(i-3,j-1);
    elseif x==15
        Ix = img(i-2,j-2);
    else
        Ix = img(i-1,j-3);
    end
    
    if Ix <= Ip - thresh
        state = 0;
    elseif Ix < Ip + thresh
        state = 1;
    else
        state = 2;
    end
    
end






