function dist = flow_dist(im,r0,c0,max_dist)
% flow_dist - distance of each foreground pixel from (r0,c0)
% On input:
%    im (mxn binary image): foreground is connected component
%    r0 (int): row value of starting point
%    c0 (int): col value of starting point
%    max_dist (int): max flow dist
% On output:
%     dist (mxn image): each pixel has distance (+1) from (r0,c0)
% Call:
%     Asf = flow_dist(As,25,25,5);
% Author:
%     T. Henderson
%     UU
%     Spring 2012
%

dist = 0*im;
[num_rows,num_cols] = size(im);
dist(r0,c0) = 1;
done = 0;
val = 0;
while done==0
    val = val + 1;
    [rows,cols] = find(dist==val);
    if isempty(rows)
        done = 1;
    else
        num_pts = length(rows);
        for p = 1:num_pts
            r = rows(p);
            c = cols(p);
            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)&&(dist(rr,cc)==0)
                        dist(rr,cc) = val + 1;
                    end
                end
            end
        end
    end
    if val>=max_dist
        done = 1;
    end
end
