
function [trl, event] = trialfun_AVE(cfg);
%% Trialfunction subject 0X



% read the header information and the events from the data
hdr   = ft_read_header(cfg.dataset);
event = ft_read_event(cfg.dataset);

% search for "trigger" events
value  = [event(find(strcmp( cfg.trialdef.eventtype, {event.type}))).value]';
sample = [event(find(strcmp( cfg.trialdef.eventtype, {event.type}))).sample]';
time_events = sample / hdr.Fs;
plot(time_events,value, '.', 'markersize', 30) % see triggers as a function of time (seconds)

% After visually inspection of data, and remembering the problem with this

%error_trials = find( time_events<100);
%value(error_trials) = [];
%sample(error_trials) = [];

% determine the number of samples before and after the trigger
pretrig  = -round(cfg.trialdef.prestim  * hdr.Fs);
posttrig =  round(cfg.trialdef.poststim * hdr.Fs);

% look for the combination of a trigger "7" followed by a trigger "64"
% for each trigger except the last one
trl = [];
for j = 1:(length(value))
    trg1 = value(j);
    %  trg2 = value(j+1);
    if ismember(trg1, cfg.trialdef.eventvalue)
      
        trlbegin = sample(j) + pretrig;
        trlend   = sample(j) + posttrig;
        offset   = pretrig;
        newtrl   = [trlbegin trlend offset  trg1];
        trl      = [trl; newtrl];
    end   
end

size(trl,1) == 576 % (96 trials x 6 blocks)

disp (['total number of original trials ', num2str(size(trl,1))]);

end

