clear; close all
figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none');
vid = VideoWriter('Fresnel2Fraunhofer.mp4','MPEG-4');
vid.FrameRate = 30;    % Default 30
vid.Quality = 100;    % Default 75
open(vid);
set(0,'defaultfigurecolor',[1 1 1]);

str1 = 'd/a = ';
str3 = 'F = a^2/(4\lambdad) = ';
str5 = 'a/\lambda = ';

lambda = 2; % x-ray wavelength in Angstroms
k = 2*pi/lambda; % Wavevector
a = 1000; % Aperture width in Angstroms
str6 = num2str(a/lambda,'%-4.0f');

expVal = 1*log10(30):0.0025:log10(5000); % Exponential increase in each step 
propSteps = 10.^(expVal);

maxd = a*max(propSteps); 
xsmax = 5*maxd*lambda/a;
xsRange0 = -xsmax:xsmax/250:xsmax;

ii = 1;
for xs = xsRange0    
    sum2 = 0; % Initialize integrating sum from 0 to a for a given xs for Fraunhofer approximation
    for xx = -a/2:a/1000:a/2 % Integrate across aperture between 0 and a over 1000 steps
        sum2 = sum2 + exp(-1j*k*(xs^2)/(2*maxd))*exp(1j*k*xs*xx/maxd);
    end
    fraun(ii) = (abs(sum2))^2;
    ii = ii+1;
end

for d = a*propSteps % From screen being 30 to 5000 times a away from aperture in exponential steps
    F = a^2/(4*lambda*d); % Fresnel number 
    str4 = num2str(F,'%-4.3f');
    xsmax = 5*d*lambda/a;
    ii = 1;
    str2 = num2str(d/a,'%-4.2f');
    xsRange = -xsmax:xsmax/250:xsmax;
    for xs = xsRange
        sum1 = 0; % Initialize integrating sum from 0 to a for a given xs for quasi exact Fresnel equation
        for xx = -a/2:a/1000:a/2 % Integrate across aperture between -a/2 and a/2 over 1000 steps
            r = (d^2 + (xs - xx)^2)^0.5;
            sum1 = sum1 + (a/1000)*(exp(-k*1j*r)/r);
        end
        intensity(ii) = (abs(sum1))^2;
        ii = ii+1;
    end
    plot(xsRange,intensity/max(intensity),'b','LineWidth', 2.0)
    hold on
    plot(xsRange,fraun/max(fraun),'r','LineWidth', 2.0)

    xlim([-xsmax xsmax]);
    ylim([0 1]);
    text(0.75*xs, 0.75, [str1,str2], 'FontSize',22);
    text(0.75*xs, 0.71, [str3,str4], 'FontSize',22);
    text(0.75*xs, 0.79, [str5,str6], 'FontSize',22);

    axis off

    frame = getframe(gcf);
    writeVideo(vid,frame);
    hold off
end
% Output the movie as an mp4 file and close it
close(vid);