clear; close all; clc;

%% Load the data
load('spatiotemporal_mfe.mat');
[height,width,N] = size(tstack);
tstack = double(tstack);
time = (0:N-1).*dt;
xf = (0:(width-1)).*dx*1e6; % space axis for fluorescence intensity

figure(1); clf;
stack_viewer(tstack);
colormap(viridis);

%% Select crystal ROI
frame = tstack(:,:,1);
roi = frame>mean(frame(:))-std(frame(:));

% Plot
figure(2); clf;
s = subplot(1,2,1);
imagesc(frame); colormap(viridis);
grid on; box on; axis square;
s.XTickLabel = ''; s.YTickLabel = ''; title('frame 1');

s = subplot(1,2,2);
spy(roi);
grid on; box on; axis square;
s.XTickLabel = ''; s.YTickLabel = ''; title('ROI');

%% Pixsum through the region of interest
pixsum = tstackfun(tstack,@(frame) mean(frame(roi)));

% Plot
figure(3); clf
plot(time,pixsum,'k-');
xlim([min(time) max(time)]);
grid on; box on; axis square;
xlabel('time / s'); ylabel('Intensity / counts');
title('Average pixel intensity');

%% Slice into segments
offset = 13; segment_length = 20; dead_points = 1; % Splitting parameters
n_segments = floor((N-offset)/(2*segment_length))*2; % Number of u/d segments
trim_region = (1+offset):n_segments/2*(2*segment_length)+offset;
% Slice pixsum
pixsum_segments = reshape(pixsum(trim_region),segment_length,n_segments);
pixsum_segments = pixsum_segments((1+dead_points):(end-dead_points),:);
% Slice time
time_segments = reshape(time(trim_region),segment_length,n_segments);
time_segments = time_segments((1+dead_points):(end-dead_points),:);

% Plot
figure(4); clf; hold on;
cm = lines;
%plot(time,pixsum,'k-');
plot(time_segments(:,1:2:end),pixsum_segments(:,1:2:end),'.','color',cm(2,:)); % Up steps
plot(time_segments(:,2:2:end),pixsum_segments(:,2:2:end),'.','color',cm(1,:)); % Down steps
xlim([min(time) max(time)]);
grid on; box on; axis square;
xlabel('time / s'); ylabel('Intensity / counts');
title('Average pixel intensity split into segments');

%% Spatiotemporal MFE
% Bin the tstack into 4x4 pixels
binstack = tstackfun(tstack,@(frame) imresize(frame,1/4));
% Calculate time-resolved MFE for each bin
MFE = zeros(size(binstack,1),size(binstack,2),numel(time_segments(:,2:end-1)));
for ni = 1:size(binstack,1)
    for mi = 1:size(binstack,2)
        slice = squeeze(binstack(ni,mi,:)); % Select slice
        % Split slice into segemnts
        slice_segments = reshape(slice(trim_region),segment_length,n_segments);
        slice_segments = slice_segments((1+dead_points):(end-dead_points),:);
        % Calculate mfe
        mfe = []; udu = true;
        for j = 1:(n_segments-2) % For each triplet of segments
            y = slice_segments(:,[j j+2]); x = time_segments(:,[j j+2]);
            P = polyfit_fast(x(:),y(:),2); % Fit a quadratic to outer segments
            on = slice_segments(:,j+1); off = polyval_fast(P,time_segments(:,j+1))';
            if udu, [on,off] = deal(off,on); end  % off is interpolated, therefore swap to divide by the corect segment
            m = on./off - 1; % (on-off)/off = on/off - 1
            udu = ~udu; mfe = [mfe; abs(m)];
        end
        MFE(ni,mi,:) = mfe;
    end
end
MFE = MFE*100; % Conver to percentage
MFE_time = time_segments(:,2:(end-1)); MFE_time = MFE_time(:); % MFE time axis
xm = linspace(min(xf),max(xf),size(MFE,1)); % space axis for MFE

% Plot
figure(4); clf;
MFE_smooth = tstackfun(MFE,@(frame) imgaussfilt(frame,0.5));
[~,I] = min(abs(MFE_time-45)); % Trim forst 45 secconds (fitting of the steps is unreliable)
stack_viewer(MFE_smooth(:,:,I:end),[0 3]);
colormap(plasma);

%% Take slices through the intensity 
smoothing_processfun = @(frame) imgaussfilt(frame,0.5);
intensity_slices = tstackfun(tstack,smoothing_processfun);
MFE_slices = tstackfun(MFE,smoothing_processfun);

p1 = 1+1i; p2 = width+height.*1i;
lf = linspace(p1,p2,ceil(norm(p2-p1))); % Line from p1 to p2
intensity_slice_processfun = @(frame)...
    interp2(1:width,1:height,frame,real(lf)',imag(lf)','linear',NaN);
intensity_slices = tstackfun(intensity_slices,intensity_slice_processfun);
xfd = abs(lf-lf(1))*dx*1e6; % x-axis for fluorescence through the diagonal

p1 = 1+1i; p2 = size(MFE,2)+size(MFE,1).*1i;
lm = linspace(p1,p2,ceil(norm(p2-p1))); % Line from p1 to p2
mfe_slice_processfun = @(frame)...
    interp2(1:size(MFE,2),1:size(MFE,1),frame,real(lm)',imag(lm)','linear',NaN);
MFE_slices = tstackfun(MFE_slices,mfe_slice_processfun);
xmd = linspace(min(xfd),max(xfd),numel(lm));

% Plot
figure(5); clf;
s = subplot(2,1,1);
imagesc(time,xfd,intensity_slices);
colormap(s,viridis);
caxis([20 70]);
xlabel('time / s'); ylabel('slice distance / um');

s = subplot(2,1,2);
imagesc(time,xmd,MFE_slices);
colormap(s,plasma);
caxis([0 3]);
xlabel('time / s'); ylabel('slice distance / um');

%% Plot figure from the paper
% 1st intensity time bin (1st-2nd minute (+45s offset))
[~,If1] = min(abs(time-(1*60+45))); [~,If2] = min(abs(time-(2*60+45)));
[~,Im1] = min(abs(MFE_time-(1*60+45))); [~,Im2] = min(abs(MFE_time-(2*60+45)));
% 1st intensity time bin (4th-5th minute (+45s offset))
[~,If3] = min(abs(time-(4*60+45))); [~,If4] = min(abs(time-(5*60+45)));
[~,Im3] = min(abs(MFE_time-(4*60+45))); [~,Im4] = min(abs(MFE_time-(5*60+45)));

clear s;
cm = [22 22 117; 54 165 76; 229 235 41; 243 124 24; 198 22 107; 117 17 112]/255;

figure(6); clf;
s(1) = subplot(2,3,1);
imagesc(xf,xf,mean(tstack(:,:,If1:If2),3));
colormap(s(1),viridis);
box on; axis square;
caxis([20 60]);
    
s(2) = subplot(2,3,2); hold on;
imagesc(xf,xf,mean(tstack(:,:,If3:If4),3));
colormap(s(2),viridis);
box on; axis square;
plot(xf,xf,'w--','LineWidth',1.5); s(2).YDir = 'reverse';
xlim(minmax(xf)); ylim(minmax(xf)); caxis([20 60]);

s(3) = subplot(2,3,3); hold on;
for j = 1:6
    [~,I1] = min(abs(time-((j-1)*60+45))); [~,I2] = min(abs(time-((j)*60+45)));
    frame = mean(tstack(:,:,I1:I2),3); % Average frame
    frame = smoothing_processfun(frame);
    plot(xfd,intensity_slice_processfun(frame),'color',cm(j,:));
end
xlim(minmax(xfd));
ylim([20 70]);
grid on; box on; axis square;
xlabel('slice distance / um'); ylabel('I / counts');

s(4) = subplot(2,3,4);
imagesc(xm,xm,mean(MFE(:,:,Im1:Im2),3));
colormap(s(4),plasma);
box on; axis square;
caxis([0 3]);

s(5) = subplot(2,3,5); hold on;
imagesc(xm,xm,mean(MFE(:,:,Im3:Im4),3));
colormap(s(5),plasma);
box on; axis square;
plot(xm,xm,'w--','LineWidth',1.5); s(5).YDir = 'reverse';
xlim(minmax(xm)); ylim(minmax(xm)); caxis([0 3]);


s(6) = subplot(2,3,6); hold on;
for j = 1:6
    [~,I1] = min(abs(MFE_time-((j-1)*60+45))); [~,I2] = min(abs(MFE_time-((j)*60+45)));
    frame = mean(MFE(:,:,I1:I2),3);
    frame = smoothing_processfun(frame);
    plot(xmd,mfe_slice_processfun(frame),'color',cm(j,:));
end
xlim(minmax(xmd)); ylim([0 3]);
grid on; box on; axis square;
xlabel('slice distance / um'); ylabel('I / counts');

% Add labels
for j = 1:2
    if j == 1; text = '1 min';
    else, text = '4 min';
    end
title(s(j),text);
s(j).Title.Units = 'normalized';
s(j).Title.HorizontalAlignment = 'right';
s(j).Title.VerticalAlignment = 'top';
s(j).Title.Position = [0.95 0.95 0];
s(j).Title.Color = 'w';
end

% Add colorbars
drawnow;
s(1).YTickLabel = ''; s(2).YTickLabel = '';
temp = s(1).Position;
cb = colorbar(s(1)); cb.Location = 'westoutside'; cb.Label.String = 'I / counts';
s(1).Position = temp;

s(4).YTickLabel = ''; s(5).YTickLabel = '';
temp = s(4).Position;
cb = colorbar(s(4)); cb.Location = 'westoutside'; cb.Label.String = '% MFE';
s(4).Position = temp;
