% Random walk (RW) in a finite slab 
% All lengths (Lz, R, ell, x0, y0) have to be given in the same unit: e.g in 1/k. 
% The outputs are: the Trajectory, the number of scattering events Nsc (0 for transmitted photons), the output angles theta, phi, the output positions x, y

clear all;
% Parameters of the slab
Lz=5; % length of the slab (e.g. Lz=5)
R=10; %transverse size     (e.g. R=10)
ell=1; %scattering mean free path   (e.g. ell=1)

Nph=10; % number of photons
for iph=1:1:Nph  %loop on different photons injected in the slab
 clear X Y Z

% Initial Conditions 
Nsc=1;  % number of scattering events already done
cos_phi = 1; theta=0; % direction of inicident propagation
x=0; %initial position along x
y=0; %initial position along y
z=0; % Initial impact with the vapor (NOT the 1st scattering event!)
r=sqrt(x^2+y^2);

% length of the 1st step using an exponential distribution (Beer-Lambert)
step = -ell*log(rand);  % use the inverse function f^(-1) to draw the random number following a distribution f: exp -> log

% The first step is ballistic in forward direction   
z = z+step;
    % register position of the photon after this first step
    X(Nsc) = x; 
    Y(Nsc) = y;
    Z(Nsc) = z;
    
    
while all(z<=Lz  && z>0  && r<R) % Next scattering event inside the slab
     
    % draw a new random direction
    theta = 2*pi*rand;
    cos_phi = -1+2*rand;  % uniform between -1 and 1 (always  check that the distribution is uniform: mistakes often happen with cos, sin etc)
    sin_phi = sqrt(1-cos_phi^2);  % always >0 since phi is between 0 and pi
    
    % length of the next step in an exponential ditribution (Beer-Lambert)
    step = -ell*log(rand);  

    % new position
    x = x + step*sin_phi*cos(theta);   
    y = y + step*sin_phi*sin(theta);
    z = z + step*cos_phi;
    r = sqrt(x^2+y^2);

    % register the next steps (trajectory)
    Nsc = Nsc+1;  % add 1 to number of scattering events
    X(Nsc) = x;
    Y(Nsc) = y;
    Z(Nsc) = z;
   
end
phi = acos(cos_phi); %outgoing angle


% plotting the trajectory (for illustration)


 %plot an indication of the contour of the slab
 Rc=[R R];
 N=1000;
 [Xc,Yc,Zc] = cylinder(Rc,N);
 surf(Xc,Yc,Lz*Zc, 'edgecolor','none'); alpha(0.1); %indiction of slab
 hold on; 
 %plot trajectory
 plot3([0 X], [0 Y], [0 Z]), xlabel('x/l'), ylabel('y/l'), zlabel('z/l'), axis([-R R -R R -2 Lz+2]); 
 pause(1);
 close(gcf);
 
end;


