function [P_out, Theta, Y] = computePolarizationAnalytic(r, B, wavelength)
%% [P_out, Theta, Y] = computePolarizationAnalytic(r, B, wavelength)
%  
% Solution analytique de la précession du neutron dans le cas d'une 
% aimanation du fil M purement selon z et donc sans champ de fuite puisque
% le fil est cionsidéré en première approximation comme de longeur inifinie
%
%
% $Revision: 11 $
% $Author: lenertz $
% $Date: 2015-07-10 14:32:19 +0200 (ven., 10 juil. 2015) $

M = [0,0,0.6]; % en Tesla

masse_neutron = 1.67493e-27; %masse du neutron en Kg
h_plank = 6.6260688e-34; % constante de plank en J.s
neutron_speed = h_plank / (masse_neutron * wavelength);
gamma_n =1.833e8;    % rapport gyromagnetique du neutron
Y = -1.5*r:r/100:1.5*r;

P_in = B/norm(B);
P_out(1:numel(Y)) = 0;
Theta = P_out;
H = M+B;

for index = 1:numel(Y);
    y = Y(index);
    if y <= r && y >= -r;
        theta = 2*sqrt(r^2 - y.^2) * gamma_n * norm(H) / (neutron_speed);
        p_out = rotGeneral(P_in, H, theta);
        Theta(index) = theta;
        P_out(index) = vectorAngles(p_out, B);
    else
        P_out(index) = 0;
        Theta(index) = 0;
        
    end
    
   

end

figure;
plot(Y,cos(P_out));
ylim([-1.1,1.1])

% Save
ST_folderName = 'D:\Data simul mag\magneticWire\';
ST_subFolderName = strcat(['B=(',...
                          num2str(B(1)),' ',...
                          num2str(B(2)),' ',...
                          num2str(B(3)),') M=(',...
                          num2str(M(1)),' ',...
                          num2str(M(2)),' ',...
                          num2str(M(3)),') analytique']);
ST_saveFolder = strcat(ST_folderName,ST_subFolderName,'\')
if not(exist(ST_subFolderName,'dir'))
    mkdir(ST_saveFolder)
end
title(ST_subFolderName)
fileName = strcat(ST_saveFolder,'Data','.mat');
save(fileName,...
    'r',...
    'B',...
    'wavelength',...
    'P_out',...
    'Theta',...
    'Y',...
    'M',...
    'B')
%figName = strcat(ST_saveFolder,'fig','.m')
%savefig(figName)

beamWidthMean(Y,P_out,50e-6);

end