function select = adjustSplit(p,nx1,REAL,EXPLICIT)
% Adjusts spectrum split when ill-conditioned.
% Augments P1=P(1:nx1) with P2 entries nearest to P1.
% Note: Assumes Inf poles are in P1 or P2 but not both.

% Copyright 2020 The MathWorks, Inc.
nx = numel(p);
p1 = p(1:nx1);
p2 = p(nx1+1:nx);
% Find P1(imin) closest to P2
if EXPLICIT
   % Use Euclidian distance
   dist = abs(p1-p2.');
else
   % Use approximate chordal metric to handle clusters near infinity.
   % Note: This metric is NaN-free when p1 contains Inf.
   dist = min(abs(p1-p2.'),abs(1./p1-1./p2.'));
end
[mindist,imin] = min(min(dist,[],2));
% Update P1 membership function
if isinf(mindist)
   % Move all Inf poles to P1
   select = true(nx,1);
else
   select2 = false(nx-nx1,1);
   % Absorb all P2's close to P1(imin)
   select2(dist(imin,:)<1.25*mindist,:) = true;
   if REAL && ~isreal(p1(imin))
      % Preserve spectrum symmetry
      imin = find(p1==conj(p1(imin)),1);
      select2(dist(imin,:)<1.25*mindist,:) = true;
   end
   select = [true(nx1,1) ; select2];
end