function [D,SingularFlag] = normalizeBlocks(D)
% Normalizes blocks in LFT model.
%   * For uncertain blocks B, this means the block seen from IC is
%     unit-norm uncertainty with zero nominal value
%   * For tunable blocks and analysis points, this means the block 
%     current value has zero feedthrough

%   Author(s): P. Gahinet
%   Copyright 1986-2022 The MathWorks, Inc.
IC = D.IC;
[Blocks,bnorm,Tnorm] = normalize(D.Blocks);
if isempty(bnorm)
   SingularFlag = false;
else
   % Non-trivial normalization
   [wN,zN] = getRowColSelection(Blocks,bnorm);
   [ny,nu,nz,nw] = getSignalSize(D);
   indwN = nu+wN;  indwNC = 1:nu+nw;  indwNC(:,indwN) = []; 
   indzN = ny+zN;  indzNC = 1:ny+nz;  indzNC(:,indzN) = [];
   % The LFT pushes the channels INDWN and INDZN to the bottom. Make
   % sure to bring them back to their original location
   if isnumeric(IC)
      IC([indzNC indzN],[indwNC indwN]) = lft(IC,Tnorm,indwN,indzN,...
         1:length(indzN),1:length(indwN));
      SingularFlag = ~allfinite(IC);
   else
      [IC,SingularFlag] = lft(IC,IC.createGain(Tnorm),...
         indwN,indzN,1:length(indzN),1:length(indwN));
      uperm(:,[indwNC indwN]) = 1:nu+nw;
      yperm(:,[indzNC indzN]) = 1:ny+nz;
      IC = ioperm(IC,yperm,uperm);
   end
end
D.IC = IC;  D.Blocks = Blocks;
