function [sel_cens] = iterative_rounding(dists,svar,k,lambda,early_stop)
% The iterative rounding algorithm.
numPoints = size(dists, 1);
[~, x, y] = originalLP(dists,svar,k);
frac_vars = x(:,any(x>0));
dists = dists(:,any(x>0));
numCenters = size(dists, 2);
unique_cens_num = size(frac_vars,2);
unique_val_cens = cell(1, unique_cens_num);
num_frac_cens = zeros(1, unique_cens_num);
starting_cens = ones(1, unique_cens_num);
groups = unique(svar);
sel_cens = zeros(1,k+length(groups));
for i = 1:unique_cens_num
    temp = unique(frac_vars(frac_vars(:,i)>0, i));
    num_frac_cens(i) = length(temp);
    unique_val_cens{i} = sort(temp);
    if i<unique_cens_num
        starting_cens(i+1) = starting_cens(i) + num_frac_cens(i);
    end
end
dists_rep = zeros(numPoints, sum(num_frac_cens));
Fs = zeros(numPoints, sum(num_frac_cens));
for i = 1:unique_cens_num
    dists_rep(:,starting_cens(i):(starting_cens(i)+num_frac_cens(i)-1)) = repmat(dists(:,i),1,num_frac_cens(i));
end
dists_rep = (1+lambda) .^ round(log(dists_rep) / log1p(lambda));
for i = 1:numPoints
    for j = 1:numCenters
        Fs(i,starting_cens(j):(starting_cens(j)+sum(frac_vars(i,j) >= unique_val_cens{j})-1))=1;
    end
end
ds = max(dists_rep .* Fs, [], 2);
ustar = zeros(numPoints, 1);
[~,inds] = sort(ds);
for i = 1:numPoints
    temp = Fs(ustar == 1, :);
    if any(any(temp & repmat(Fs(inds(i),:),size(temp,1),1))) == false
        ustar(inds(i)) = 1;
    end
end
Bs = Fs;
for i = 1:numPoints
    Bs(i,:) = (dists_rep(i,:) <= ds(i) / (1+lambda)) & Fs(i,:);
end

hicounter = 0;

while true
    [~,y2] = iterative_LP(dists_rep, svar, ustar, ds, Fs, Bs, k);
    sumBs = (Bs .* (1-ustar)) * y2;
    hicounter = hicounter + 1; 
    if all(sumBs < 1) || (early_stop == 1 && sum(y2>0)<=k+length(groups)) || (hicounter>=50 && sum(y2>0)<=k+length(groups))
        counter = 1;
        counter2 = 1;
        for i = 1:length(y)
            if y(i) ~= 0
                if any(y2(starting_cens(counter):(starting_cens(counter)+num_frac_cens(counter)-1))>0)
                    sel_cens(counter2) = i;
                    counter2 = counter2 + 1;
                end
                counter = counter+1;
            end
        end
        break;
    else
        for i = 1:numPoints
            if abs(sumBs(i)-1) <= 0.00001
                Fs(i,:) = Bs(i,:);
                ds(i) = ds(i) / (1+lambda);
                Bs(i,:) = (dists_rep(i,:) <= ds(i) / (1+lambda)) & Fs(i,:);
                temp = any((Fs .* (ustar == 1)) .* repmat(Fs(i,:),numPoints,1), 2);
                if all(ds(temp) > ds(i))
                    ustar(temp) = 0;
                    ustar(i) = 1;
                end
                break
            end
        end
    end    
end
end