% Cartoon of an angle-scanned XPD experiment. Data from Osterwalder/Greber
% group, University of Zurich
close all; clear

vid = VideoWriter('xpdMap.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);
LL = 1.05;

GeTe = importdata('GeTe_Te4s_626eV.dat'); % XPD data
GeTe = flip(GeTe,1);

% Steps in polar direction are constant and equal to 1 degrees. Upper and
% lower limits of each data pixel given by theta1 and theta2
theta = GeTe(:,2); % Polar angles
phi = (pi/180)*(360-GeTe(:,3)); % Azimuthal angles
len = size(phi,1); % Number of data points
% Detect data-point indices where new phi rotation begins 
kk = 1;
for ii = 1:len-1
    if (phi(ii+1) < phi(ii)) % New azimuthal scan detected
        phi0deg(kk) = ii;
        kk = kk+1;
    end
end

inty = GeTe(:,1); % Intensity values of data at theta, phi

hold off

% Color index for "rgb" to determine color of each data square based on its
% intensity
rgb = customcolormap([0 0.5 1],{'#ffff00','#ff0000','#000000'});
Call = zeros(len,3);
colIndex = round(256*(inty-min(inty))/(max(inty)-min(inty)));
for ii = 1:len
    if (colIndex(ii) == 0)
        colIndex(ii) = 1;
    end
    Call(ii,:) = rgb(colIndex(ii),:);
end
colormap(Call);

% OK. All prep stuff done. Now for the plotting...
pt1 = 2:2:phi0deg(3);
pt2 = phi0deg(4:end);
allphiIndex = [pt1 pt2 len];
% And we're off! On the way-out Wacky Races!
for jj = allphiIndex % Data point loop
    col = 1:jj;
    tic % Remove, also toc, if you're not obsessed with how terribly
    % long it takes to render this video. Planning to buy a new mac
    % soon...
    rho = sind(theta);
    if (jj <= phi0deg(3))
        polarscatter(phi(1:jj),theta(1:jj),80,Call(1:jj,:),...
            'filled')
        rlim("manual")
        rlim([0 90])
        
    else
        polarscatter(phi(1:jj),...
            theta(1:jj),80,...
            Call(1:jj,:),'filled')
        rlim("manual")
        rlim([0 90])
        
    end
    set(gca,'fontsize',16)
    set(gca,'linewidth',1.6)
    
    frame = getframe(gcf);
    writeVideo(vid,frame);
    if (jj > phi0deg(3))
        pauseMov(vid,1)
    end
    rlim("manual")
    rlim([0 90])
    toc
    
end % End data point loop
close(vid)