function atlas = update_atlas(atlas, ID)
% UPDATE_ATLAS   Update the polyhedral mesh
%
% ATLAS = UPDATE_ATLAS(ATLAS, ID)
%
% ATLAS - Manifold atlas
% ID    - Integer id of chart with new radius

% This file is part of the atlas_kd toolbox, copyright (C) Michael
% Henderson, Frank Schilder, Harry Dankowicz, Erika Fotsch, of the package
% COCO (http://sourceforge.net/projects/cocotools).

chart1 = atlas.charts{ID};
nOut   = [chart1.neigh(chart1.neigh~=0) chart1.emptyN];
nIn    = [];
while ~isempty(nOut)
  chart2 = atlas.charts{nOut(1)};
  chart2 = create_polyhedron(chart2, atlas.cont.Rmarg);
  chart2.emptyN = [];
    
  % only merge with merged charts
  chart2.intsct = setdiff(chart2.intsct, ID);
  intsct = setdiff(chart2.intsct, nOut);
  for j=1:numel(intsct)
    chart3     = atlas.charts{intsct(j)};
    atlas.edge = atlas.edge + 1;
    chart2     = chop_polyhedron(atlas.edge, chart2, chart3);
    if chart2.P.n==0
      chart3.emptyN = union(chart3.emptyN, chart2.id);
    end
    if ismember(chart3.id, nIn)
      atlas.edge = atlas.edge + 1;
      chart3     = chop_polyhedron(atlas.edge, chart3, chart2);
      if chart3.P.n==0
        chart2.emptyN = [chart2.emptyN, chart3.id];
      end
      atlas.charts{intsct(j)} = chart3;
    end
  end
  atlas.charts{nOut(1)} = chart2;
  nIn = [nIn nOut(1)]; %#ok<AGROW>
  nOut(1) = [];
end

% re-insert resized chart
chart1 = create_polyhedron(chart1, atlas.cont.Rmarg);
chart1.emptyN = [];

list   = list_intersecting_charts(atlas.tree, ID, chart1.x, chart1.R); % Construct list of all overlapping charts
chart1.intsct = list;

for i=1:numel(list)
  chart2     = atlas.charts{list(i)};
  atlas.edge = atlas.edge + 1;
  chart1     = chop_polyhedron(atlas.edge, chart1, chart2);
  if chart1.P.n==0
    chart2.emptyN = [chart2.emptyN chart1.id];
  end
  
  if chart2.P.n~=0
    atlas.edge = atlas.edge + 1;
    chart2     = chop_polyhedron(atlas.edge, chart2, chart1);
    if chart2.P.n==0
      chart1.emptyN = [chart1.emptyN chart2.id];
    end
  end
  chart2.intsct = [chart2.intsct chart1.id];
  atlas.charts{list(i)} = chart2;
end

atlas.charts{ID} = chart1;

atlas.boundary = union(atlas.boundary, [nIn ID]);
bdry_charts    = atlas.charts(atlas.boundary);
idx            = cellfun(@(x) ~isempty(x.bv), bdry_charts);
atlas.boundary = atlas.boundary(idx);

end
