% Movie plotting out the spectra of a U14 undulator at SLS as a function of
% electron-beam emittance 
% Comment out "hold on" to get individual spectra per frame instead of
% accumulated spectra 

clear; close all; 

vid = VideoWriter('IDspectraVemittance.mp4','MPEG-4'); 
vid.Quality = 100; 
vid.FrameRate = 10; 
open(vid); 
figure('units','pixels','position',[0 0 1920 1080],'ToolBar','none'); 
set(0,'defaultfigurecolor',[1 1 1]);

% Create rgb progression through a rainbow 
bot = 8:8:128; % 0 to 7f in 16 steps 
top = 128:8:248; % 80 to ff 
all = 0:16:240; % 0 to ff 
botc = 0*all; % vector of zeros 
midc = botc + 127; % vector of 127s 
topc = botc + 255; % vector of 255s 
rcomp = [top topc topc flip(all) botc botc bot flip(bot)]/256; % R in rgb 
gcomp = [botc bot top flip(top) midc flip(bot) botc botc]/256; % G in rgb 
bcomp = [botc botc botc botc bot midc midc flip(bot)]/256; % B in rgb 

str7 = '{\epsilon_x^e} = ';
str8 = ' pm.rad'; 
str4 = 'Flux into 38 x 38 {\mu}rad^2'; 
str5 = 'U14 CPMU'; 

N = 101;
for ii = 1:N 
    if (ii>1)
        delete(hText);
        delete(hText2);
        delete(hText3); 
    end

    % Comment out 'hold off' if you want accumulated plots but simply a 
    % single spectrum per frame
    % hold off
    str1 = 'IDspectra/';
    str2 = num2str(sprintf('%03d',ii)); 
    str3 = '.dat';
    strTot = [str1,str2,str3];
    M = dlmread(strTot, ' ', 2, 0); % Read in file, ignore first two lines 
    semilogy(M(:,1)/1000.0,M(:,3),...
        'color',[rcomp(ii+10) gcomp(ii+10) bcomp(ii+10)], 'LineWidth', 2); 
    hold on
    str6 = num2str(5500 - ((ii-1)*(5360/(N-1))),'% 7.1f'); 
    strTot3 = [str7,str6,str8]; 
    hText = text(22, 5e13, strTot3, 'FontSize',28,...
        'color',[rcomp(ii+10) gcomp(ii+10) bcomp(ii+10)]); 
    hText2 = text(22, 1.5e14, str4, 'FontSize',28);     
    hText3 = text(22, 4.0e14, str5, 'FontSize',28); 
    
    set(gca,'FontName','Helvetica','fontsize',28);
    set(gca,'TickLength',[0.016, 2]); 
    set(gca,'linewidth',2); 
    set(gca,'XMinorTick','on');
    xlim([1 30]);
    ylim([3e9 5e15]);
    xlabel('Photon energy [keV]');
    ylabel('Flux ph/s/0.1% BW'); 
    hold on
    % Store the frame
    frame = getframe(gcf); 
    writeVideo(vid,frame); 
end 
% Output the movie as an mpg file
close(vid);
