function sys = modred(sys,elim,method)
%MODRED  Model simplification by state elimination.
%
%   RSYS = MODRED(SYS,ELIM) simplifies the state-space model SYS by 
%   discarding the states specified in the vector ELIM. The full state 
%   vector X is partitioned as X = [X1;X2] where Xr=X1 is the reduced
%   state vector and X2 is discarded.
%
%   ELIM can be a vector of indices or a logical vector commensurate
%   with X where TRUE values mark states to be discarded. If SYS has 
%   been balanced with BALREAL and the vector G of Hankel singular 
%   values has small entries, you can use MODRED to eliminate the 
%   corresponding states:
%      [sys,g] = balreal(sys)   % compute balanced realization
%      elim = (g<1e-8)          % small entries of g -> negligible states
%      rsys = modred(sys,elim)  % remove negligible states
%
%   RSYS = MODRED(SYS,ELIM,METHOD) also specifies the state elimination
%   method. Available choices for METHOD include:
%      'matchdc'    Treats X2 as infinitely fast to enforce matching 
%                   DC gains (default)
%      'truncate'   Simply deletes X2.
%   The 'truncate' option tends to produce a better approximation in the
%   frequency domain, but the DC gains are not guaranteed to match.
%
%   Note: For more accurate results, use BALRED instead of BALREAL+MODRED.
%
%   See also BALREAL, BALRED, SS.

%   Author(s): J.N. Little, P. Gahinet
%   Copyright 1986-2012 The MathWorks, Inc.
ni = nargin;
if ni<2
   error(message('Control:general:TwoOrMoreInputsRequired','modred','modred'))
elseif numsys(sys)~=1
   error(message('Control:general:RequiresSingleModel','modred'))
elseif ni==3 && any(strncmpi(method,{'m','d','t'},1))
   % Make sure to trap old keywords 'mdc' and 'del'
   if strncmpi(method,'m',1)
      method = 'MatchDC';
   else
      method = 'Truncate';
   end
else
   method = 'MatchDC';  % default
end

% Get order and check ELIM
ns = order(sys);
if isa(elim,'logical')
   elim = find(elim);
end
elim = elim(:);
if any(diff(sort(elim))==0)
   error(message('Control:general:IndexRepeated','modred(SYS,ELIM)','ELIM'))
elseif any(elim<0) || any(elim>ns)
   error(message('Control:general:IndexOutOfRange','modred(SYS,ELIM)','ELIM'))
end

% Perform separation
try
   sys = modred_(sys,method,elim);
catch E
   ltipack.throw(E,'command','modred',class(sys))
end

% Clear notes, userdata, etc
sys.Name = '';  sys.Notes = {};  sys.UserData = [];
