% ISSTABLE tells if ssm is numerically stable
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DESCRIPTION: ISSTABLE tells if ssm is numerically stable
%
%              val = sys.isStable
%
% <a href="matlab:utils.helper.displayMethodInfo('ssm', 'isStable')">Parameters Description</a>
%
% VERSION: $Id: isStable.m,v 1.6 2011/04/08 08:56:23 hewitson Exp $
% 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function varargout = isStable(varargin)
  %%% Check if this is a call for parameters
  if utils.helper.isinfocall(varargin{:})
    varargout{1} = getInfo(varargin{3});
    return
  end
  objs = utils.helper.collect_objects(varargin(:), 'ssm');
  
  utils.helper.msg(utils.const.msg.MNAME, ['running ', mfilename]);
  
  for i=1:numel(objs)
    if ~objs(i).isnumerical  % checking system is numeric
      error(['error in double : system named ' objs(i).name ' is not numeric']);
    end
    A = ssm.blockMatFusion(objs(i).amats, objs(i).sssizes, objs(i).sssizes);
    Ts = objs(i).timestep;
    if Ts == 0
      vp = eig(A);
      f = find(real(vp)>5e-15);
      f2 = find(real(vp)>0);
      display((vp(f)));
    else
      try
        vp = eig(A^1024);
      catch ME
        vp = eig(A);
      end
      f = find(abs(vp)>1+5e-12);
      f2 = find(abs(vp)>1);
      display((vp(f)));
    end
    ninst = numel(f);
    ninst2 = numel(f2);
    isst(i) = ninst==0;
    if ninst>0;
      display(['warning, system named "' objs(i).name '" is not stable'])
    elseif ninst2>0;
      display(['warning, system named "' objs(i).name '" might be numerically unstable'])
    else
      display(['System named "' objs(i).name '" is stable'])
    end
  end
  varargout ={isst};
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                               Local Functions                               %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


%--------------------------------------------------------------------------
% Get Info Object
%--------------------------------------------------------------------------
function ii = getInfo(varargin)
  
  if nargin == 1 && strcmpi(varargin{1}, 'None')
    sets = {};
    pl   = [];
  else
    sets = {'Default'};
    pl   = getDefaultPlist;
  end
  % Build info object
  ii = minfo(mfilename, 'ssm', 'ltpda', utils.const.categories.output, '$Id: isStable.m,v 1.6 2011/04/08 08:56:23 hewitson Exp $', sets, pl);
end

%--------------------------------------------------------------------------
% Get Default Plist
%--------------------------------------------------------------------------
function pl = getDefaultPlist()
  pl = plist();
end

