% Program plotting the CTR intensity as a function of l and displacement
% dz of the top atomic layer of an elemental simple cubic lattiice between 
% +/- 5%. On the right the movement of this layer is shown, but exaggerated
% by a factor of 5. 

close all
vid = VideoWriter('CTRvSurfaceDilation.mp4','MPEG-4');
vid.Quality = 100;
vid.FrameRate = 30;
open(vid);

figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none');
set(0,'defaultfigurecolor',[1 1 1]);
set(gca,'linewidth',7);

lp = [0. 0. 0.2];
myBlue = [0.32 0.35 0.7];
lightblue = [0.64 0.77 1];
light('Position',lp,'Style','infinite');

pos1 = [0.1 0.1 0.5 0.8]; % Top left 3D cartoon
pos2 = [0.64 0.1 0.35 0.8]; % Bottom left EXAFS plot 

str1 = '\delta = ';
str3 = ' %';

[xx,yy,zz] = sphere(50);  
r1 = 0.35; 

z01 = 0:0.0005:0.05; 
z02 = 0.049:-0.0005:-0.05; 
z03 = -0.049:0.0005:0; 
z0 = [z01 z02 z03]; 
l = 0:0.005:3;
for z = z0
    subplot('Position',pos1); 
    newplot 
    F0ctr = (1 - exp(1i*2*pi*l)).^-1 + exp(-1i*2*pi*l);
    I0ctr = (abs(F0ctr)).^2;
    Fctr = (1 - exp(1i*2*pi*l)).^-1 + exp(-1i*2*pi*(1+z)*l);
    Ictr = (abs(Fctr)).^2;
    hold off
    plot(l,log10(I0ctr),'color',lightblue, 'Linewidth', 2)
    hold on
    plot(l,log10(Ictr),'color',myBlue, 'Linewidth', 2)
    set(gca,'fontsize',25,'linewidth',2);

    ylim([-2,3]) 
    xlabel('l [r.l.u.]');
    ylabel('log_{10}(CTR intensity)'); 
    
    str2 = num2str(z*100,'% 4.2f'); 
    strTot = [str1,str2,str3]; 
    hText = text(0.5, -1.25, strTot, 'FontSize',25); 

    
    subplot('Position',pos2); 
    newplot 
    hold off 
    for atomRow = -3:3 
        hold on
        surf(xx*r1+atomRow,yy*r1,zz*r1,'FaceColor',myBlue,... 
                'EdgeColor','none','FaceLighting','gouraud','FaceAlpha',0.2);
    end 
    
    for atomCol = 0:-1:-5 
        for atomRow = -3:3 
            if (atomCol == 0)
            surf(xx*r1+atomRow,yy*r1,zz*r1+atomCol+z*5,'FaceColor',myBlue,... 
                'EdgeColor','none','FaceLighting','gouraud','FaceAlpha',1+atomCol/5.5);
            else 
                surf(xx*r1+atomRow,yy*r1,zz*r1+atomCol,'FaceColor',myBlue,... 
                'EdgeColor','none','FaceLighting','gouraud','FaceAlpha',1+atomCol/5.5);
            end 
        end 
    end 
    axis off;
    axis equal; 
    light('Position',lp,'Style','infinite');
    set(gca, 'Projection','perspective');
    xlim([-4 4]);
    ylim([-1 1]);
    zlim([-6 1]);
    view(0,0);

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