function [prob atlas cseg flush] = init_atlas(atlas, prob, cseg)
%INIT_ATLAS   Initialize atlas.
%
% Assign successfully located initial chart to point list and flush.

% 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).

chart          = cseg.curr_chart;
h              = atlas.cont.h;

% Initialize step size to keep residuum below MaxRes
res   = chart_hc_res(prob, chart, h);
while (res > atlas.cont.MaxRes) && (h > atlas.cont.h_min)
  h   = max(atlas.cont.h_min, atlas.cont.h_fac_min*h);
  res = chart_hc_res(prob, chart, h);
end

chart.R        = h;
chart.h        = h;
mark           = chart.P.mark;
chart          = create_polyhedron(chart, atlas.cont.Rmarg);
chart.P.mark   = mark;
chart.bv       = find(~chart.P.mark);
chart.loc      = [];
chart.emptyN   = []; 
chart.intsct   = [];
chart.pt_type  = 'EP';
chart.ep_flag  = 1;
cseg.ptlist{1} = chart;
flush          = true;

end

function res = chart_hc_res(prob, chart, h)

% Ignore residuum of arc-length constraint
prob.xfunc.mode = 2;

% Compute residuum on boundary box
xx  = chart.TS*chart.s(:,chart.bv);
res = 0;
for i=1:size(xx,2)
  [prob chart f] = prob.efunc.F(prob, chart, chart.x + h*xx(:,i));
  res = max(res,norm(f));
end

end
