%% Příprava workspace
clear all;
clc;
close all;

%% Simulovaná data
load('SyntheticEchoes_cartesian_reco');
load('SyntheticEchoes_cartesian_ReferenceMaps');

%% Převedení buňky do 4D matice (x,y,z,čas)
nSlices=size(data2,1);
nSamples=size(data2,2);
[nRows,nCols]=size(data2{1,1});
data4D=zeros(nRows,nCols,nSlices,nSamples);
for sl=1:nSlices
    for t=1:nSamples
        data4D(:,:,sl,t)=imrotate(data2{sl,t},90);
    end
end

outputFolder=[];
nSamples=size(data4D,4);
timeAxis=(0:1:nSamples-1)*info.acq.Ts/60;
Ts = info.acq.Ts;

data = data4D;

%% Simul
data2D=DataCells2Mat(data2);

mean_baseline = mean(data2D(:,:,:,1:15),4);
%% Převod pro simul
for i = 1:size(data2D,4)
data(:,:,:,i) = (data2D(:,:,:,i)-mean_baseline)./mean_baseline;
end

data4D = data;

mean_baseline = mean(SIs(:,:,1:2000),3);
%% Převod pro simul
for i = 1:size(SIs,3)
SIs_1(:,:,i) = (SIs(:,:,i)-mean_baseline)./mean_baseline;
end

%% Normalizace dat

AUC_data = sum(abs(data),4)/size(data,4);
AUC_data = AUC_data(:);
AUC_data(AUC_data==0)=[];
med_data = median(AUC_data,'all');
data = data./med_data;

% data(isinf(data))=0;
% data(isnan(data))=0;

%% Automatická detekce

[output_common] = automatic_detection_sim(data,Ts);

%% Simul visual

I1 = data2D(:,:,:,61);
I1 = mat2gray(I1);
I1 = I1.*255;
I1 = uint8(I1);
I1 = imresize(I1, [1024 1024]);

a = output_common(:,:,:);
% im_ref = output_common(:,:,:);
a = imresize(a, [1024 1024]);
a = uint8(~a);

I2 = I1.*a;
I3 = I1;
I3(a==0)=255;


I1(:,:,1) = I3;
I1(:,:,2) = I2;
I1(:,:,3) = I2;

figure;
subplot 121
imshow(I1);
subplot 122
imshow(RoisMap,[])

aifs_mean = zeros(size(data,3),size(data,4));

for j = 1
[rows, columns]=find(output_common(:,:,j)==1);

%% Get AIF
aif = zeros(size(data,4)*size(data,3),length(rows));
aif = [];
aifs = [];
aif_s = [];

for i = 1:length(rows)
        aifs= squeeze(data(rows(i,1),columns(i,1),j,:));
        aif_s(i,:) = aifs; 
end

figure;
plot(timeAxis,aif_s');
xlabel('Časová osa [min]')
ylabel('AIF [a.u.]')

aif_mean = mean(aif_s,1);
figure;
plot(timeAxis,aif_mean);
xlabel('Časová osa [min]')
ylabel('AIF [a.u.]')

end



