%---------------------------------------------------------------------  
% function [m,state] = FT_check_cavity_ABCD(M)
% 
% computes the stability parameter m from the ABCD matrix of an 
% optical resonantor
%
% M: ABCD matrix
% m: stability parameter
% state: cavity is stable (0), critical (1) or unstable (2)
%
% Andreas Freise 29.08.08 afreise@googlemail.com
%---------------------------------------------------------------------  
%
% Description: computes the stability parameter m from the ABCD matrix of an
% Description: optical resonator
% Keywords: stability, parameter, m, resonator, check, cavity, m

function [m,state] = FT_check_cavity_ABCD(M)

  if (size(M,3)==1)
    A=M(1,1);
    D=M(2,2);
    m=(A+D)./2.0;
    
    if (m < -1 || m > 1) 
      state=2;
    elseif (m == -1 || m == 1) 
      state=1;
    else 
      state=0;
    end
  else
    m=zeros(1,2);
    for i=1:2
      A=M(1,1,i);
      D=M(2,2,i);
      m(i)=(A+D)./2.0;
    end

    if ((m(1) < -1 || m(1) > 1) || (m(2) < -1 || m(2) > 1) )
      state=2;
    elseif ((m(1) == -1 || m(1) == 1) || (m(1) == -1 || m(1) == 1) )
      state=1;
    else 
      state=0;
    end
      
  end
