%% AllEmotions is function that plots number of fixations in each roi for all emotions and exports Number of fixations in videos per subject per each emotion
%% Input data
% efed: experiment (EFE1/EFE2; EFED1/EFED2)
% mini: start of interval in video in ms
% maxi: end of interval in video in ms
% check: 1/0, 1=number,0=percentage
% path: path to fixation data
% limitdwn: minimum duration of fixation in ms
% limitup: maximum duration of fixation in ms
% export: 1/0, 1=export, 0= not export
% way: path to save .xls file
%% Output data
% graphic output with all emotions ploted in different colors in ROIs
% .xls file, emotion per one sheet, number of fix in everz video per subject
% efed='EFED1'
% mini=1
% maxi=5000
% path='\\filesrv4\home$\micankov\.windows\Bureau\Fixations\data\EventFixDynamic'
% limitup=1800
% limitdwn=50
% export=1
% way='\\filesrv4\home$\micankov\.windows\Bureau\programsandoutputsstatistics\PROGRAMS'
% check=0

function AllEmotions(efed,mini, maxi, check, path, limitup, limitdwn, export,way)
%% preset 
if mini==0
    mini=1;
else 
    mini=mini;
end
emotion={'N','F','D','S','G'};

%% load data
load(path)
%% choosing the particular videos for all emotions from all subjects
all=zeros(5,13);
s=struct;
v=struct;
t=struct;
for a=1:5 %go through all emotions one by one
    emo=emotion(a);
    FIXperemo=zeros(1,13);         
    NbFx=[];
    VidInd=[];
    True=[];
    for i=1:length(fieldnames(EventFix.(efed))) % for all subjects
        subj=fieldnames(EventFix.(efed));
        subj=subj(i,1);
        subj=subj{1,1};
        persubj=zeros(13,5000);
        subjFIX=zeros(1,13);
        kk=1;
            for j=1:length(EventFix.(efed).(subj)) % all stimuli videos
                nature=EventFix.(efed).(subj)(1,j).Nature; % get nature of video
                truename=EventFix.(efed).(subj)(1,j).TrueName;
                if strcmp (nature, emo) % Compare if emotions fit
                    if isempty(EventFix.(efed).(subj)(1,j).Roi) %if doesnt contain ROI, then move on
                        mat=zeros(13,5000);
                        fix=zeros(1,13);
                        True{i,kk}=sprintf('NODATA_%s',truename);
                        VidInd(i,kk)=j;
                        kk=kk+1;
                    else
                        mat=EventFix.(efed).(subj)(1, j).FixInVid; %takes the matrixe of fixations
                        %% cut to interval and optimalization (takes the whole duration of fixation that belongs in the interval)
                        l=1;
                        m=1;
                        if sum(mat(:,mini))==1
                            while sum(mat(:,mini-l))==1
                                l=l+1;
                            end
                            minim=mini-l;
                        else 
                            minim=mini;
                        end
                        if sum(mat(:,maxi))==1
                            while sum(mat(:,maxi+m))==1
                                m=m+1;
                            end
                            maxim=maxi+m;
                        else 
                            maxim=maxi;
                        end
                        mat(:,[1:minim])=0;
                        mat(:,[maxim:end])=0; %now we have 1 only where the fixation appear in given interval

                        %% Number of fixations in the interval
                        fix=zeros(1,13);
                        B.NumObjects=[];
                        for pp=1:9 %number of rows
                            B = bwconncomp(mat(pp, [mini:maxi])); %connects components
                            pom=0;
                            for o=1:B.NumObjects
                                if (length(B.PixelIdxList{1,o}))>=limitup || (length(B.PixelIdxList{1,o}))<=limitdwn
                                    pom=pom+1;
                                else
                                    pom=pom+0;
                                end
                            end
                            fix(pp)=B.NumObjects-pom; % gives number of fixations in each row (sum gives total number of fix)
                        end
                        NbFx(i,kk)=sum(fix); 
                        VidInd(i,kk)=j;
                        True{i,kk}=truename;
                        kk=kk+1;
                    end
               else
                    fix=zeros(1,13);
               end
               subjFIX=subjFIX+fix;
            end
            FIXperemo=subjFIX+FIXperemo; % final matrix of number of fixations
    end
    all(a,:)=FIXperemo;
    anotherfield=sprintf('%s', emotion{1,a});
    s(:).(anotherfield)=NbFx;
    v(:).(anotherfield)=VidInd;
    t(:).(anotherfield)=True;
end

if check<=1
    final(:,1)=all(:,1)+all(:,2);
    final(:,2)=all(:,3)+all(:,7);
    final(:,3:5)=all(:,4:6);
    final(:,6:7)=all(:,8:9);
    final=final';

    if check==1
    %% fix per video
        final(:,1)=round(final(:,1)./24);
        final(:,2)=round(final(:,2)./10);
        final(:,3)=round(final(:,3)./12);
        final(:,4)=round(final(:,4)./12);
        final(:,5)=round(final(:,5)./12);
        title1='Fixation per video';
        yy='number of fixation per video';

    elseif check==0 
     %% portion of video
        final(:,1)=(final(:,1)/( sum(final(:,1))))*100;
        final(:,2)=(final(:,2)/( sum(final(:,2))))*100;
        final(:,3)=(final(:,3)/( sum(final(:,3))))*100;
        final(:,4)=(final(:,4)/( sum(final(:,4))))*100;
        final(:,5)=(final(:,5)/( sum(final(:,5))))*100;
        title1='Percentage distribution in ROI';
        yy='Percentage';
    end

    h=bar(final)
%     ybuff=2 ;
%     for i=1:length(h)
%         XDATA=get(get(h(i),'Children'),'XData');
%         YDATA=get(get(h(i),'Children'),'YData');
%         for j=1:size(XDATA,2)
%             x=XDATA(1,j)+(XDATA(3,j)-XDATA(1,j))/2;
%             y=YDATA(2,j)+ybuff;
%             t=[num2str(YDATA(2,j),3)];
%             text(x,y,t,'Color','k','HorizontalAlignment','center', 'rotation', 45, 'fontsize',10)
%         end
%     end
    Labels = {'Eyes','Brows','Mouth','Chin','Nose','Corr','Front'};
    set(gca,'XTick', 1:7, 'XTickLabel', Labels);
    title(sprintf('%s, %d-%d ms, experiment: %s', title1, mini, maxi, efed), 'fontsize', 16)
    xlabel('ROIs', 'fontsize', 16)
    ylabel(sprintf('%s', yy),'fontsize', 16)
    legend('Neutral','Fear', 'Disgust', 'Surprise', 'Happiness')
end

%% xls fixations
if export==1
    filename=sprintf('%s_NumberOfFixation_%d_%dms.xls', efed, limitdwn, limitup)
    names=fieldnames(s);
    subjects=fieldnames(EventFix.(efed));
    for i=1:length(names)
        A=s.(names{i});
        xlswrite([way '\' filename], [subjects num2cell(A)], names{i});
    end
end

%% vid ind
if export==1
    filename=sprintf('%s_VidIndOFNumberOfFixation_%d_%dms.xls', efed, limitdwn, limitup)
    names=fieldnames(v);
    subjects=fieldnames(EventFix.(efed));
    for i=1:length(names)
        A=v.(names{i});
        xlswrite([way '\' filename], [subjects num2cell(A)], names{i});
    end
end
%% tru name
if export==1
    filename=sprintf('%s_TruenameVidOFNumberOfFixation_%d_%dms.xls', efed, limitdwn, limitup)
    names=fieldnames(t);
    subjects=fieldnames(EventFix.(efed));
    for i=1:length(names)
        A=t.(names{i});
        xlswrite([way '\' filename], [subjects (A)], names{i});
    end
end

