% 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 = 'L:\projects\jvbproject\Björn\ace-brat3\export\';
files = dir([wdir, '*.mat']);
%files = dir([wdir, 'new_acebrat3ppn13l05_TrialSegmentation.mat']);
% ==> Name your analysis directory where the results should be stored:
adir = 'L:\projects\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 = 'L:\projects\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;
%segmentsize = 18.2; %give the size of the likeability segment in seconds
segmentsize = 18; %give the size of the likeability segment in seconds
nr100ms = segmentsize*SampleRate/binsize100ms;

%% text files for Bin analysis whole trial
sjsFileBin=[adir,'ace-brat3_Bin_whole_trial_',num2str(length(files)),'sjs_',date,'.txt'];
%info that is stored in the analysis file
fidBin = fopen(sjsFileBin, 'wt+');
fprintf(fidBin, 'sjCode\tSjNr\tlist\tincCorr\tincZygo\tmarkertrial\tlikeConditie\teventValenceConditie\teventReasonConditie\tbaseline\tbaseCorr\tbaseZygo\tCorrPrTrial');
% to store the 100ms bins corrugator
%for t=1:(nr100ms-1)
for t=1:(nr100ms)
    fprintf(fidBin, '\tCorrPr100ms_%i', t);
end

fprintf(fidBin, '\tLikeZygoPrTrial');
% to store the 100ms bins zygomaticus
%for u=1:(nr100ms-1)
for u=1:(nr100ms)
    fprintf(fidBin, '\tLikeZygoPr100ms_%i', u);
end
fprintf(fidBin, '\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(17));
    %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 
        % Find relevant info for baseline markers 1-64
        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;
                    
                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;
                    

                    
                    % 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)
                        segment(iFile).incCorr(markertrial)=baseline(pBaseline,4);
                        segment(iFile).incZygo(markertrial)=baseline(pBaseline,5);
                        % store listnr
                        result(markertrial).list=order;
                        %Calculate baseline
                        %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
                        
                        %store the entire trial in 100ms bins
                        for sSignal=1:length(corrugator(iTrial,:))/binsize100ms %for all 100ms bins during the segment
                            stime1 = round(1+(sSignal-1)*binsize100ms);
                            stime2 = round(1+ sSignal*binsize100ms);
                            if sSignal==length(corrugator(iTrial,:))/binsize100ms
                                stime2 = round(sSignal*binsize100ms);
                            end
                            % Proportion: baseline begin of trial
                            resultSegmentsCorrPr(markertrial,sSignal)=mean(corrugator(iTrial,stime1:stime2))/result(1,markertrial).baselineCorr*100;
                            resultSegmentsZygoPr(markertrial,sSignal)=mean(zygomaticus(iTrial,stime1:stime2))/result(1,markertrial).baselineZygo*100;
                        end
                        segment(iFile).bin100ms(markertrial).CorrPr=resultSegmentsCorrPr(markertrial,:);
                        segment(iFile).bin100ms(markertrial).ZygoPr=resultSegmentsZygoPr(markertrial,:);
                        
                        result(markertrial).CorrPrTrial=mean(corrugator(iTrial,:))/result(1,markertrial).baselineCorr*100;
                        result(markertrial).ZygoPrTrial=mean(zygomaticus(iTrial,:))/result(1,markertrial).baselineZygo*100;
                        
                        segment(iFile).likeConditie(markertrial)=LikeMarker;

                        waitingForBaseline=0; % no longer waiting to compute baseline
                    end
                    
                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
                        % include condition likeability
                        LikeMarker=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
                        segment(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
                        segment(iFile).eventReason(markertrial)=marker;
                        storeMarkertrial=1;
                    end
                    
                elseif marker==120 % end of trial trigger
                    waitingForBaseline=0;
                    
                else % end of a critical segment
                    % do nothing
                    
                end % relevant markers
            end % numerical markers
            %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(fidBin,'%s\t%i\t%i\t%i\t%i\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,segment(iFile).incCorr(markertrial),...
                    segment(iFile).incZygo(markertrial),markertrial,segment(iFile).likeConditie(markertrial),segment(iFile).eventValence(markertrial),segment(iFile).eventReason(markertrial),...
                    result(markertrial).baseline,result(markertrial).baselineCorr,result(markertrial).baselineZygo,...
                    result(markertrial).CorrPrTrial,segment(iFile).bin100ms(markertrial).CorrPr,...
                    result(markertrial).ZygoPrTrial,segment(iFile).bin100ms(markertrial).ZygoPr);
                fprintf(fidBin,'\n');
                storeMarkertrial=0;
            end
                
        end %iMarker
    end %iTrial
end %iFile
%Export result all subjects
%allFile=[adir,'ACE-BRaT3_full_timecourse_',num2str(length(files)),'sjs_',date,'.mat'];
%save(allFile,'segment','-v7.3');
fclose('all');