function imr = AMAM_flow(im,r,c,dist)
%
% AMAM_flow - counts out a max distance along connected neighbors 
%             from a pixel
% On input:
%     im (mxn image): binary image
%     r (int): starting row
%     c (int): starting col
%     dist (float): max dist to flow out from start
% On output:
%     imr (mxn image): pixels in connected component of (r,c) within dist
% Call:
%     imr = AMAM_flow(im_roads,23,56,20);
% Author:
%     T. Henderson
%     UU
%     Fall 2008
%

[num_rows,num_cols] = size(im);
imr = zeros(num_rows,num_cols);
imq = zeros(num_rows,num_cols);
queue = [r,c,0];
imr(r,c) = 1;
imq(r,c) = 1;
while ~isempty(queue)
    r = queue(1,1);
    c = queue(1,2);
    d = queue(1,3)+1;
    imr(r,c) = d;
    queue = queue(2:end,:);
    r_min = max(1,r-1);
    r_max = min(num_rows,r+1);
    c_min = max(1,c-1);
    c_max = min(num_cols,c+1);
    for rr = r_min:r_max
        for cc = c_min:c_max
            if (im(rr,cc)>0)&(imq(rr,cc)==0)&(d<=dist)
                queue = [queue; rr,cc,d];
                imq(rr,cc) = 1;
            end
        end
    end
end
