close all; clear; clc;

%% Load data
load('FRAP.mat');

% Frame size is large, therefore scale down for easier viewing
tstack = tstackfun(tstack,@(frame) imresize(frame,1/4));
figure(1); clf;
stack_viewer(tstack,'fix');
colormap(viridis);

[height,width,N] = size(tstack);
tstack = double(tstack);
time = (0:N-1).*dt; % time axis
xf = (0:(width-1)).*dx*1e6*4; % space axis for fluorescence intensity
xf = xf-mean(xf);

%% Bleach and outside ROIs
frame = tstack(:,:,2); n = size(tstack,1);
roi_bleach = false(size(frame));
region_y = (round(n/3)+2):(round(2*n/3)-2); % Middle 1/3rd + 2 pixels padding
roi_bleach(region_y,region_y) = true;

roi_outside = false(size(frame));
region_y = [(1:round(n/3)-2) (round(2*n/3)+2):n]; % Outside 1/3rd + 2 pixels padding
roi_outside(region_y,:) = true; roi_outside(:,region_y) = true;

figure(2); clf;
subplot(1,3,1);
imagesc(xf,xf,tstack(:,:,2));
box on; axis square;
colormap(viridis);
xlabel('x / um'); ylabel('y / um');
title('First post-bleach frame');

s = subplot(1,3,2);
spy(roi_bleach);
box on; axis square;
s.XTickLabel = ''; s.YTickLabel = ''; xlabel(s,'');
title('Bleach region');

s = subplot(1,3,3);
spy(roi_outside);
box on; axis square;
s.XTickLabel = ''; s.YTickLabel = ''; xlabel(s,'');
title('Outside region');

%% Plot bleaching recovery corrected for bleaching of the whole frame over the course of the experiment
outside_pixsum = tstackfun(tstack,@(x) mean(x(roi_outside))); % Outside bleach
bleach_pixsum = tstackfun(tstack,@(x) mean(x(roi_bleach))); % Bleached ROI

recovery_curve = bleach_pixsum - outside_pixsum + outside_pixsum(1); % Correct for photobleach
recovery_curve = (recovery_curve )/outside_pixsum(1); % Normalise to 1st frame

figure(3); clf;
plot(time,recovery_curve);
grid on; box on; axis square;
xlabel('time / s'); ylabel('fractional intensity');

%% Prepare data for error fit of the edge of the ROI 

region_y = (round(n/3)+2):(round(2*n/3)-2); % Middle 1/3rd + 2 pixels padding
processfun = @(frame) [frame(region_y,1:n/2); fliplr(frame(region_y,(n/2+1):end))];
edgestack = tstackfun(tstack,processfun); % Left and right edges put together
processfun = @(frame) mean(frame,1);
edges = tstackfun(edgestack,processfun);
xe = xf(1:n/2); % x-axis for the edge of the bleach region

figure(4); clf;
stack_viewer(edgestack,'fix')
colormap(viridis);

figure(5); clf;
imagesc(time,xf,edges);
colormap(viridis);
cb = colorbar; cb.Label.String = 'Intensity / Counts';
grid on; box on; axis square;
xlabel('time / s'); ylabel('x / um');
title('Average edges of the bleach region');

%% Fit error function to edges

m = @(x,p) (p(4)-p(3))*(1-erf((xe-p(1))/(2*sqrt(p(2)))))/2 + p(3);
options = optimset('MaxFunEvals',1e6,'MaxIter',1e6);
for j = 2:N
    edge = edges(:,j)';
    p0 = [-20 1 edge(end) edge(1)];
    fitfun = @(p) mean((edge-m(xe,p)).^2);
    pf = fminsearch(fitfun,p0,options);
    C(j) = pf(2);
    
    if time(j) > 400, break; end
    if~mod(j,10)
        figure(6); clf; hold on;
        plot(xe,edge,'o',xe,m(xe,p0),'k--',xe,m(xe,pf),'k-');
        xlim(minmax(xe));
        grid on; box on; axis square;
        xlabel('x / um'); ylabel('I / counts');
    end
end
C(1) = NaN; time_C = time(1:numel(C));

%% Fit inital gradient of C
region = time_C>0 & time_C<150;
P = polyfit(time_C(region),C(region),1);

figure(7); clf; hold on;
plot(time_C,C,'o','MarkerSize',4);
plot(time_C,polyval(P,time_C));
xlim([0 400]); ylim([0 100]);
xlabel('time / s'); ylabel('C / \mum^2');
grid on; box on; axis square;
title(sprintf('D = %0.2e m^2 s^{-1}, b = %0.2f um^2',P(1)/1e12,P(2)));

%% Plot figure from the paper
clear s;
figure(8); clf;
colormap(viridis);

[~,I1] = min(abs(time-2*60));
[~,I2] = min(abs(time-10*60));

s(1) = subplot(2,3,1);
imagesc(imresize(tstack(:,:,2),1/2));
axis square; box on;
s(1).XTickLabel = ''; s(1).YTickLabel = '';

s(2) = subplot(2,3,2);
imagesc(imresize(tstack(:,:,I1),1/2));
axis square; box on;
s(2).XTickLabel = ''; s(2).YTickLabel = '';

s(3) = subplot(2,3,3);
imagesc(imresize(tstack(:,:,I2),1/2));
axis square; box on;
s(3).XTickLabel = ''; s(3).YTickLabel = '';

s(4) = subplot(2,3,4); hold on;
plot(time,recovery_curve);
plot([1 1]*time(I1),[0.5 1],'k--');
plot([1 1]*time(I2),[0.5 1],'k--');
grid on; box on; axis square;
xlabel('time / s'); ylabel('fractional intensity');
xlim([0 800]); ylim([0.5 1]);

s(5) = subplot(2,3,5);
edge = edges(:,2)'; edge = (edge-edge(end))./(edge(1)-edge(end));
m = @(x,p) (1-erf((xe-p(1))/(2*sqrt(p(2)))))/2;
fitfun = @(p) mean((edge-m(xe,p)).^2);
p0 = [-20 1];
pf = fminsearch(fitfun,p0,options);

plot(xe,edge,xe,m(xe,pf));
xlim([-40 0]); ylim([-0.1 1.1]);
grid on; box on; axis square;
xlabel('x / um'); ylabel('Norm. Intensity');
s(5).YTickLabel = '';

s(6) = subplot(2,3,6); hold on;
plot(time_C,C,'.','MarkerSize',6);
plot(time_C,polyval(P,time_C));
xlim([0 400]); ylim([0 100]);
xlabel('time / s'); ylabel('C / \mum^2');
grid on; box on; axis square;

