function [trl] = trials_extract(cfg);

event = read_fcdc_event(cfg.dataset);

back_indx = [find(strcmp('backpanel trigger', {event.type}))];


%[backpanel, frontpanel] = read_ctf_trigger(cfg.dataset);
%back_indx  = find(backpanel);
%front_indx = find(frontpanel);

fprintf('There are %d samples, indicating about %d minutes of sampling\n', length(event), round(length(event)*0.5/60));
fprintf('found %d triggers on the backpanel\n', length(back_indx));


% select only the trigger samples where a real trigger occurred
event  = event(back_indx);


% start with an empty trial definition
trl = [];
for i=1:length(event)
    % take four subsequent triggers
    if sum(event(i).value == cfg.trialdef.stim) % if the event is a stimulus
        if sum(event(i+1).value == cfg.trialdef.resp) % and the next event is a correct response
            fprintf('found a usable stimulus period at sample %d\n', back_indx(i));
            trlbegin  = event(i).sample - round(cfg.trialdef.prestim*cfg.fsample); % begin sample is stimulus onset - prestim interval
            trlend    = event(i).sample + round(cfg.trialdef.poststim*cfg.fsample); % end sample is stim onset + post stim interval
            %trlend    = event(i+1).sample - round(cfg.trialdef.preresp*cfg.fsample); % end sample is response onset - preresp interval
            trllen = (trlend - trlbegin)./cfg.fsample;
            trloffset = cfg.trialdef.prestim*cfg.fsample; % trial offset is prestimulus interval (0.2 sec)
            newtrl = [trlbegin trlend trloffset];
            trl = [trl; newtrl];
            %end
        end
    end
end

fprintf('created %d trials\n', size(trl,1));
