function [J, Err, cost] = utApplyRegularizationCorrection(J, Err, cost, R, Rs, x, xCenter, N, QRModel)
% Add regularization to the objective function.
%
% QRModel: model computes qr factors of error and Jacobian.
% N: number of samples
% Rs = Cholesky factor of sqrt(Lambda)*R; and input argument R = Rs'*Rs

% Copyright 2014-2019 The MathWorks, Inc.

% Note: J is not scaled by 1/N (and Err has no scaling). However,
% the "cost" is. Both Err and J absorb the weighting in sqrt form.
cost = cost + (x-xCenter)'*R*(x-xCenter)/N;
if ~isempty(Err)
   Err = [Err; Rs*(x-xCenter)];
end
if ~isempty(J)   
   J = [J; Rs];
   if QRModel
      R1 = triu(qr([J, Err]));
      [nRr,nRc] = size(R1);
      R1 = R1(1:min(nRr,nRc),:);
      J = R1(:,1:end-1);
      Err = R1(:,end);
   end
end
