function D = foldBlocks(D,isF)
% Folds blocks into IC model. Each block is replaced by its current
% or linearized value. ISF is a logical vector commensurate with 
% D.Blocks that flags the blocks to be folded

%   Copyright 1986-2011 The MathWorks, Inc.
iFold = find(isF);
if isempty(iFold)
   return
end
iKeep = find(~isF);
[ny,nu] = iosize(D);
Blocks = D.Blocks;
[wperm,zperm] = getRowColPerm(Blocks,[iKeep;iFold]);
if isnumeric(D.IC)
   % Move folded blocks to end of block vector
   IC = D.IC([1:ny,ny+zperm],[1:nu,nu+wperm]);
   % Fold blocks
   D.IC = lft(IC,double_(Blocks(iFold)));
else
   % Move folded blocks to end of block vector
   IC = ioperm(D.IC,[1:ny,ny+zperm],[1:nu,nu+wperm]);
   % Fold blocks
   FoldBlocks = Blocks(iFold);
   [nwF,nzF] = iosize(FoldBlocks);
   [nyz,nuw] = iosize(IC);
   D.IC = lft(IC,D.blk2lti(FoldBlocks),nuw-nwF+1:nuw,nyz-nzF+1:nyz,1:nzF,1:nwF);
end
D.Blocks = Blocks(iKeep,:);
