function dist = BOOK_flow_dist(im,r0,c0)
% BOOK_flow_dist - distance of all pixels from source
% On input:
%     im (mxn binary image): connected component (foreground is 1)
%     r0 (int): start row of flow
%     c0 (int): start col of flow
% On output:
%     dist (mxn binary image): distance (+1) of each point from source
% Call:
%     d = BOOK_flow_dist(im,21,18);
% 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
end
