function dop=dopSessionCollect(dop)
% dopOSCCI Mark II: dopSessionCollect ~ 16-11-2010 (last edit)
%
% collect session information until we reach final session for particular
% individual and then summarise it together.
%
% dopSessionSet and dopSessionCollect operate by rearraning the
% dop.data.fileList variable in order of individual session files.  The
% data from each session is 'stacked' to create a single stack consisting
% of all the sessions and then the summary functions are re-run on this
% data.
%
% therefore, any messing with the dop.data.fileList after this point
% (dopSessionSet) will mess up the session summary.
%
% Uses dop.ses structure from dopSessionSet
% dop.ses
%       fileNameLoc: [1x49 char]
%              okay: 1
%      inListReport: [1x26 char]
%     sesListReport: [1x28 char]
%           noMatch: 0
%       xListReport: [1x32 char]
%          fileList: {1x8 cell}
%          sesNames: {'mon'  'tues'  'wed'  'thur'}
%          indFiles: [1x2 struct] ***
%        fileReport: [1x146 char]
%                 n: 2
%              nSes: 4

fprintf('%s\n',['Running ',mfilename]);
try
    if ~dop.sum.skip && ~dop.sum.quit && dop.def.sesFileChk % request to check session file
        %% collect session data
        fprintf('\t%s\n','Collecting Session data...');
        
        %% > check dop.data.fileList
        % make sure this is inline with the session list expectations
        if or(strcmp(dop.sum.fileNameLoc,dop.ses.indFiles(dop.ses.ind).files{dop.ses.session}),... % file name location
                strcmp(dop.sum.fileName,dop.ses.indFiles(dop.ses.ind).files{dop.ses.session}))  % or file name match
            fprintf('\t\t%s\n',['Session ',num2str(dop.ses.session),...
                ' (',dop.ses.sesNames{dop.ses.session},')']);
            
            dop.ses.vars={'stack','avg','dif','scrn'}; % variables to be session stacked
            for i=1:length(dop.mk.evNames) % for each event
                dop.tmp.en=dop.mk.evNames{i};
                for j=1:length(dop.ses.vars); % for each variable
                    dop.tmp.var=dop.ses.vars{j};
                    if ~isfield(dop.ses,dop.tmp.var) || ...
                            ~isfield(dop.ses.(dop.tmp.var),(dop.tmp.en))
                        dop.ses.(dop.tmp.var).(dop.tmp.en)=dop.(dop.tmp.var).(dop.tmp.en);
                    else
                        dop.ses.(dop.tmp.var).(dop.tmp.en)=...
                            vertcat(dop.ses.(dop.tmp.var).(dop.tmp.en),dop.(dop.tmp.var).(dop.tmp.en));
                    end
                end
                % calculate the number of epochs available after screening
                % use the for balancing between sessions if required.
                dop.ses.scrnEpochs.(dop.tmp.en)(dop.ses.session)=sum(dop.scrn.(dop.tmp.en)(:,end));
                dop.ses.allEpochs.(dop.tmp.en)(dop.ses.session)=sum(dop.scrn.(dop.tmp.en)(:,1));
            end
            if isempty(dop.ses.combinedName)
                dop.ses.combinedName=dop.sum.fileTxt;
            else
                dop.ses.combinedName=[dop.ses.combinedName,'_',dop.sum.fileTxt];
                dop.sum.fileTxt=dop.ses.combinedName;
            end
            
            %% check if final session summarised
            if or(strcmp(dop.sum.fileNameLoc,dop.ses.indFiles(dop.ses.ind).files{end}),... % file name location
                    strcmp(dop.sum.fileName,dop.ses.indFiles(dop.ses.ind).files{end}))  % or file name match
                fprintf('%s\n\t%s\n\t%s\n',...
                    '----------------------------------',...
                    'Finished Individual''s final Session Summary:',...
                    'Updating to combined session dop structures...');
                % move data into dop variables
                for i=1:length(dop.mk.evNames) % for each event
                    dop.tmp.en=dop.mk.evNames{i};
                    for j=1:length(dop.ses.vars); % for each variable
                        dop.tmp.var=dop.ses.vars{j};
                        dop.(dop.tmp.var).(dop.tmp.en)=dop.ses.(dop.tmp.var).(dop.tmp.en);
                    end
                    % calculate the number of epochs available after screening
                    % use the for balancing between sessions if required.
                    %                 dop.ses.scrnEpochs.(dop.tmp.en)(dop.ses.session)=sum(dop.scrn.(dop.tmp.en)(:,2));
                end
                %% > behavioural
                % see dopBehSummary
%                 if dop.def.behFileChk
%                     for i=1:numel(dop.beh.behNames)
%                         dop.tmp.behFilter=dop.beh.filter.(dop.beh.behNames{i});
%                         for j=2:dop.ses.nSes
%                             % stack them on top of each other
%                             dop.beh.filter.(dop.beh.behNames{i})=vertcat(dop.beh.filter.(dop.beh.behNames{i}),dop.tmp.behFilter);
%                         end
%                     end
%                 end
                %% session epoch balancing
                % consider doing this here
%                 if sum(dop.ses.bal)
%                     dop.scrn.labels{end+1}=dop.def.saveEpochSelectionLabels{end}; % 'bal'
%                     if length(dop.scrn.saveData)<length(dop.scrn.labels)
%                         dop.scrn.saveData(end+1)=dop.def.saveEpochSelection(end);
%                         dop.scrn.saveGraphData(end+1)=dop.def.saveEpochSelectionGraph(end);
%                     end
%                 end
%                 if dop.ses.bal(1)
%                     dop.def.saveEpochSelection(3)=1; % this can only run during summary session
%                 end
%                 if dop.ses.bal(2)
%                     dop.def.saveGraphData(3)=1;
%                 end
                if sum(dop.ses.bal) % balance
                    dop.scrn.labels{end+1}=dop.def.saveEpochSelectionLabels{end}; % 'bal'
                    if length(dop.scrn.saveData)<length(dop.scrn.labels)
                        dop.scrn.saveData(end+1)=dop.def.saveEpochSelection(end);
                        dop.scrn.saveGraphData(end+1)=dop.def.saveEpochSelectionGraph(end);
                        dop.scrn.calcData(end+1)=dop.def.saveEpochSelection(end);
                        dop.scrn.calcGraphData(end+1)=dop.def.saveEpochSelectionGraph(end);
                    end
                                        
                    for i=1:length(dop.mk.evNames) % for each event
                        if dop.def.evType(i)
                            dop.tmp.en=dop.mk.evNames{i};
%                             dop.scrn.columnLabels{3}=[dop.def.saveEpochSelectionLabels{3},'Epochs']; % balEpochs
                            dop.scrn.(dop.tmp.en)(:,end+1)=dop.scrn.(dop.tmp.en)(:,end); % same as scrn to begin with
                            dop.tmp.eps=dop.ses.scrnEpochs.(dop.tmp.en); % screened epochs
                            dop.tmp.aeps=dop.ses.allEpochs.(dop.tmp.en); % all available epochs (might be some missing
                            [dop.tmp.min dop.tmp.minInd]=min(dop.tmp.eps);
                            if sum(dop.ses.bal)  ... % this may change if probelm found (see below)
                                    && dop.tmp.min(1)<max(dop.tmp.eps)
                                % min < max, therefore imblance - therefore
                                % drop trials from session without min epochs
                                % default = drop 1st available trial
                                for j=1:numel(dop.tmp.eps)
                                    if sum(dop.tmp.eps(j)~=dop.tmp.min) % not a min
                                        dop.tmp.range=... % epochs under consideration...
                                            1+(j-1)*dop.tmp.aeps(j):(j)*dop.tmp.aeps(j);
                                        dop.tmp.dif=dop.tmp.eps(j)-dop.tmp.min; % how many too many?
                                        jj=1;
                                        dop.tmp.drop=[];
                                        while jj<numel(dop.tmp.range) && numel(dop.tmp.drop)<dop.tmp.dif
                                            if dop.scrn.(dop.tmp.en)(dop.tmp.range(jj),end)
                                                dop.tmp.drop(end+1)=dop.tmp.range(jj);
                                                dop.scrn.(dop.tmp.en)(dop.tmp.range(jj),end)=0;
                                            end
                                            jj=jj+1;
                                        end
%                                         while or(~dop.scrn.(dop.tmp.en)(dop.tmp.range(jj),end),...
%                                                 jj<numel(dop.tmp.range)); jj=jj+1;
%                                             
%                                         end
                                        if jj==length(dop.tmp.range) && dop.scrn.(dop.tmp.en)(dop.tmp.range(jj),end)==0
                                            fprintf('%s\n\t%s\n',...
                                                '!!!!!!!!!!!!!!!!!',...
                                                'Problem with epoch balancing - balancing cancelled');
                                            dop.scrn.labels(end)=[];
                                        else
                                            fprintf('\t%s\n',...
                                                ['Screened epoch ',num2str(dop.tmp.drop),...
                                                ' from session ',num2str(j),' (',dop.ses.sesNames{j},')']);
%                                             dop.scrn.(dop.tmp.en)(dop.tmp.range(jj),end)=0; % screen epoch
                                        end
                                    end
                                end
%                             else
%                                 dop.scrn.columnLabels={dop.scrn.columnLabels{1},dop.scrn.columnLabels{2}};
                            end
                        end
                    end
                    %% report
                    if sum(dop.ses.bal) % balance
                        dop.ses.(dop.tmp.en).balReport=...
                            sprintf('%s\n\t%s\n',...
                            ['Session Balance Report - ',dop.tmp.en],...
                            [num2str(sum(dop.scrn.(dop.tmp.en)(:,end))),' of ',...
                            num2str(sum(dop.tmp.aeps)),' total epochs ',...
                            'available for Session epoch Balanced Summary']);
                        disp(dop.ses.(dop.tmp.en).balReport);
                    end
                end
                %% run combined summary
                fprintf('%s\n\t%s\n',...
                    '----------------------------------',...
                    'Running Combined Session Summary:');
                dop.ses.session=dop.ses.session+1;
                dop.sum.fileName=dop.ses.combinedName;
                % run summary functions on the large stacks...
                % calculate summaries
                dop=dopDataCalc(dop);
                % behavioural summary
                dop=dopBehSummary(dop);
                % save data
                dop=dopSaveSum(dop); % save the summary data to file
                % save graph data
                dop=dopGraphDataSave(dop);
                % create graphs
                dop=dopGraph(dop);
                % individual summary report
                dop=dopSumReport(dop);
                
                %% ready for next individual
                dop=dopSessionReset(dop);
%                 dop.ses.ind=dop.ses.ind+1;
%                 dop.ses.session=1;
%                 dop.ses.combinedName=[];
%                 if dop.ses.bal(1)
%                     dop.def.saveEpochSelection(3)=0; 
%                     % this can only run during combination summary session
%                     % can't find variable in dopSaveSum otherwise
%                 end
%                 if dop.ses.bal(2)
%                     dop.def.saveGraphData(3)=0;
%                 end
%                 for i=1:length(dop.ses.vars);
%                     dop.tmp.var=dop.ses.vars{i};
%                     if isfield(dop.ses,dop.tmp.var)
%                         dop.ses=rmfield(dop.ses,dop.tmp.var);
%                     end
%                 end
%                 if isfield(dop.
            else
                dop.ses.session=dop.ses.session+1;
            end
        else
            %% error
            fprintf('\n%s\n%s\n\t%s\n\t%s\n\t%s\n',...
                '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!',...
                'Session Summary Error',...
                'Problem with order of dop.data.fileList',...
                ' > possible the list has been modified after dopSessSet',...
                'Session Summary will not be completed (dop.def.sesFileChk set to 0)');
            dop.def.sesFileChk=0;
        end
        %% clear tmp variable
        if isfield(dop,'tmp')
            dop=rmfield(dop,'tmp');
        end
    else
        fprintf('\t%s\n','Session summary not requested');
    end
catch err
    %% catch dopOSCCI error
    % 
save(dopOSCCIdebug(mfilename));throw(err); 
%     dopOSCCIcrash(err,dop,mfilename);
end