function [D,BlkStruct] = sortBlocks(D)
% Sorts blocks by name in LFT model.
% Second output argument is used by mu-analysis code.

%   Author(s): P. Gahinet
%   Copyright 1986-2011 The MathWorks, Inc.
Blocks = D.Blocks;

% Sort blocks
BlockNames = getBlockName(Blocks);
[BlockNames,bperm] = sort(BlockNames);
if any(diff(bperm)<0)
   % Permute blocks
   [wperm,zperm] = getRowColPerm(Blocks,bperm);
   [ny,nu] = iosize(D);
   if isnumeric(D.IC)
      D.IC = D.IC([1:ny,ny+zperm],[1:nu,nu+wperm]);
   else
      D.IC = ioperm(D.IC,[1:ny,ny+zperm],[1:nu,nu+wperm]);
   end
   Blocks = Blocks(bperm,:);
   D.Blocks = Blocks;
end

% Construct BLKSTRUCT
if nargout>1
   nblk = numel(Blocks);
   [BlockNames,iu] = unique(BlockNames,'first');
   ncopies = diff([iu ; nblk+1]);
   BlockList = getBlockList(Blocks(iu));
   BlkStruct = struct('Name',BlockNames,'Size',[],'Type',[],'Occurrences',[],'Simplify',[]);
   for ct=1:numel(iu)
      blk = BlockList{ct};
      BlkStruct(ct).Size = iosize(blk);
      BlkStruct(ct).Type = class(blk);
      BlkStruct(ct).Occurrences = ncopies(ct);
      if isa(blk,'UncertainBlock')
         % Simplify level
         BlkStruct(ct).Simplify = find(strcmp({'off';'obvious';'basic';'full'},blk.AutoSimplify)) - 1;
      end
   end
end