%% Curve Fitting
close all;
clear all;
clc;
%% setting
border = 15;                % remove border pixels
Smo = 3;                    % spatial smooth
window = 100;               % movmean window for extract high-frequency component
bleachCorrection = false;    % whether to correct bleach

%% file path
folderName = 'D:\Datasets and Projects\Kira''s Group\Michael\HighSNR\'; % file
fName = '2x_150um_reg_DualwLEP_30min_Ch1_moco.tif';
pOut = 'D:\';  % output folder

%% read tif
dataOrg = readTif([folderName,fName]);
dataOrg = single(dataOrg(border+1:end-border,border:end-border,:)); % remove border, select target duration
[H,W,T] = size(dataOrg);
% selectDuration = 1:T;    % the target duration to observe
% dataOrg = dataOrg(:,:,selectDuration);

%% average projection
datMean = mean(dataOrg,3);
datMean = datMean - min(datMean(:));
datMean = datMean/max(datMean(:));

%% preprocessing debleach
if(Smo == 0)
    data = dataOrg;
else
    data = imgaussfilt(dataOrg,Smo);
end

if(bleachCorrection)
    data  = preprocessDebleach(data,datMean);                 % remove bleaching
else
    data = reshape(data,[],T);
end

%% Correcting
[datCorrect,weights,hfc] = correctHemodynamic(data,datMean,window);                 % linear regression to fit
datCorrect = reshape(datCorrect,[H,W,T]);

%% Output
writeTif( [pOut,fName(1:end-4),'Correct.tif'], datCorrect, 1 );


