function EDGED=persobel(MATRIX)

% Personnal version of edge enhancement,
% using the Sobel method.
%
% EXAMPLES:
%
% >> persobel('cell.jpg')
%    where cell.jpg is the cellular pattern image
% OR
% >> persobel(MATRIX)
%    where MATRIX is the double-type matrix of
%    the cellular pattern image, i.e. MATRIX=double(imread('cell.jpg')).
%
% >> EDGED=persobel(...) returns as EDGED the matrix of the 
% enhanced edge image.


if isstr(MATRIX)
   MATRIX=double(imread(MATRIX)); % Turns the image into a matrix
end

%Mv=[-1 0 1 ; -2 0 2 ; -1 0 1];
%Mh=[1 2 1 ; 0 0 0 ; -1 -2 -1];
[HEIGHT WIDTH]=size(MATRIX);
GRAD=zeros(HEIGHT,WIDTH);
EDGED=zeros(HEIGHT,WIDTH);

%figure;imshow(MATRIX);colormap(gray);title('Cellular Pattern');axis on;
%zoom on

h=waitbar(0,'Computing the image gradient, patience required!');

for I=2:HEIGHT-1 % This loop computes the gradient matrix GRAD.
   waitbar(I/HEIGHT,h)
   for J=2:WIDTH-1
      GRAD(I,J)=(MATRIX(I-1,J+1)+2*MATRIX(I,J+1)+MATRIX(I+1,J+1)-MATRIX(I-1,J-1)-2*MATRIX(I,J-1)-MATRIX(I+1,J-1))^2+(MATRIX(I-1,J-1)+2*MATRIX(I-1,J)+MATRIX(I-1,J+1)-MATRIX(I+1,J-1)-2*MATRIX(I+1,J)-MATRIX(I+1,J+1))^2;
   end
end

close(h)

M=max(max(GRAD));
m=1;

while m~=2 % This loop compares the gradient to the input threshold.
   
   t=input('\n Enter threshold percentage (for instance 20): ');
   h=waitbar(0,'Comparing the gradient to the threshold, so far so good...');
   
   for I=2:HEIGHT-1
      waitbar(I/HEIGHT,h)
      for J=2:WIDTH-1
         if GRAD(I,J)>t*M/100
            EDGED(I,J)=255;
         end
      end
   end
   
   close(h)
   
   figure;colormap(gray);image(EDGED);
   title(sprintf('Persobel -- Edge enhancement -- Threshold : %d %%',t));
   axis on;zoom on;
   
   m=menu('What would you like to do now?','Change threshold','Quit or return to main menu');
   
end