% script to analyse EMG data
% Open matfile which contains corrugator and zygomaticus data as well as
% timing info and markers.
% Marijn Struiksma March 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-BRaT\Analyzer na EDFChecker v1.0\matfiles\';
files = dir([wdir, '*.mat']);
% ==> Name your analysis directory where the results should be stored:
adir = 'M:\jvbproject\Björn\ACE-BRaT\Analyzer na EDFChecker v1.0\analysis\';
if (exist(adir)~=7)
    mkdir(adir);
end
%Directory where the baseline selection files can be found
bdir = 'M:\jvbproject\Björn\ACE-BRaT\Raw data\Baseline\Subjects\Björn\';
%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)

%{
%text files for Bin analysis
sjsFileBinLike=[adir,'ACE-BRaT_Bin_Like_',num2str(length(files)),'sjs_',date,'.txt'];
sjsFileBinAffect=[adir,'ACE-BRaT_Bin_Affect_',num2str(length(files)),'sjs_',date,'.txt'];
% sjsFileBinLike=[adir,'ACE-BRaT_Bin_Like_l02ppn06',date,'.txt'];
% sjsFileBinAffect=[adir,'ACE-BRaT_Bin_Affect_l02ppn06',date,'.txt'];
%info that is stored in the analysis file
fidBinLike = fopen(sjsFileBinLike, 'wt+');
fprintf(fidBinLike, 'sjCode\tSjNr\tlist\tincCorr\tincZygo\tmarkertrial\tlikeConditie\tbaseline\tbaseCorr\tbaseZygo');
fidBinAffect = fopen(sjsFileBinAffect, 'wt+');
fprintf(fidBinAffect, 'sjCode\tSjNr\tlist\tincCorr\tincZygo\tmarkertrial\tlikeConditie\taffectConditie\tbaseline\tbaseCorr\tbaseZygo');
for t=1:50
    fprintf(fidBinLike, '\tLikeCorrPct %i', t);
    fprintf(fidBinAffect, '\tAffectCorrPct %i', t);
end
fprintf(fidBinLike, '\tLikeCorrPctS1\tLikeCorrPctS2\tLikeCorrPctS3\tLikeCorrPctS4\tLikeCorrPctS5\tLikeCorrPctTrial');
fprintf(fidBinAffect, '\tAffectCorrPctS1\tAffectCorrPctS2\tAffectCorrPctS3\tAffectCorrPctS4\tAffectCorrPctS5\tAffectCorrPctTrial');
for u=1:50
    fprintf(fidBinLike, '\tLikeZygoPct %i', u);
    fprintf(fidBinAffect, '\tAffectZygoPct %i', u);
end
fprintf(fidBinLike, '\tLikeZygoPctS1\tLikeZygoPctS2\tLikeZygoPctS3\tLikeZygoPctS4\tLikeZygoPctS5\tLikeZygoPctTrial\n');
fprintf(fidBinAffect, '\tAffectZygoPctS1\tAffectZygoPctS2\tAffectZygoPctS3\tAffectZygoPctS4\tAffectZygoPctS5\tAffectZygoPctTrial\n');
%}

%% Open file and anlyze results
for iFile = 1:length(files)
    
    filename_list{iFile} = files(iFile).name(25:end-22); %Get file name (without edf checker name)
    disp(filename_list{iFile})
    all(iFile).fileName = filename_list{iFile};
    order = str2num(files(iFile).name(35));
    load([wdir,files(iFile).name]);   %Load single data file
    baseline=load([bdir,filename_list{iFile},'.txt']);   %Load single baseline file
    storeMarkertrial=0;
    binsize = SampleRate*0.1;
    nr100ms = 5*SampleRate/binsize;
    binsizeSecs = SampleRate;
    nr1s = 5*SampleRate/binsizeSecs;
    
    % 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>=1)&&(marker<=64)    %baseline trigger
                    pBaseline=find(baseline==marker,1);
                    %%Check in baseline txt file whether to include
                    %%corrrugator(c4) and zygomaticus (c5)
                    result(marker).incCorr=baseline(pBaseline,4);
                    all(iFile).incCorr(marker)=baseline(pBaseline,4);
                    segment(iFile).incCorr(marker)=baseline(pBaseline,4);
                    result(marker).incZygo=baseline(pBaseline,5);
                    all(iFile).incZygo(marker)=baseline(pBaseline,5);
                    segment(iFile).incZygo(marker)=baseline(pBaseline,5);
                    % store listnr
                    result(marker).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<-3000)||(b>0)
                            disp([filename_list{iFile},' marker:',int2str(marker)])
                            disp('baseline incorrect')
                        end
                    end
                       
                    %Determine timepoints window 1
                    posB=Markers(iTrial,iMarker).Position;
                    if isnan(b3)
                        t1=round(posB+(b1/1000*SampleRate));
                        t2=round(posB+(b2/1000*SampleRate));
                        result(marker).baselineCorr=mean(Corrugator(iTrial,t1:t2));
                        result(marker).baselineZygo=mean(Zygomaticus(iTrial,t1:t2));
                        result(marker).baseline=b2-b1;
                    else
                        t1=round(posB+(b1/1000*SampleRate));
                        t2=round(posB+(b2/1000*SampleRate));
                        t3=round(posB+(b3/1000*SampleRate));
                        t4=round(posB+(b4/1000*SampleRate));
                        result(marker).baselineCorr=mean(horzcat(Corrugator(iTrial,t1:t2),Corrugator(iTrial,t3:t4)));
                        result(marker).baselineZygo=mean(horzcat(Zygomaticus(iTrial,t1:t2),Zygomaticus(iTrial,t3:t4)));
                        result(marker).baseline=(b2-b1)+(b4-b3);
                    end
                    segment(iFile).timecourse(marker).CorrPr=Corrugator(iTrial,:)/result(marker).baselineCorr*100;
                    segment(iFile).timecourse(marker).ZygoPr=Zygomaticus(iTrial,:)/result(marker).baselineZygo*100;
                    %store the entire trial in 100ms bins
                    for sSignal=1:length(Corrugator(iTrial,:))/binsize %for all 100ms bins during the segment
                        stime1 = round(1+(sSignal-1)*binsize);
                        stime2 = round(1+ sSignal*binsize);
                        if sSignal==length(Corrugator(iTrial,:))/binsize
                            stime2 = round(sSignal*binsize);
                        end
                        % Proportion baseline 3s begin of trial
                        resultSegmentsCorrPr(marker,sSignal)=mean(Corrugator(iTrial,stime1:stime2))/result(1,marker).baselineCorr*100;
                        resultSegmentsZygoPr(marker,sSignal)=mean(Zygomaticus(iTrial,stime1:stime2))/result(1,marker).baselineZygo*100;
                    end
                    segment(iFile).bin100ms(marker).CorrPr=resultSegmentsCorrPr(marker,:);
                    segment(iFile).bin100ms(marker).ZygoPr=resultSegmentsZygoPr(marker,:);

                    
                elseif (marker>=65)&&(marker<=128) % likeability trigger
                    markertrial=marker-64;
                    posL=Markers(iTrial,iMarker).Position;
                    t2=round(posL+(5*SampleRate));
                    %store proportional data for the entire likeability epoch for
                    %visualization purposes
                    all(iFile).timecourse(markertrial).likeCorrPr=Corrugator(iTrial,posL:t2)/result(markertrial).baselineCorr*100;
                    all(iFile).timecourse(markertrial).likeZygoPr=Zygomaticus(iTrial,posL:t2)/result(markertrial).baselineZygo*100;
                    %compute results for the entire likeability trial
                    result(markertrial).likeCorrRawTrial=mean(Corrugator(iTrial,posL:t2));
                    result(markertrial).likeCorrPrTrial=mean(Corrugator(iTrial,posL:t2))/result(markertrial).baselineCorr*100;
                    result(markertrial).likeZygoRawTrial=mean(Zygomaticus(iTrial,posL:t2));
                    result(markertrial).likeZygoPrTrial=mean(Zygomaticus(iTrial,posL:t2))/result(markertrial).baselineZygo*100;
                    
                    for kSignal=1:nr100ms %for all 100ms bins during 5s
                        ktime1 = round(posL + (kSignal-1)*binsize);
                        ktime2 = round(posL + kSignal*binsize);
                        % Proportion baseline 3s begin of trial
                        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:nr1s %for all 1s bins during 5s
                        mtime1 = round(posL + (mSignal-1)*binsizeSecs);
                        mtime2 = round(posL + mSignal*binsizeSecs);
                        % Proportion baseline 3s begin of trial
                        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,:);
                    
                    % include condition likeability based on list order
                    if (marker>=65)&&(marker<=80)
                        switch order
                            case {1,2}
                                likeConditie=1; %positive
                            case {3,4}
                                likeConditie=-1; %negative
                        end
                    elseif (marker>=81)&&(marker<=96)
                        switch order
                            case {1,2}
                                likeConditie=-1; %negative
                            case {3,4}
                                likeConditie=1; %positive
                        end
                    elseif (marker>=97)&&(marker<=112)
                        switch order
                            case {1,2}
                                likeConditie=1; %positive
                            case {3,4}
                                likeConditie=-1; %negative
                        end
                    elseif (marker>=113)&&(marker<=128)
                        switch order
                            case {1,2}
                                likeConditie=-1; %negative
                            case {3,4}
                                likeConditie=1; %positive
                        end
                    end
                    result(markertrial).likeConditie=likeConditie;
                    all(iFile).likeConditie(markertrial)=likeConditie;
                    all(iFile).marker(markertrial)=markertrial;
                    segment(iFile).likeConditie(markertrial)=likeConditie;
                    segment(iFile).marker(markertrial)=markertrial;
                    
                elseif (marker>=129)&&(marker<=192) % affect trigger
                    markertrial=marker-128;
                    posA=Markers(iTrial,iMarker).Position;
                    t2=round(posA+(2.5*SampleRate));
                    t3=round(posA+(5*SampleRate));
                    %store proportional data for the entire affect epoch for
                    %visualization purposes
                    all(iFile).timecourse(markertrial).affectCorrPr=Corrugator(iTrial,posA:t3)/result(markertrial).baselineCorr*100;
                    all(iFile).timecourse(markertrial).affectZygoPr=Zygomaticus(iTrial,posA:t3)/result(markertrial).baselineZygo*100;
                    %compute results for the first and second affect half
                    result(markertrial).affectCorrRawTrial=mean(Corrugator(iTrial,posA:t2));
                    result(markertrial).affectCorrPrTrial=mean(Corrugator(iTrial,posA:t2))/result(markertrial).baselineCorr*100;
                    result(markertrial).affectZygoRawTrial=mean(Zygomaticus(iTrial,posA:t2));
                    result(markertrial).affectZygoPrTrial=mean(Zygomaticus(iTrial,posA:t2))/result(markertrial).baselineZygo*100;
                    
                    for lSignal=1:nr100ms %for all 100ms bins during 5s
                        ltime1 = round(posA + (lSignal-1)*binsize);
                        ltime2 = round(posA + lSignal*binsize);
                        % Proportion baseline 3s begin of trial
                        resultBinAffectCorrPr(markertrial,lSignal)=mean(Corrugator(iTrial,ltime1:ltime2))/result(1,markertrial).baselineCorr*100;
                        resultBinAffectZygoPr(markertrial,lSignal)=mean(Zygomaticus(iTrial,ltime1:ltime2))/result(1,markertrial).baselineZygo*100;
                    end
                    all(iFile).bin(markertrial).AffectCorrPr=resultBinAffectCorrPr(markertrial,:);
                    all(iFile).bin(markertrial).AffectZygoPr=resultBinAffectZygoPr(markertrial,:);

                    for nSignal=1:nr1s %for all 1s bins during 5s
                        ntime1 = round(posA + (nSignal-1)*binsizeSecs);
                        ntime2 = round(posA + nSignal*binsizeSecs);
                        % Proportion baseline 3s begin of trial
                        resultSecsAffectCorrPr(markertrial,nSignal)=mean(Corrugator(iTrial,ntime1:ntime2))/result(1,markertrial).baselineCorr*100;
                        resultSecsAffectZygoPr(markertrial,nSignal)=mean(Zygomaticus(iTrial,ntime1:ntime2))/result(1,markertrial).baselineZygo*100;
                    end
                    all(iFile).binSecs(markertrial).AffectCorrPr=resultSecsAffectCorrPr(markertrial,:);
                    all(iFile).binSecs(markertrial).AffectZygoPr=resultSecsAffectZygoPr(markertrial,:);
                    
                    % include condition affect based on list order
                    if (marker>=129)&&(marker<=144)
                        switch order
                            case {1,3}
                                affectConditie=1; %positive
                            case {2,4}
                                affectConditie=-1; %negative
                        end
                    elseif (marker>=145)&&(marker<=176)
                        switch order
                            case {1,3}
                                affectConditie=-1; %negative
                            case {2,4}
                                affectConditie=1; %positive
                        end
                    elseif (marker>=177)&&(marker<=192)
                        switch order
                            case {1,3}
                                affectConditie=1; %positive
                            case {2,4}
                                affectConditie=-1; %negative
                        end
                    end % if marker condition
                    result(markertrial).affectConditie=affectConditie;
                    all(iFile).affectConditie(markertrial)=affectConditie;
                    segment(iFile).affectConditie(markertrial)=affectConditie;
                    storeMarkertrial=0; %LET OP!!!!! op 0 gezet voor plaatjes analyse.
                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
                % 'sjCode\tSjNr\tlist\tincCorr\tincZygo\tmarkertrial\tlikeConditie');
                % for t=1:50
                %     fprintf(fidBinLike, '\tLikeCorrPct %i', t);
                % end
                % fprintf(fidBinLike, '\tLikeCorrPctS1\tLikeCorrPctS2\tLikeCorrPctS3\tLikeCorrPctS4\tLikeCorrPctS5\tLikeCorrPctTrial');
                % for u=1:50
                %     fprintf(fidBinLike, '\tLikeZygoPct %i', u);
                % end
                % fprintf(fidBinLike, '\tLikeZygoPctS1\tLikeZygoPctS2\tLikeZygoPctS3\tLikeZygoPctS4\tLikeZygoPctS5\tLikeZygoPctTrial\n');
                % ==> 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).baseline,result(markertrial).baselineCorr,result(markertrial).baselineZygo,...
                    resultBinLikeCorrPr(markertrial,1:nr100ms),resultSecsLikeCorrPr(markertrial,1:nr1s),...
                    result(markertrial).likeCorrPrTrial,resultBinLikeZygoPr(markertrial,1:nr100ms),...
                    resultSecsLikeZygoPr(markertrial,1:nr1s),result(markertrial).likeZygoPrTrial);
                fprintf(fidBinLike,'\n');
                
                % Affect
                % 'sjCode\tSjNr\tlist\tincCorr\tincZygo\tmarkertrial\tlikeConditie\taffectConditie');
                % for t=1:50
                %     fprintf(fidBinAffect, '\tAffectCorrPct %i', t);
                % end
                % fprintf(fidBinAffect, '\tAffectCorrPctS1\tAffectCorrPctS2\tAffectCorrPctS3\tAffectCorrPctS4\tAffectCorrPctS5\tAffectCorrPctTrial');
                % for u=1:50
                %     fprintf(fidBinAffect, '\tAffectZygoPct %i', u);
                % end
                % fprintf(fidBinAffect, '\tAffectZygoPctS1\tAffectZygoPctS2\tAffectZygoPctS3\tAffectZygoPctS4\tAffectZygoPctS5\tAffectZygoPctTrial\n');
                % ==> Add Affect bin results to file 3s Baseline begin trial
                fprintf(fidBinAffect,'%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).affectConditie,...
                    result(markertrial).baseline,result(markertrial).baselineCorr,result(markertrial).baselineZygo,...
                    resultBinAffectCorrPr(markertrial,1:nr100ms),resultSecsAffectCorrPr(markertrial,1:nr1s),...
                    result(markertrial).affectCorrPrTrial,resultBinAffectZygoPr(markertrial,1:nr100ms),...
                    resultSecsAffectZygoPr(markertrial,1:nr1s),result(markertrial).affectZygoPrTrial);
                fprintf(fidBinAffect,'\n');
                
            
                
                storeMarkertrial=0;
            end
        end %iMarker
    end %iTrial
end %iFile
%Export result all subjects
%allFile=[adir,'ACE-BRaT_results_',num2str(length(files)),'sjs_',date,'.mat'];
%save(allFile,'all','-v7.3');
segmentFile=[adir,'ACE-BRaT_timecourse_',num2str(length(files)),'sjs_',date,'.mat'];
save(segmentFile,'segment','-v7.3');
fclose('all');