function grid = segmentOrgan(grid)
organ_im = pts2binim(fliplr(grid.shape));

R = organ_im;
region_ind = grid.region_vertices_ind;
vertices = grid.region_vertices;

vertices = grid.control_pts;
region_ind = grid.region_ctrl_pt_ind;


number_of_regions = length(region_ind);
centroids = zeros(number_of_regions, 2);
w_h = waitbar(0, 'Building regions...');
for i=1:number_of_regions
    waitbar(i/number_of_regions, w_h);
    %r_vertices = vertices(region_ind{i},:);
   r = zeros(size(R));
    for ii=1:length(region_ind{i})
        r_vertices = grid.tri_info.pts(grid.tri_info.T(region_ind{i}(ii), :), :);
       r = r+roipoly(r, r_vertices(:,1), r_vertices(:,2));
    end
   %figure(1);
   %imagesc(r)
    r = r&organ_im;
    R = R + r*i;
    organ_im = organ_im & ~r;
    centroids(i,:) = getCentroid(r);
  %  figure(1); cla;
  %  imagesc(r); 
  %  plot(centroids(i,1),centroids(i,2), 'go');
end
close(w_h);
grid.R = R;
grid.centroids = centroids;
grid.vert = [grid.control_pts; grid.centroids];