function [imageOut] = kirschEdge(imageIn, varargin)

thres_flag = 0;

if nargin > 1
    threshold = varargin{1};
    thres_flag = 1; 
end

% The Kirsch operator

% Igray is grayscale of the original image
im_double = double(imageIn);

% Eight directions Kirsch edge masks. below masks are gettting from
% rotation of the one mask.
g1=[5,5,5; -3,0,-3; -3,-3,-3]; % South
g2=[5,5,-3; 5,0,-3; -3,-3,-3]; % Southeast
g3=[5,-3,-3; 5,0,-3; 5,-3,-3]; % East
g4=[-3,-3,-3; 5,0,-3; 5,5,-3]; %
g5=[-3,-3,-3; -3,0,-3; 5,5,5];
g6=[-3,-3,-3; -3,0,5;-3,5,5];
g7=[-3,-3,5; -3,0,5;-3,-3,5];
g8=[-3,5,5; -3,0,5;-3,-3,-3];
% filtering with Kirsch mask
% edges in all the direction
%     Each mask respondsmaximally to an edge oriented in a particular general
%     direction. The maximum value over all eight orientations
%     is the output value for the edge magnitude image.
x1=imfilter(im_double,g1,'replicate');
x2=imfilter(im_double,g2,'replicate');
x3=imfilter(im_double,g3,'replicate');
x4=imfilter(im_double,g4,'replicate');
x5=imfilter(im_double,g5,'replicate');
x6=imfilter(im_double,g6,'replicate');
x7=imfilter(im_double,g7,'replicate');
x8=imfilter(im_double,g8,'replicate');

y1=max(x1,x2);
y2=max(y1,x3);
y3=max(y2,x4);
y4=max(y3,x5);
y5=max(y4,x6);
y6=max(y5,x7);
imageOut=max(y6,x8); % result image

% image mapping in the interval of 0 to 255
imageOut = (255)*((imageOut-min(imageOut(:)))/(max(imageOut(:))-min(imageOut(:))));
% imageOut = mapfun(imageOut, 0, max(max(imageOut)), 0, 255);

% Threshold
if thres_flag == 1
    threshed = imageOut >= threshold*255 ; % if the input value is greater than thres value sets as 1
    imageOut = threshed;
end


