function [atlas cseg] = merge(atlas, cseg)
% MERGE   Merge a chart into the atlas
%
% Adds a new chart to chart tree and adjust polygonal representations

% 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 = cseg.ptlist{end};

if isempty(atlas.tree)
  atlas.tree = create_tree(numel(chart1.x)); % Initialize the tree
else
  % Construct list of all overlapping charts
  list = list_intersecting_charts(atlas.tree, -1, chart1.x, chart1.R);
  chart1.intsct = list;
  
  for i=1:numel(list)
    chart2     = atlas.charts{list(i)};
    if ~atlas.isclose(chart1, chart2)
      continue
    end
    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; % Update existing charts
  end
end
    
atlas.boundary = [atlas.boundary chart1.id]; % Append new chart to boundary
atlas.charts   = [atlas.charts   chart1   ]; % Append new chart to atlas

bdry_charts    = atlas.charts(atlas.boundary);
idx            = cellfun(@(x) ~isempty(x.bv), bdry_charts);
atlas.boundary = atlas.boundary(idx);

atlas = atlas.add_chart2tree(chart1.id); % Insert new chart in tree

end
