function dop=dopEventBaseCorrect(dop)
% dopOSCCI Mark II: dopEventBaseCorrect ~ 11-11-2010 (last edit)
%
% corrects the event data epoch by adjusting for average activation in the
% baseline period.
%
% uses dop.filter info to adjust the dop.stack variable - the dop.stack
% variable will be altered.
%
% Stim Only Event Type:
% baseline correction for stim only event type (see dopTaskDef) uses the
% base match (dop.def.evMath) variable to determine the info used for the
% baseline correction.
%
fprintf('\n%s\n\t%s\n',['Running ',mfilename],...
    'Baseline correcting Event Data:');
try
    dop.bc.translation='baseline correction';
    dop.bc.evNames=dop.stack.evNames; % prior 29-10-10 fieldnames(dop.stack);
    dop.bc.done=[]; % keep a record on events corrected as if base type event comes before stim only, need to do stim first
    for i=1:length(dop.bc.evNames)
        dop.bc.evn=i; % channel number
        dop.bc.en=dop.bc.evNames{dop.bc.evn}; % event name
        fprintf('\t\t%s',dop.bc.en);
        % subtract mean baseline for each event epoch from each event epoch
        % this uses an array operation which is quite tidy.
        switch dop.def.evType(i)
            case 0 % base - must to matching stim only first!!!
                for j=1:length(dop.def.evMatch)
                    if dop.def.evMatch(j)==i
                        dop.bc.sn=dop.bc.evNames{j}; % base name
                        dop.bc.done(end+1)=j;
                        fprintf('\t%s',['(Correcting ''',dop.bc.sn,''' first)']);
                        dop.stack.(dop.bc.sn)=bsxfun(@minus,dop.stack.(dop.bc.sn),...
                            mean(dop.stack.(dop.bc.en)(:,dop.filter.(dop.bc.en).base,:),2));
                    end
                end
                dop.stack.(dop.bc.en)=bsxfun(@minus,dop.stack.(dop.bc.en),...
                    mean(dop.stack.(dop.bc.en)(:,dop.filter.(dop.bc.en).base,:),2));
            case 1 % stimulus only event marker - requires different base
                if sum(i==dop.bc.done)
                     fprintf('\t%s',('already corrected'));
                else
                dop.bc.bn=dop.bc.evNames{dop.def.evMatch(i)}; % base name
                fprintf('\t%s',['(Using ''',dop.bc.bn,''' event for baseline)']);
                dop.stack.(dop.bc.en)=bsxfun(@minus,dop.stack.(dop.bc.en),...
                    mean(dop.stack.(dop.bc.bn)(:,dop.filter.(dop.bc.bn).base,:),2));
                end
            otherwise % base or regular
                dop.stack.(dop.bc.en)=bsxfun(@minus,dop.stack.(dop.bc.en),...
                    mean(dop.stack.(dop.bc.en)(:,dop.filter.(dop.bc.en).base,:),2));
        end
        fprintf('\n');
    end
    fprintf('\n\t%s\n','Done');
    %% remove the bc field
% type of temporary data storage
dop=rmfield(dop,'bc');
catch err
    %% catch dopOSCCI error
    % 
save(dopOSCCIdebug(mfilename));rethrow(err); 
%     dopOSCCIcrash(err,dop,mfilename);
end


