% script to analyse EMG data
% Open matfile which contains corrugator and zygomaticus data as well as
% timing info and markers.
% Marijn Struiksma September 2015

%% Required directories
%List all files that were cleaned up from Biotrace junk using the
%EDF-checker and pre-processed in Analyzer and then exported
wdir = 'M:\jvbproject\Björn\ace-brat3\export\';
%files = dir([wdir, 'ACE-BRaT_2_test_triggers2-edf_Segmentation_101_13s.mat']);
files = dir([wdir, '*.mat']);
% ==> Name your analysis directory where the results should be stored:
%adir = 'C:\Users\Marijn\SURFdrive\Björn\ACE-BRaT\test exp2\analysis\';
adir = 'M:\jvbproject\Björn\ace-brat3\Analysis\Matlab\results\';
if (exist(adir)~=7)
    mkdir(adir);
end

%Directory where the baseline selection files can be found
%bdir = 'C:\Users\Marijn\SURFdrive\Björn\ACE-BRaT\test exp2\baseline\';
bdir = 'M:\jvbproject\Björn\ace-brat3\Baseline\';
%1		2		3		4		5       6       7
%Triggers	Start_Baseline1	End_Baseline1	corrugator:Inclusion(1)/Exclusion (0)
%zygomaticus:Inclusion(1)/Exclusion(0)	(Start_Baseline2 when not 500ms in one segment)
%(End Baseline2)

%% required general variables
SampleRate = 2048; % make sure you have the correct sample rate in Hz!
binsize100ms = SampleRate*0.1;
binsizeSecs = SampleRate;
segmentsizeLikeability = 3.5; %give the size of the likeability segment in seconds
segmentsizeDots = 1; %give the size of the dots segment in seconds
segmentsizeName = 1; %give the size of the name segment in seconds
segmentsizeEventValence = 4; %give the size of the affect event segment in seconds
segmentsizeEventReason = 2.5; %give the size of the affect reason segment in seconds(round off to full seconds)
nr100msLike = segmentsizeLikeability*SampleRate/binsize100ms;
nr1sLike = segmentsizeLikeability*SampleRate/SampleRate;
nr100msDots = segmentsizeDots*SampleRate/binsize100ms;
nr1sDots = segmentsizeDots*SampleRate/SampleRate;
nr100msName = segmentsizeName*SampleRate/binsize100ms;
nr1sName = segmentsizeName*SampleRate/SampleRate;
nr100msEvVal = segmentsizeEventValence*SampleRate/binsize100ms;
nr1sEvVal = round(segmentsizeEventValence*SampleRate/SampleRate);
nr100msEvRe = segmentsizeEventReason*SampleRate/binsize100ms;
nr1sEvRe = round(segmentsizeEventReason*SampleRate/SampleRate)-1;

%% text files for Bin analysis Likeability
sjsFileBinLike=[adir,'ace-brat3_Bin_Like_',num2str(length(files)),'sjs_',date,'.txt'];
%info that is stored in the analysis file
fidBinLike = fopen(sjsFileBinLike, 'wt+');
fprintf(fidBinLike, 'sjCode\tSjNr\tlist\tincCorr\tincZygo\tmarkertrial\tlikeConditie\teventValenceConditie\tbaseline\tbaseCorr\tbaseZygo\tLikeCorrPrTrial');
% to store the 100ms bins corrugator
for t=1:nr100msLike
    fprintf(fidBinLike, '\tLikeCorrPr100ms_%i', t);
end
% to store the 1sec bins corrugator
for t=1:nr1sLike
    fprintf(fidBinLike, '\tLikeCorrPr1s_%i', t);
end

fprintf(fidBinLike, '\tLikeZygoPrTrial');
% to store the 100ms bins zygomaticus
for u=1:nr100msLike
    fprintf(fidBinLike, '\tLikeZygoPr100ms_%i', u);
end
% to store the 1sec bins zygomaticus
for t=1:nr1sLike
    fprintf(fidBinLike, '\tLikeZygoPr1s_%i', t);
end
fprintf(fidBinLike, '\n');

%% text files for Bin analysis Dots
sjsFileBinDots=[adir,'ace-brat3_Bin_Dots_',num2str(length(files)),'sjs_',date,'.txt'];
%info that is stored in the analysis file
fidBinDots = fopen(sjsFileBinDots, 'wt+');
fprintf(fidBinDots, 'sjCode\tSjNr\tlist\tincCorr\tincZygo\tmarkertrial\tlikeConditie\teventValenceConditie\tbaseline\tbaseCorr\tbaseZygo\tDotsCorrPrTrial');
% to store the 100ms bins corrugator
for t=1:nr100msDots
    fprintf(fidBinDots, '\tDotsCorrPr100ms_%i', t);
end
% to store the 1sec bins corrugator
for t=1:nr1sDots
    fprintf(fidBinDots, '\tDotsCorrPr1s_%i', t);
end

fprintf(fidBinDots, '\tDotsZygoPrTrial');
% to store the 100ms bins zygomaticus
for u=1:nr100msDots
    fprintf(fidBinDots, '\tDotsygoPr100ms_%i', u);
end
% to store the 1sec bins zygomaticus
for t=1:nr1sDots
    fprintf(fidBinDots, '\tDotsZygoPr1s_%i', t);
end
fprintf(fidBinDots, '\n');

%% text files for Bin analysis Name
sjsFileBinName=[adir,'ace-brat3_Bin_Name_',num2str(length(files)),'sjs_',date,'.txt'];
%info that is stored in the analysis file
fidBinName = fopen(sjsFileBinName, 'wt+');
fprintf(fidBinName, 'sjCode\tSjNr\tlist\tincCorr\tincZygo\tmarkertrial\tlikeConditie\teventValenceConditie\tbaseline\tbaseCorr\tbaseZygo\tNameCorrPrTrial');
% to store the 100ms bins corrugator
for t=1:nr100msName
    fprintf(fidBinName, '\tNameCorrPr100ms_%i', t);
end
% to store the 1sec bins corrugator
for t=1:nr1sName
    fprintf(fidBinName, '\tNameCorrPr1s_%i', t);
end

fprintf(fidBinName, '\tNameZygoPrTrial');
% to store the 100ms bins zygomaticus
for u=1:nr100msName
    fprintf(fidBinName, '\tNameZygoPr100ms_%i', u);
end
% to store the 1sec bins zygomaticus
for t=1:nr1sName
    fprintf(fidBinName, '\tNameZygoPr1s_%i', t);
end
fprintf(fidBinName, '\n');

%% text files for Bin analysis Event Valence
sjsFileBinEventValence=[adir,'ace-brat3_Bin_EventValence_',num2str(length(files)),'sjs_',date,'.txt'];
%info that is stored in the analysis file
fidBinEventValence = fopen(sjsFileBinEventValence, 'wt+');
fprintf(fidBinEventValence, 'sjCode\tSjNr\tlist\tincCorr\tincZygo\tmarkertrial\tlikeConditie\teventValenceConditie\tbaseline\tbaseCorr\tbaseZygo\tEventValenceCorrPrTrial');
% to store the 100ms bins corrugator
for t=1:nr100msEvVal
    fprintf(fidBinEventValence, '\tEventValenceCorrPr100ms_%i', t);
end
% to store the 1sec bins corrugator
for t=1:nr1sEvVal
    fprintf(fidBinEventValence, '\tEventValenceCorrPr1s_%i', t);
end

fprintf(fidBinEventValence, '\tEventValenceZygoPrTrial');
% to store the 100ms bins zygomaticus
for u=1:nr100msEvVal
    fprintf(fidBinEventValence, '\tEventValenceZygoPr100ms_%i', u);
end
% to store the 1sec bins zygomaticus
for t=1:nr1sEvVal
    fprintf(fidBinEventValence, '\tEventValenceZygoPr1s_%i', t);
end
fprintf(fidBinEventValence, '\n');

%% text files for Bin analysis Event Reason
sjsFileBinEventReason=[adir,'ace-brat3_Bin_EventReason_',num2str(length(files)),'sjs_',date,'.txt'];
%info that is stored in the analysis file
fidBinEventReason = fopen(sjsFileBinEventReason, 'wt+');
fprintf(fidBinEventReason, 'sjCode\tSjNr\tlist\tincCorr\tincZygo\tmarkertrial\tlikeConditie\teventValenceConditie\tbaseline\tbaseCorr\tbaseZygo\tEventReasonCorrPrTrial');
% to store the 100ms bins corrugator
for t=1:nr100msEvRe
    fprintf(fidBinEventReason, '\tEventReasonCorrPr100ms_%i', t);
end
% to store the 1sec bins corrugator
for t=1:nr1sEvRe
    fprintf(fidBinEventReason, '\tEventReasonCorrPr1s_%i', t);
end

fprintf(fidBinEventReason, '\tEventReasonZygoPrTrial');
% to store the 100ms bins zygomaticus
for u=1:nr100msEvRe
    fprintf(fidBinEventReason, '\tEventReasonZygoPr100ms_%i', u);
end
% to store the 1sec bins zygomaticus
for t=1:nr1sEvRe
    fprintf(fidBinEventReason, '\tEventReasonZygoPr1s_%i', t);
end
fprintf(fidBinEventReason, '\n');

%% Open file and anlyze results
for iFile = 1:length(files)
    
    filename_list{iFile} = files(iFile).name(5:end-22); %Get file name (without edf checker name)
    disp(filename_list{iFile})
    all(iFile).fileName = filename_list{iFile};
    order = str2num(files(iFile).name(20));
    %order = 1;
    load([wdir,files(iFile).name]);   %Load single data file
    baseline=load([bdir,filename_list{iFile},'.txt']);   %Load single baseline file
    storeMarkertrial=0;
    waitingForBaseline=0;
    waitingfForExperiment=0;
    practiceFinished=0;
    
    % Loop over 64 trials
    for iTrial = 1: SegmentCount
        nrMarkers = size(Markers);
        for iMarker = 1:nrMarkers(2)
            if ~isempty(Markers(iTrial,iMarker).Description);
                marker = str2num(Markers(iTrial,iMarker).Description);
            else
                marker = [];
            end
            %disp(marker)
            if ~isempty(marker) % check only numerical triggers
                
                if  marker==101    %trigger start baseline
                    % set up for baseline calculations
                    waitingForBaseline=1;
                    
                    % Find relevant info for Morality markers 1-64, Minimal groups markers 121-186
                elseif (marker>=1)&&(marker<=64)||(marker>=121)&&(marker<=184) %trigger item
                    practiceFinished=0;
                    if waitingForBaseline==1 % waiting for baseline to finish
                        markertrial=marker;
                        % find the relevant baseline
                        pBaseline=find(baseline==marker,1);
                        %%Check in baseline txt file whether to include
                        %%corrrugator(c4) and zygomaticus (c5)
                        result(markertrial).incCorr=baseline(pBaseline,4);
                        all(iFile).incCorr(markertrial)=baseline(pBaseline,4);
                        result(markertrial).incZygo=baseline(pBaseline,5);
                        all(iFile).incZygo(markertrial)=baseline(pBaseline,5);
                        % store listnr
                        result(markertrial).list=order;
                        %Calculate baseline
                        %Determine windows for baseline
                        b1=baseline(pBaseline,2);
                        b2=baseline(pBaseline,3);
                        b3=baseline(pBaseline,6);
                        b4=baseline(pBaseline,7);
                        %Check baseline values
                        for b=[b1,b2,b3,b4]
                            if (b<0)||(b>2000)
                                disp([filename_list{iFile},' markertrial:',int2str(markertrial)])
                                disp('baseline incorrect')
                            end
                        end
                        
                        %Determine timepoints window
                        %posB=Markers(iTrial,iMarker).Position; from
                        %previous experiment where the trial marker was the
                        %end of the baseline, now irrelevant
                        if isnan(b3) % single window
                            t1=round(1+(b1/1000*SampleRate));
                            t2=round(1+(b2/1000*SampleRate));
                            result(markertrial).baselineCorr=mean(corrugator(iTrial,t1:t2));
                            result(markertrial).baselineZygo=mean(zygomaticus(iTrial,t1:t2));
                            result(markertrial).baseline=b2-b1;
                        else % two windows
                            t1=round(1+(b1/1000*SampleRate));
                            t2=round(1+(b2/1000*SampleRate));
                            t3=round(1+(b3/1000*SampleRate));
                            t4=round(1+(b4/1000*SampleRate));
                            result(markertrial).baselineCorr=mean(horzcat(corrugator(iTrial,t1:t2),corrugator(iTrial,t3:t4)));
                            result(markertrial).baselineZygo=mean(horzcat(zygomaticus(iTrial,t1:t2),zygomaticus(iTrial,t3:t4)));
                            result(markertrial).baseline=(b2-b1)+(b4-b3);
                        end
                        waitingForBaseline=0; % no longer waiting to compute baseline
                        
                        %store proportional data for the entire Likeability epoch for
                        %visualization purposes
                        all(iFile).timecourse(markertrial).likeCorrPr=raw(iFile).timecourse(iTrial).likeCorr/result(markertrial).baselineCorr*100;
                        all(iFile).timecourse(markertrial).likeZygoPr=raw(iFile).timecourse(iTrial).likeZygo/result(markertrial).baselineZygo*100;
                        %compute results for the entire likeability trial
                        result(markertrial).likeCorrRawTrial=mean(raw(iFile).timecourse(iTrial).likeCorr);
                        result(markertrial).likeCorrPrTrial=mean(raw(iFile).timecourse(iTrial).likeCorr)/result(markertrial).baselineCorr*100;
                        result(markertrial).likeZygoRawTrial=mean(raw(iFile).timecourse(iTrial).likeZygo);
                        result(markertrial).likeZygoPrTrial=mean(raw(iFile).timecourse(iTrial).likeZygo)/result(markertrial).baselineZygo*100;
                        
                        for kSignal=1:nr100msLike %for all 100ms bins during the segment
                            ktime1 = round(posL + (kSignal-1)*binsize100ms);
                            ktime2 = round(posL + kSignal*binsize100ms);
                            % compute proportion per bin
                            resultBinLikeCorrPr(markertrial,kSignal)=mean(corrugator(iTrial,ktime1:ktime2))/result(1,markertrial).baselineCorr*100;
                            resultBinLikeZygoPr(markertrial,kSignal)=mean(zygomaticus(iTrial,ktime1:ktime2))/result(1,markertrial).baselineZygo*100;
                        end
                        all(iFile).bin(markertrial).LikeCorrPr=resultBinLikeCorrPr(markertrial,:);
                        all(iFile).bin(markertrial).LikeZygoPr=resultBinLikeZygoPr(markertrial,:);
                        
                        for mSignal=1:nr1sLike %for all 1s bins during the segment
                            mtime1 = round(posL + (mSignal-1)*binsizeSecs);
                            mtime2 = round(posL + mSignal*binsizeSecs);
                            % compute proportion per bin
                            resultSecsLikeCorrPr(markertrial,mSignal)=mean(corrugator(iTrial,mtime1:mtime2))/result(1,markertrial).baselineCorr*100;
                            resultSecsLikeZygoPr(markertrial,mSignal)=mean(zygomaticus(iTrial,mtime1:mtime2))/result(1,markertrial).baselineZygo*100;
                        end
                        all(iFile).binSecs(markertrial).LikeCorrPr=resultSecsLikeCorrPr(markertrial,:);
                        all(iFile).binSecs(markertrial).LikeZygoPr=resultSecsLikeZygoPr(markertrial,:);
                        % store the like condition and markertrial
                        result(markertrial).likeConditie=raw(iFile).likeConditie(iTrial);
                        all(iFile).marker(markertrial)=markertrial;
                        
                        % Store Dots segment
                        posD=Markers(iTrial,iMarker).Position;
                        t2=round(posD+(segmentsizeDots*SampleRate));
                        %store proportional data for the entire Dots epoch for
                        %visualization purposes
                        all(iFile).timecourse(markertrial).dotsCorrPr=corrugator(iTrial,posD:t2)/result(markertrial).baselineCorr*100;
                        all(iFile).timecourse(markertrial).dotsZygoPr=zygomaticus(iTrial,posD:t2)/result(markertrial).baselineZygo*100;
                        %compute results for Dots segment
                        result(markertrial).dotsCorrRawTrial=mean(corrugator(iTrial,posD:t2));
                        result(markertrial).dotsCorrPrTrial=mean(corrugator(iTrial,posD:t2))/result(markertrial).baselineCorr*100;
                        result(markertrial).dotsZygoRawTrial=mean(zygomaticus(iTrial,posD:t2));
                        result(markertrial).dotsZygoPrTrial=mean(zygomaticus(iTrial,posD:t2))/result(markertrial).baselineZygo*100;
                        
                        for qSignal=1:nr100msDots %for all 100ms bins during the segment
                            qtime1 = round(posD + (qSignal-1)*binsize100ms);
                            qtime2 = round(posD + qSignal*binsize100ms);
                            % compute proportion per bin
                            resultBinDotsCorrPr(markertrial,qSignal)=mean(corrugator(iTrial,qtime1:qtime2))/result(1,markertrial).baselineCorr*100;
                            resultBinDotsZygoPr(markertrial,qSignal)=mean(zygomaticus(iTrial,qtime1:qtime2))/result(1,markertrial).baselineZygo*100;
                        end
                        all(iFile).bin(markertrial).DotsCorrPr=resultBinDotsCorrPr(markertrial,:);
                        all(iFile).bin(markertrial).DotsZygoPr=resultBinDotsZygoPr(markertrial,:);
                        
                        for rSignal=1:nr1sDots %for all 1s bins during the segment
                            rtime1 = round(posD + (rSignal-1)*binsizeSecs);
                            rtime2 = round(posD + rSignal*binsizeSecs);
                            % compute proportion per bin
                            resultSecsDotsCorrPr(markertrial,rSignal)=mean(corrugator(iTrial,rtime1:rtime2))/result(1,markertrial).baselineCorr*100;
                            resultSecsDotsZygoPr(markertrial,rSignal)=mean(zygomaticus(iTrial,rtime1:rtime2))/result(1,markertrial).baselineZygo*100;
                        end
                        all(iFile).binSecs(markertrial).DotsCorrPr=resultSecsDotsCorrPr(markertrial,:);
                        all(iFile).binSecs(markertrial).DotsZygoPr=resultSecsDotsZygoPr(markertrial,:);
                        
                    else % end of a critical segment
                        % do nothing
                    end
                    
                elseif (marker==65)||(marker==66) % practice trials Morality
                    practiceFinished=practiceFinished+1;
                    waitingfForExperiment=0;
                    
                elseif (marker==185)||(marker==186) % practice trials Minimal groups
                    practiceFinished=practiceFinished+1;
                    waitingfForExperiment=0;
                    
                elseif (marker==102)||(marker==103)||(marker==104)||(marker==105) % likeability trigger
                    % 102=moral 103=immoral 104=ingroup 105=outgroup
                    if practiceFinished==2
                        waitingfForExperiment=1;
                    end
                    if waitingfForExperiment==1 % excludes practice trials
                        posL=Markers(iTrial,iMarker).Position;
                        t2=round(posL+(segmentsizeLikeability*SampleRate));
                        
                        %store raw data for the entire Likeability epoch to
                        %compute the proportional data after the long pause
                        raw(iFile).timecourse(iTrial).likeCorr=corrugator(iTrial,posL:t2);
                        raw(iFile).timecourse(iTrial).likeZygo=zygomaticus(iTrial,posL:t2);
                        
                        % include condition likeability
                        raw(iFile).likeConditie(iTrial)=marker;
                    end
                    
                elseif (marker==110)||(marker==111)||(marker==112)||(marker==113)   % Event valence trigger
                    % 110=positive morality 111=negative morality
                    % 112=poisitive minimal group 113=negative minimal group
                    if waitingfForExperiment==1 % excludes practice trials
                        posV=Markers(iTrial,iMarker).Position;
                        t2=round(posV+(segmentsizeEventValence*SampleRate));
                        %store proportional data for the entire eventValence epoch for
                        %visualization purposes
                        all(iFile).timecourse(markertrial).eventValenceCorrPr=corrugator(iTrial,posV:t2)/result(markertrial).baselineCorr*100;
                        all(iFile).timecourse(markertrial).eventValenceZygoPr=zygomaticus(iTrial,posV:t2)/result(markertrial).baselineZygo*100;
                        %compute results for event valence segment
                        result(markertrial).eventValenceCorrRawTrial=mean(corrugator(iTrial,posV:t2));
                        result(markertrial).eventValenceCorrPrTrial=mean(corrugator(iTrial,posV:t2))/result(markertrial).baselineCorr*100;
                        result(markertrial).eventValenceZygoRawTrial=mean(zygomaticus(iTrial,posV:t2));
                        result(markertrial).eventValenceZygoPrTrial=mean(zygomaticus(iTrial,posV:t2))/result(markertrial).baselineZygo*100;
                        
                        for lSignal=1:nr100msEvVal %for all 100ms bins during the segment
                            ltime1 = round(posV + (lSignal-1)*binsize100ms);
                            ltime2 = round(posV + lSignal*binsize100ms);
                            % compute proportion per bin
                            resultBinEventValenceCorrPr(markertrial,lSignal)=mean(corrugator(iTrial,ltime1:ltime2))/result(1,markertrial).baselineCorr*100;
                            resultBinEventValenceZygoPr(markertrial,lSignal)=mean(zygomaticus(iTrial,ltime1:ltime2))/result(1,markertrial).baselineZygo*100;
                        end
                        all(iFile).bin(markertrial).EventValenceCorrPr=resultBinEventValenceCorrPr(markertrial,:);
                        all(iFile).bin(markertrial).EventValenceZygoPr=resultBinEventValenceZygoPr(markertrial,:);
                        
                        for nSignal=1:nr1sEvVal %for all 1s bins during the segment
                            ntime1 = round(posV + (nSignal-1)*binsizeSecs);
                            ntime2 = round(posV + nSignal*binsizeSecs);
                            % compute proportion per bin
                            resultSecsEventValenceCorrPr(markertrial,nSignal)=mean(corrugator(iTrial,ntime1:ntime2))/result(1,markertrial).baselineCorr*100;
                            resultSecsEventValenceZygoPr(markertrial,nSignal)=mean(zygomaticus(iTrial,ntime1:ntime2))/result(1,markertrial).baselineZygo*100;
                        end
                        all(iFile).binSecs(markertrial).EventValenceCorrPr=resultSecsEventValenceCorrPr(markertrial,:);
                        all(iFile).binSecs(markertrial).EventValenceZygoPr=resultSecsEventValenceZygoPr(markertrial,:);
                        
                        % include event valence condition
                        result(markertrial).eventValence=marker;
                        all(iFile).eventValence(markertrial)=marker;
                    end
                    
                elseif (marker==116)||(marker==117)||(marker==118)||(marker==119)   % Event reason trigger
                    % 116=positive morality 117=negative morality
                    % 118=poisitive minimal group 119=negative minimal group
                    if waitingfForExperiment==1 % excludes practice trials
                        posR=Markers(iTrial,iMarker).Position;
                        t2=round(posR+(segmentsizeEventReason*SampleRate));
                        %store proportional data for the entire eventValence epoch for
                        %visualization purposes
                        all(iFile).timecourse(markertrial).eventReasonCorrPr=corrugator(iTrial,posR:t2)/result(markertrial).baselineCorr*100;
                        all(iFile).timecourse(markertrial).eventReasonZygoPr=zygomaticus(iTrial,posR:t2)/result(markertrial).baselineZygo*100;
                        %compute results for event valence segment
                        result(markertrial).eventReasonCorrRawTrial=mean(corrugator(iTrial,posR:t2));
                        result(markertrial).eventReasonCorrPrTrial=mean(corrugator(iTrial,posR:t2))/result(markertrial).baselineCorr*100;
                        result(markertrial).eventReasonZygoRawTrial=mean(zygomaticus(iTrial,posR:t2));
                        result(markertrial).eventReasonZygoPrTrial=mean(zygomaticus(iTrial,posR:t2))/result(markertrial).baselineZygo*100;
                        
                        for oSignal=1:nr100msEvRe %for all 100ms bins during the segment
                            otime1 = round(posR + (oSignal-1)*binsize100ms);
                            otime2 = round(posR + oSignal*binsize100ms);
                            % compute proportion per bin
                            resultBinEventReasonCorrPr(markertrial,oSignal)=mean(corrugator(iTrial,otime1:otime2))/result(1,markertrial).baselineCorr*100;
                            resultBinEventReasonZygoPr(markertrial,oSignal)=mean(zygomaticus(iTrial,otime1:otime2))/result(1,markertrial).baselineZygo*100;
                        end
                        all(iFile).bin(markertrial).EventReasonCorrPr=resultBinEventReasonCorrPr(markertrial,:);
                        all(iFile).bin(markertrial).EventReasonZygoPr=resultBinEventReasonZygoPr(markertrial,:);
                        
                        for pSignal=1:nr1sEvRe %for all 1s bins during the segment
                            ptime1 = round(posR + (pSignal-1)*binsizeSecs);
                            ptime2 = round(posR + pSignal*binsizeSecs);
                            % compute proportion per bin
                            resultSecsEventReasonCorrPr(markertrial,pSignal)=mean(corrugator(iTrial,ptime1:ptime2))/result(1,markertrial).baselineCorr*100;
                            resultSecsEventReasonZygoPr(markertrial,pSignal)=mean(zygomaticus(iTrial,ptime1:ptime2))/result(1,markertrial).baselineZygo*100;
                        end
                        all(iFile).binSecs(markertrial).EventReasonCorrPr=resultSecsEventReasonCorrPr(markertrial,:);
                        all(iFile).binSecs(markertrial).EventReasonZygoPr=resultSecsEventReasonZygoPr(markertrial,:);
                        storeMarkertrial=1;
                        end
                    
                elseif (marker==106)||(marker==107) % Name trigger
                    % 106=name morality 107=name minimal groupsd
                    if waitingfForExperiment==1 % excludes practice trials
                        posN=Markers(iTrial,iMarker).Position;
                        t2=round(posN+(segmentsizeName*SampleRate));
                        %store proportional data for the entire Name epoch for
                        %visualization purposes
                        all(iFile).timecourse(markertrial).nameCorrPr=corrugator(iTrial,posN:t2)/result(markertrial).baselineCorr*100;
                        all(iFile).timecourse(markertrial).nameZygoPr=zygomaticus(iTrial,posN:t2)/result(markertrial).baselineZygo*100;
                        %compute results for Name segment
                        result(markertrial).nameCorrRawTrial=mean(corrugator(iTrial,posN:t2));
                        result(markertrial).nameCorrPrTrial=mean(corrugator(iTrial,posN:t2))/result(markertrial).baselineCorr*100;
                        result(markertrial).nameZygoRawTrial=mean(zygomaticus(iTrial,posN:t2));
                        result(markertrial).nameZygoPrTrial=mean(zygomaticus(iTrial,posN:t2))/result(markertrial).baselineZygo*100;
                        
                        for sSignal=1:nr100msName %for all 100ms bins during the segment
                            stime1 = round(posN + (sSignal-1)*binsize100ms);
                            stime2 = round(posN + sSignal*binsize100ms);
                            % compute proportion per bin
                            resultBinNameCorrPr(markertrial,sSignal)=mean(corrugator(iTrial,stime1:stime2))/result(1,markertrial).baselineCorr*100;
                            resultBinNameZygoPr(markertrial,sSignal)=mean(zygomaticus(iTrial,stime1:stime2))/result(1,markertrial).baselineZygo*100;
                        end
                        all(iFile).bin(markertrial).NameCorrPr=resultBinNameCorrPr(markertrial,:);
                        all(iFile).bin(markertrial).NameZygoPr=resultBinNameZygoPr(markertrial,:);
                        
                        for tSignal=1:nr1sName %for all 1s bins during the segment
                            ttime1 = round(posN + (tSignal-1)*binsizeSecs);
                            ttime2 = round(posN + tSignal*binsizeSecs);
                            % compute proportion per bin
                            resultSecsNameCorrPr(markertrial,tSignal)=mean(corrugator(iTrial,ttime1:ttime2))/result(1,markertrial).baselineCorr*100;
                            resultSecsNameZygoPr(markertrial,tSignal)=mean(zygomaticus(iTrial,ttime1:ttime2))/result(1,markertrial).baselineZygo*100;
                        end
                        all(iFile).binSecs(markertrial).NameCorrPr=resultSecsNameCorrPr(markertrial,:);
                        all(iFile).binSecs(markertrial).NameZygoPr=resultSecsNameZygoPr(markertrial,:);
                    end
                    
                elseif marker==120 % end of trial trigger
                    waitingForBaseline=0;
                    
                else % not a critical trigger
                    
                end % relevant markers
            end % numerical
            
            %Export result per subject
            if storeMarkertrial==1
                % ==> Add EMG parameters/scores to be exported
                % Likeability
                % ==> Add Like bin results to file 3s Baseline begin trial
                fprintf(fidBinLike,'%s\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t',...
                    filename_list{iFile},iFile,result(markertrial).list,result(markertrial).incCorr,...
                    result(markertrial).incZygo,markertrial,result(markertrial).likeConditie,result(markertrial).eventValence,...
                    result(markertrial).baseline,result(markertrial).baselineCorr,result(markertrial).baselineZygo,...
                    result(markertrial).likeCorrPrTrial,resultBinLikeCorrPr(markertrial,:),resultSecsLikeCorrPr(markertrial,:),...
                    result(markertrial).likeZygoPrTrial,resultBinLikeZygoPr(markertrial,:),resultSecsLikeZygoPr(markertrial,:));
%                    result(markertrial).likeCorrPrTrial,resultBinLikeCorrPr(markertrial,1:nr100msLike),resultSecsLikeCorrPr(markertrial,1:nr1sLike),...
 %                   result(markertrial).likeZygoPrTrial,resultBinLikeZygoPr(markertrial,1:nr100msLike),resultSecsLikeZygoPr(markertrial,1:nr1sLike));
                fprintf(fidBinLike,'\n');
                
                % EventValence
                % ==> Add EventValence bin results to file 3s Baseline begin trial
                fprintf(fidBinEventValence,'%s\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t',...
                    filename_list{iFile},iFile,result(markertrial).list,result(markertrial).incCorr,...
                    result(markertrial).incZygo,markertrial,result(markertrial).likeConditie,result(markertrial).eventValence,...
                    result(markertrial).baseline,result(markertrial).baselineCorr,result(markertrial).baselineZygo,...
                    result(markertrial).eventValenceCorrPrTrial,resultBinEventValenceCorrPr(markertrial,1:nr100msEvVal),resultSecsEventValenceCorrPr(markertrial,1:nr1sEvVal),...
                    result(markertrial).eventValenceZygoPrTrial,resultBinEventValenceZygoPr(markertrial,1:nr100msEvVal),resultSecsEventValenceZygoPr(markertrial,1:nr1sEvVal));
                fprintf(fidBinEventValence,'\n');
                
                % Dots
                % ==> Add Dots bin results to file 3s Baseline begin trial
                fprintf(fidBinDots,'%s\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t',...
                    filename_list{iFile},iFile,result(markertrial).list,result(markertrial).incCorr,...
                    result(markertrial).incZygo,markertrial,result(markertrial).likeConditie,result(markertrial).eventValence,...
                    result(markertrial).baseline,result(markertrial).baselineCorr,result(markertrial).baselineZygo,...
                    result(markertrial).dotsCorrPrTrial,resultBinDotsCorrPr(markertrial,1:nr100msDots),resultSecsDotsCorrPr(markertrial,1:nr1sDots),...
                    result(markertrial).dotsZygoPrTrial,resultBinDotsZygoPr(markertrial,1:nr100msDots),resultSecsDotsZygoPr(markertrial,1:nr1sDots));
                fprintf(fidBinDots,'\n');
                
                % Name
                % ==> Add Name bin results to file 3s Baseline begin trial
                fprintf(fidBinName,'%s\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t',...
                    filename_list{iFile},iFile,result(markertrial).list,result(markertrial).incCorr,...
                    result(markertrial).incZygo,markertrial,result(markertrial).likeConditie,result(markertrial).eventValence,...
                    result(markertrial).baseline,result(markertrial).baselineCorr,result(markertrial).baselineZygo,...
                    result(markertrial).nameCorrPrTrial,resultBinNameCorrPr(markertrial,1:nr100msName),resultSecsNameCorrPr(markertrial,1:nr1sName),...
                    result(markertrial).nameZygoPrTrial,resultBinNameZygoPr(markertrial,1:nr100msName),resultSecsNameZygoPr(markertrial,1:nr1sName));
                fprintf(fidBinName,'\n');
                
                % EventReason
                % ==> Add EventReason bin results to file 3s Baseline begin trial
                fprintf(fidBinEventReason,'%s\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t%i\t',...
                    filename_list{iFile},iFile,result(markertrial).list,result(markertrial).incCorr,...
                    result(markertrial).incZygo,markertrial,result(markertrial).likeConditie,result(markertrial).eventValence,...
                    result(markertrial).baseline,result(markertrial).baselineCorr,result(markertrial).baselineZygo,...
                    result(markertrial).eventReasonCorrPrTrial,resultBinEventReasonCorrPr(markertrial,1:nr100msEvRe),resultSecsEventReasonCorrPr(markertrial,1:nr1sEvRe),...
                    result(markertrial).eventReasonZygoPrTrial,resultBinEventReasonZygoPr(markertrial,1:nr100msEvRe),resultSecsEventReasonZygoPr(markertrial,1:nr1sEvRe));
                fprintf(fidBinEventReason,'\n');
                
                storeMarkertrial=0;
            end
        end %iMarker
    end %iTrial
end %iFile
%Export result all subjects
allFile=[adir,'ace-brat3_segments_',num2str(length(files)),'sjs_',date,'.mat'];
save(allFile,'all','-v7.3');
fclose('all');