function S = allmargin_(sys,opt)
% All stability margins

% Copyright 1986-2014 The MathWorks, Inc.
[nch,~,nsys] = size(sys);
D = sys.Data_;
S = struct(...
   'GainMargin',cell([nch size(D)]),...
   'GMFrequency',[],...
   'PhaseMargin',[],...
   'PMFrequency',[],...
   'DelayMargin',[],...
   'DMFrequency',[],...
   'Stable',[]);

% Compute margins
if nsys>0
   if nch==1
      for ct=1:nsys
         S(1,ct) = allmargin(D(ct),opt);
      end
   else
      % Compute margins of j-th channel with other loops closed
      G = createGain(D(1),-eye(nch-1));
      for j=1:nch
         jCL = [1:j-1,j+1:nch];
         for ct=1:nsys
            S(j,ct) = allmargin(lft(D(ct),G,jCL,jCL,1:nch-1,1:nch-1),opt);
         end
      end
   end
end

if nch==1
   % Size discontinuity needed for backward compatibility
   S = reshape(S,size(D));
end