% This function will check the stability of a given transfer function by
% either evaluating the resultant phase and gain margin or looking at the
% poles for any positive real parts and repeated imaginary poles
% Input:
%   TF - the desired transfer function to be analyzed
%   poleormarg - char string 'pole' or 'margin' that chooses the analysis
%   method
% Output:
%   stable_or_not - boolean 0 for unstable or 1 for stable

% Created by Brevin Banks 
% Modified 3/18/2023
function stable_or_not = Check_stable(TF,poleormarg)

if nargin==1
    poleormarg='pole';
end

stable_or_not = 1;
if strcmp('pole',poleormarg)
    [z,p,k] = zpkdata(TF);
    poles = [z{1};p{1}];
    for tester=1:length(poles) 
        if real(poles(tester))>0 % check for any positive real parts of poles
            stable_or_not = 0;
        end
        for iter=1:length(poles) % check for repeated imaginary axis poles
            if real(poles(tester))== 0 && imag(poles(tester))==imag(poles(iter)) && real(poles(iter))==0 && iter~=tester
                stable_or_not = 0;
            end
        end
    end
    
elseif strcmp('margin',poleormarg) %ensure input TF is an open loop transfer function (this includes the impedance)
    warning('off');
    [mag1,phase1] = margin(TF);
    stable_or_not = 1;
    mg = allmargin(TF);
    if any(mg.GainMargin<0)
        stable_or_not = 0;
    end
    if any(mg.PhaseMargin<0)
        stable_or_not = 0;
    end
    % Check if stable or not
    if phase1 <= 0 % unstable if negative
        stable_or_not = 0;
    end

    if mag1 <= 0 % unstable if negative
        stable_or_not = 0;
    end
    warning('on');
end

end



