
%---------------------------------------------------------------------  
% function [M,m] = FT_compute_cavity_ABCD(cavity)
% 
% computes the ABCD matrix and stability parameter for an
% optical resonantor
%
% cavity: strcuture with optical components of cavity
% M: ABCD eigen matrix of the cavity (2x2x2)
% m: stability parameter
% state: cavity is stable (0), critical (1) or unstable (2)
%
% Andreas Freise 11.02.10 afreise@googlemail.com
%---------------------------------------------------------------------  
%

% Description: Computes the ABCD matrix and stability parameter
% Description: for an optical resonator
% Keywords: matrix, stability, parameter, compute, cavity, m

function [M,m] = FT_compute_cavity_ABCD(cavity)

  baseid='compute_cavity_ABCD';
  clast=cavity.ncomponents;
  
  n=1;
  
  M=zeros(2,2,2);
  M(1,1,:)=1;
  M(2,2,:)=1;
  
  for p=1:clast
    Ms = FT_ABCD_space(cavity.space(p).L, cavity.space(p).n);
    M = FT_multiply_ABCDs(M,FT_invert_ABCD(Ms));
    Mm = FT_ABCD_mirror(cavity.mirror(p).Rc,cavity.mirror(p).alpha,n);
    M = FT_multiply_ABCDs(M,FT_invert_ABCD(Mm));
  end
  
  % should be inverted but is correct without the following line. To be checked!
  %M=FT_invert_ABCD(M);
  
  [m,state] = FT_check_cavity_ABCD(M);
  if (sum(state)~=0)
    msgid=[baseid,':stability'];
    if (length(m)==1)
      result=sprintf('cavity not stable (m=%d).\n',m);
    else
      result=sprintf('cavity not stable (m=%d,%d).\n',m(1),m(2));
    end
    error(msgid,result);
  end
