function Cout = Cavity_resonance_phase(Cin)
%  Cout = Cavity_resonance_phase(Cin) find the resonance of a cavity
% This procedure can find the resonance of the cavity by finding the
% suitable round trip phase shift to bring the circulating field on resonance.

Cout = Cin;

if ~Cin.Laser_start_on_input
    Field_in =  Change_E_n(Cin.Laser_in,Cin.I_array(1).n2);
    Field_in = Transmit_Reflect_Interface(Field_in,Cin.I_array(1));
    Field_Circ = Field_in;
else
    Field_Circ = Cin.Laser_in;
end

num_iter = Cin.Cavity_phase_param;

Field_total = Normalise_E(Field_Circ,0);
Phase_adjust =1;


% Calculate the pseudo eigen mode in the cavity

for q = 1:num_iter
    
    Field_total = Field_total + Field_Circ;
    for pp=1:Cin.Nb_mirror
        
        if pp ~= Cin.Nb_mirror % check we are not at the last iteration
            Field_Circ = Propagate_E(Field_Circ,Cin.Propagation_mat_array(pp));
            Field_Circ = Reflect_mirror(Field_Circ,Cin.I_array(pp+1));
        else
            Field_Circ = Propagate_E(Field_Circ,Cin.Propagation_mat_array(pp))*Phase_adjust;
            Field_Circ = Reflect_mirror(Field_Circ,Cin.I_array(1));
        end
        
    end
    
    Phase_adjust = Phase_adjust * exp(-1i*angle(Calculate_Overlap(Field_Circ,Field_total)));
    
end

% Then find the round trip to make the eigen mode on resonnance

Field_before = Field_total;
Field_Circ = Field_total;

for pp=1:Cin.Nb_mirror
    
    if pp ~= Cin.Nb_mirror % check we are not at the last iteration
        Field_Circ = Propagate_E(Field_Circ,Cin.Propagation_mat_array(pp));
        Field_Circ = Reflect_mirror(Field_Circ,Cin.I_array(pp+1));
    else
        Field_Circ = Propagate_E(Field_Circ,Cin.Propagation_mat_array(pp));
        Field_Circ = Reflect_mirror(Field_Circ,Cin.I_array(1));
    end
    
end

Cout.Resonance_phase = exp(-1i* angle(Calculate_Overlap(Field_Circ,Field_before)));

disp(['Found the phase for resonance in cavity ' inputname(1)])

end