% ==================================================================================================
% Module:   atdiffusion.m
%
% Usage:    
%
% Purpose: 
%     Performs anisotropic diffusion on a grayscale image
%     
% Input Variables:
%     I image
%     t number of iterations
%     g function
%     k variable
%     
% Returned Results:
%     The grayscale image with filter applied.
%  
% Restrictions/Notes:
%     This function is geared for grayscale images.  g is hardcoded into
%     the program for speed. Optionally, g may be specified and evaulated
%     using Matlab's eval() function.
%     
% See Also:
%
% References:
%
% 
% Author:       Isaac Gerg
% Date:         3/25/04
% Revisions:    none
% ==================================================================================================
function O = atdiffusion(I,t,g,k)

I = double(I);
I_plus_1 = zeros(size(I));
for q=1:t
    q
	for x = 1:size(I,1)
        for y = 1:size(I,2)
            if x<2 || y<2 || x>size(I,1)-2 || y>size(I,2)-2
                continue;
            end
            del_n = I(x,y+1) - I(x,y);
            del_s = I(x,y-1) - I(x,y);
            del_e = I(x+1,y) - I(x,y);
            del_w = I(x-1,y) - I(x,y);
            p = del_n;
            cn = exp(-abs(p)/k);
            p = del_e;
            ce = exp(-abs(p)/k);
            p = del_s;
            cs = exp(-abs(p)/k);
            p = del_w;
            cw = exp(-abs(p)/k);
            %exp(-abs(p)/k);
            % 1/(1+(p/k)^2)
            I_plus_1(x,y) = I(x,y) + 0.25*(del_n*cn + del_s*cs + del_e*ce + del_w*cw);
        end
	end
    I = I_plus_1;    
end
O = uint8(I_plus_1);
