function [calc]=F0_ef(calc,sim,layer,SF,sequence)
%lcalc passed by reference?
%sim and others are not changed so matlab don't copy them
%calc is copied, passing by reference seems complicated

twok = 1.01355e-3*sim.energy(1);   %1.01355e-3=2*twopi/12398.42
factor = 830.9471/sim.energy(1)^2; %0.00000540556*12398.42^2
calc.Q(:,:,1) = [1;1] * twok * sin(calc.reflectivity(1,:)); % initializing, vacuum n=1

for k=1:length(layer) % 1: cap layer.  SF.cf(1,1) is for vacuum
    l_indexref = sqrt(1 - factor*layer(k).density(2)*SF.cf(k+1,1));
    calc.Q(:,:,k+1 ) = [ l_indexref ; inv(l_indexref)] * twok * sin(acos(cos(calc.reflectivity(1,:))/l_indexref));
    phase=exp(1i*calc.Q(1,:,k+1)*layer(k).thickness(2));
    calc.exp_phase(:,:,k+1) = [phase;phase];
end

for k=length(sequence)-1:-1:1
    r = ((calc.Q(:,:,sequence(k))-calc.Q(:,:,sequence(k+1))) ./ (calc.Q(:,:,sequence(k))+calc.Q(:,:,sequence(k+1)))).* exp(-0.5*(calc.Q(:,:,sequence(k)).*calc.Q(:,:,sequence(k+1)))*layer(sequence(k+1)-1).roughness(2)^2);
    calc.R(:,:,k) = (r +calc.R(:,:,k+1) .* calc.exp_phase(:,:,sequence(k+1)))./ (1 + r .* calc.R(:,:,k+1) .* calc.exp_phase(:,:,sequence(k+1))) ;
end
calc.M_final(1,1,:) = calc.R(1,:,1); % 1,1 : sigma - sigma
calc.M_final(2,2,:) = calc.R(2,:,1); % 2,2 : pi - pi

end