function varargout=dopEventScreen(markData,evStack,actRejData,varargin)
% dopOSCCI Mark II: dopEventScreen ~ 19-Jan-2012 (last edit)
%
% create an epoch filter for problematic trials based upon:
% - amount of available data (markData.short)
% - activation outside activation rejection range (actRejData.(name).reject)
%
% two levels of screening (could be more)
% - first levels is nothing, includes all trials
% - second levels screens for acceptable activation (could be the same as
%   first level)
%

fprintf('\n%s\n\t%s',['Running ',mfilename],...
    'Screen Event Epochs:');
try
    inputs.varargin=varargin;
    inputs.defaults=struct('inShort',0,...); % include epochs with inadequate data
        'evChs',0,... % doppler external channel numbers - might use this for reports...
        'eventLabels','mark1',...); % names of event channels
        'actRej',[70 130],...); % activation rejection values
        'evType',2,... % event type: 2 = base + poi, 1 = poi, 0 = base
        'evMatch',0,... % corresponding event number if evType < 2
        'epSelLabels',[]); % epoch selection labels {'all','act','man','scrn','bal'};
    es=setGetInputsStruct(inputs);
    
    es.translation='event/epoch screen';
    es.structAbbreviations='es';
    es.mk=markData; clear markData
    es.stack=evStack; clear evStack
    es.actRejData=actRejData; clear actRejData
    es.skip=0; % check to see if there are any trials available
    es.skipReason=[];
    if isempty(es.epSelLabels) % use default:
        % struct function doesn't accept cell inputs
        es.epSelLabels={'all','length','act'};%,'man','scrn','bal'};
    end
    
    %% notes
    es.out.notes=sprintf('%s\n\t%s\n\t%s\n\t%s\n\t%s\n\n\t%s\n\t%s\n\t%s\n\t%s\n\t%s\n',...
        'Event/Epoch Screening notes:',...
        '> screening output includes 3 levels for each event channel:',...
        '1 (first column) = no screening, all epochs included',...
        '2 (second column) = length screening:',...
        ' - data length:',...
        'If raw data length is inadequate for specified epoch,',...
        ' short at start or short at end of data file',...
        '3 (third column) = activation rejection:',...
        ' - activation rejection:',...
        ['activation less than ',num2str(es.actRej(1)),...
        ' and greater than ',num2str(es.actRej(2))]);
    
    
    es.nev=length(es.evChs); % number of event channels
    for i=1:es.nev
        es.ch=i; % event channel
        es.en=es.eventLabels;% event name
        if iscell(es.eventLabels)
            es.en=es.eventLabels{es.ch};
        end
        es.nmks=length(es.mk.(es.en).marks); % number of marks
        es.out.(es.en)(1:es.nmks,1)=ones(es.nmks,1); % all epochs (first level) no screen
        
        %% short data/length
        es.out.(es.en)(1:es.nmks,2)=ones(es.nmks,1); % all epochs screen if short
        %         if isfield(es.mk,'short') && ~es.inShort % short epochs noted && not to be included
        if isfield(es.stack,'short') && ~es.inShort % short epochs noted && not to be included
            if isfield(es.stack.short,es.en) % for this particular event name
                es.sfs=fieldnames(es.stack.short.(es.en)); % short fields
                es.shortScreen=ones(es.nmks,1);
                for j=1:length(es.sfs)
                    es.sf=es.sfs{j}; % short field
                    % these values should be proportions of epoch missing,
                    % therefore rounding up short lead to removal of
                    % problematic epoch
                    switch es.sf
                        case 'start'
                            es.shortScreen(1:ceil(es.stack.short.(es.en).(es.sf)))=0;
                        case 'finish'
                            ceil(es.stack.short.(es.en).(es.sf))
                            es.shortScreen(1+es.nmks-ceil(es.stack.short.(es.en).(es.sf)))=0;
                    end
                end
                % now put it together in logical array
                es.out.(es.en)(1:es.nmks,2)=...
                    and(es.out.(es.en)(1:es.nmks,2),es.shortScreen);
            end
        end
        %% activation rejection
        es.out.(es.en)(1:es.nmks,3)=es.actRejData.(es.en).reject==0; % if not rejected then keep
        if ~sum(es.out.(es.en)(1:es.nmks,3))
            es.skip=es.skip+1; % no suitable trials
            es.skipReason='No suitable epochs';
        end
        
        %% Event matching
        % seems incorrect to calculate LIs based upon periods of interest
        % that have been baseline corrected with a problematic baseline
        % period.  So these should be screened out also...
        % note: just POI only events - base only doesn't matter as much -
        % less critical calculations based upon these and it's possible
        % that multiple events could be linked to them
        if es.evType(i) == 1 % poi and event matching required
            es.tmp.matchLabel = es.eventLabels{es.evMatch(i)};
            fprintf([' Checking if more non-rejected epochs in %s POI '...
                'event compared with matching baseline (%s).\n'],...
                es.eventLabels{i},es.tmp.matchLabel);
            
            for j = 1 : size(es.out.(es.eventLabels{i}),2)
                es.tmp.okay1 = find(es.out.(es.eventLabels{i})(:,j)==1);
                es.out.(es.eventLabels{i})(:,j) = logical(floor((es.out.(es.eventLabels{i})(:,j) + es.out.(es.tmp.matchLabel)(:,j))/2));
                es.tmp.okay2 = find(es.out.(es.eventLabels{i})(:,j)==1);
                for jj = 1 : numel(es.tmp.okay1)
                    if ~sum(es.tmp.okay1(jj)==es.tmp.okay2)
                        fprintf('\t - %u now also screened (%s)\n',es.tmp.okay1(jj),es.epSelLabels{j});
                    end
                end
                
            end
        end
    end
    %% set ouputs
    es.out.columnLabels={es.epSelLabels{1} es.epSelLabels{2} es.epSelLabels{3}};%{'allEpochs','scrnEpochs'};
    varargout{1}=es.out;
    varargout{2}=es.skip;
    varargout{3}=es.skipReason;
    fprintf('\t%s\n','Done');
catch err
    %% catch dopOSCCI error
    %
    save(dopOSCCIdebug(mfilename));rethrow(err);
    %     dopOSCCIcrash(err,es,mfilename);
end

clear es inputs

