function grid2 = merge_regions(grid, region_ind)
% function grid = merge_regions(grid, region_ind)
%
% A function that takes a grid and indices to the regions to merge. The
% function returns the new grid with the regions updates and automatically
% builds the springs.
%
% Dr. A. I. Hanna (2007)

grid2 = grid;
region_vertices_ind = [];
region_ctrl_pt_ind = [];
ctrl_pts = grid2.control_pts;
pts = grid2.region_vertices;
for i=1:length(region_ind)
    region_vertices_ind = cat(1, region_vertices_ind, grid.region_vertices_ind{region_ind(i)});
end
[rpts, ind] = order_xy_pts(pts(region_vertices_ind,:));
region_vertices_ind = region_vertices_ind(ind);

in = [];
for i=1:length(region_ind)
    in = cat(1, in, grid.region_ctrl_pt_ind{region_ind(i)});
end
in = unique(in(:));
[sctrlpts, ind] = order_xy_pts(ctrl_pts(in,:));
region_ctrl_pt_ind = cat(1, region_ctrl_pt_ind, in(ind));

regions_to_remove = setdiff(region_ind, region_ind(1));
grid2.region_ctrl_pt_ind(regions_to_remove) = [];
grid2.region_ctrl_pt_ind{region_ind(1)} = region_ctrl_pt_ind;
grid2.region_vertices_ind(regions_to_remove) = [];
grid2.region_vertices_ind{region_ind(1)} = region_vertices_ind;
grid2 = build_regions(grid2);

grid2 = init_grid(grid2);
[grid2] = makeInternalSprings(grid2);
[grid2] = makeExternalSprings(grid2);
[grid2] = makeShapeSprings(grid2);
return