function [aif,info]=ClusterAIFExport(data4D, TF,outputFolder,info, visu)
dataPeak=mean(data4D(:,:,:,:),4);

dataPeak=imadjustn(dataPeak);
[nRows,nCols,nSlices,nSamples]=size(data4D);

% TF=TF_1stMomentCluster;
TF_4D=repmat(TF,[1 1 1 nSamples]);

signals=data4D(TF_4D);
rSig=reshape(signals,[],nSamples);
nSignals=size(rSig,1);
% rSigNorm=rSig./repmat(sum(rSig,2),[1 nSamples]);

[corR,corC,corS] = ind2sub(size(TF),find(TF == 1));

[M,~]=max(rSig,[],2);
[B,I]=sort(M,'ascend');

rSigSorted=rSig(I,:);
sR=corR(I);
sC=corC(I);
sS=corS(I);

TF=false(nRows,nCols,nSlices);
for i=1:nSignals
    TF(sR(i),sC(i),sS(i))=true;
end

percentOfCurves=2;
nSelected=ceil(nSignals/100)*percentOfCurves;

selectVox=nSignals-nSelected+1:nSignals;

sSel=rSigSorted(selectVox,:);
Rsel=sR(selectVox);
Csel=sC(selectVox);
Ssel=sS(selectVox);

TFsel=false(nRows,nCols,nSlices);
colorMap=zeros(nRows,nCols,nSlices);
for i=1:nSelected
    TFsel(Rsel(i),Csel(i),Ssel(i))=true;
    colorMap(Rsel(i),Csel(i),Ssel(i))=i;
end

% aif saving
aif={mean(sSel,1)};
aifFileName='data.mat';
info.codewords{1,end+1}='aif';
info.clusterInfo.dataPeak=dataPeak;
info.clusterInfo.TFsel=TFsel;
info.clusterInfo.colorMap=colorMap;

% try
%     save(fullfile(outputFolder,aifFileName),'aif','info');
%     disp('Saving AIF file done!');
% catch
%     disp('AIF file export was not successful!');
% end



if visu
    
    cmap=hsv(nSelected);
    
    f1=figure;
    axS1=subplot(1,3,1);
    plot(rSig');
    axS2=subplot(1,3,2);
    hold on;
    for i=1:nSelected
        plot(sSel(i,:),'color',cmap(i,:));
    end
    axS2.YLim=axS1.YLim;
    
    axS3=subplot(1,3,3);
    plot(aif{1,1},'r','LineWidth',2);
    title('resulting measured AIF');
    axS3.YLim=axS1.YLim;
    
    cmapColor=hsv(nSelected);
    cmapColor=[0 0 0; cmapColor];
    
    uint8Image = uint8(255 * mat2gray(dataPeak));
    cmapGray=gray(255);
    
    figure('visible','off');
    subplot(1,1,1);
    TFinitImg=montage(TFsel,'ThumbnailSize',[],'BorderSize',[2 2]);
    imgTF=get(TFinitImg,'CData');
    
    f2=figure
    ax1=subplot(1,2,1);
    montage(TFsel,'ThumbnailSize',[],'BorderSize',[2 2]);
    
    ax2=subplot(1,2,2);
    img1=montage(uint8Image,cmapGray,'ThumbnailSize',[],'BorderSize',[2 2]);
    hold(ax2,'on');
    img2=montage(colorMap,cmapColor,'ThumbnailSize',[],'BorderSize',[2 2]);
    img2.AlphaData=imgTF*0.7;
    img2.AlphaDataMapping='scaled';%   0 transparent, 1 opaque
    
    linkaxes([ax1 ax2],'xy');
    saveas(f1,fullfile(outputFolder,'clustersSignals.fig'));
    saveas(f1,fullfile(outputFolder,'clustersMap.fig'));
end
end