clear; close all; clc;

%% Load the data
load('fmnhewl_solution.mat');
[height,width,N] = size(tstack);
tstack = double(tstack);
time = (0:N-1).*dt; % time axis
xf = (0:(width-1)).*dx*1e6; % space axis for fluorescence intensity

% Frame size is large, therefore scale down for easier viewing
tstack_small = tstackfun(tstack,@(frame) imresize(frame,1/4));
figure(1); clf;
stack_viewer(tstack_small,'fix');
colormap(viridis);

%% Slice average pixel intensity into segments
pixsum = tstackfun(tstack,@(frame) mean(frame(:))); % Average pixel intensity in each frame

offset = 33; segment_length = 30; 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),:);

%% Find the centerline between the segments
% Find center points
cp = [];
for j = 1:n_segments-1
    P1 = polyfit_fast(time_segments(:,j),pixsum_segments(:,j),2); % Fit j'th segment
    P2 = polyfit_fast(time_segments(:,j+1),pixsum_segments(:,j+1),2); % Fit j+1'st segment
    x = (time_segments(end,j) + time_segments(1,j+1))/2; % Intermediate time point
    y = (polyval_fast(P1,x) + polyval_fast(P2,x))/2; % Average of poly. fits
    cp(j) = x + 1i*y;
end
%cp = diff(cp)/2 + cp(1:end-1); % Find baseline points
cfit = @(x) interp1(real(cp),imag(cp),x,'pchip'); % Interpolating fun.

figure(2); clf; hold on;
cm = lines;
plot(time,cfit(time),'-','color',[1 1 1]*0.2);
plot(cp,'x','color',[1 1 1]*0.2);
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
grid on; box on; axis square;
xlabel('time / s'); ylabel('Intensity / counts');
title('Intensity segments + centerline');

%% Subtract the centerline from pixel intensity
steps = pixsum-(cfit(time'));

steps = reshape(steps(trim_region),segment_length*2,n_segments/2);
steps = steps((1+dead_points):(end-dead_points),:);

time_steps = reshape(time(trim_region),segment_length*2,n_segments/2);
time_steps = time_steps((1+dead_points):(end-dead_points),:);

cm = lines;
figure(3); clf; hold on;
plot(time,zeros(size(time)),'k--');
plot(time_steps,steps,'-','color',cm(5,:)); % Up steps
ylim([-1 1]*2);
grid on; box on;
xlabel('time / s'); ylabel('\Delta Intensity / counts');
title('Intensity variation wrt. the centerline');

%% Find average %MFE step
average_off_step = steps(2:28,3:end-2); % Discard first and last two steps (poor centerline fitting)
average_off_step = mean(average_off_step(:));

mfe_steps = (pixsum./(cfit(time')+average_off_step) - 1)*100; % Use shifed centerline as the off data

mfe_steps = reshape(mfe_steps(trim_region),segment_length*2,n_segments/2);
mfe_steps = mfe_steps((1+dead_points):(end-dead_points),:);

average_mfe_step = mean(mfe_steps(:,2:end-1),2); % Average step
spread_mfe_step = std(mfe_steps(:,2:end-1),[],2)./sqrt(size(mfe_steps,2)-2); % Standard error of the mean
time_amfe = time_steps(:,1)-time_steps(1,1)+1.5;

%%
% p(1) = period, p(2) = upper level, p(3) = lower level, p(4) = phase
m = @(x,p) (p(3)-p(2)).*(sin(2*pi*x./p(1) + p(4))>0) + p(2); % Model
fitfun = @(p) mean( (average_mfe_step - m(time_amfe,p)).^2 );
p0 = [60 -1.2 0 0];
pf = fminsearch(fitfun,p0);

time_dense = linspace(-5,65,2e2); % Dense time axis for prettier plot
figure(4); clf; hold on;
plot(time_dense,zeros(size(time_dense)),'k--');
kernel = @(N) exp(-linspace(-2,2,N).^2)/sum(exp(-linspace(-2,2,N).^2)); % Normalised smoothing kernel
plot(time_dense,conv(m(time_dense,pf),kernel(11),'same'),'k-');
errorbar(time_amfe,average_mfe_step,spread_mfe_step,'.','color',cm(5,:),'MarkerSize',10);
xlim([0 60]); ylim([-1.5 0.2]);
grid on; box on; axis square;
ylabel('% MFE'); xlabel('step time / s');

%% Plot figure from the paper
cm = lines;

clear s;
figure(5); clf;
s(1) = subplot(2,1,1); hold on;
%plot(time,pixsum,'k-');
plot(time,cfit(time),'-','color',[1 1 1]*0.2);
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([0 1e3]); ylim([45 120]);
grid on; box on; axis square;
xlabel('time / s'); ylabel('Intensity / counts');

s(2) = subplot(2,1,2); hold on;
plot(time_dense,zeros(size(time_dense)),'k--');
kernel = @(N) exp(-linspace(-2,2,N).^2)/sum(exp(-linspace(-2,2,N).^2)); % Normalised smoothing kernel
plot(time_dense,conv(m(time_dense,pf),kernel(11),'same'),'k-');
errorbar(time_amfe,average_mfe_step,spread_mfe_step,'.','color',cm(5,:),'MarkerSize',10);
xlim([0 60]); ylim([-1.5 0.2]);
grid on; box on; axis square;
ylabel('% MFE'); xlabel('step time / s');

% Add subplot
s(3) = copyobj(s(1),gcf);
s(3).PlotBoxAspectRatioMode = 'auto';
s(3).Position = [0.46 0.78 0.17 0.12];
s(3).XTickLabel = ''; s(3).YTickLabel = '';
xlabel(s(3),''); ylabel(s(3),'');
xlim(s(3),[680 780]); ylim(s(3),[51 53]);