function trl = mousetrialfun(cfg)

% this function requires the following fields to be specified
% cfg.dataset
% cfg.trialdef.threshold
% cfg.trialdef.prestim
% cfg.trialdef.poststim

hdr = ft_read_header(cfg.dataset);
trigchan = find(strcmp(hdr.label, 'HL1'));
trigger_data = ft_read_data(cfg.dataset, 'chanindx', trigchan); % read trigger data
trigger_data = -trigger_data; % flip sign
trigger_data = trigger_data - median(trigger_data); % shift

if isfield(cfg, 'trialdef') && isfield(cfg.trialdef, 'threshold')
  trigger_threshold = cfg.trialdef.threshold;
else
  trigger_threshold = 0.5*max(trigger_data);
end

% give some feedback
figure
plot(trigger_data, 'b')
hold on
plot(trigger_threshold*ones(size(trigger_data)), 'g')

stim_duration = cfg.trialdef.prestim  * hdr.Fs; % number of samples
rest_duration = cfg.trialdef.poststim * hdr.Fs; % number of samples

% extracts, trigger timing ------------------------------------------------
data1 = find(abs(trigger_data) > trigger_threshold);      % exceed threshold
data2 = find(data1-[0,data1(1,1:end-1)] > rest_duration); % exceed 'rest_duration'
idx = data1(data2);
clear data1 data2

trigger_event(1,:) = idx;
clear idx

% give some additional feedback
plot(trigger_event(1,:), trigger_threshold, 'rx')

% extracts, trigger contents ----------------------------------------------
for tr = 1:size(trigger_event,2)
  temp_data = abs(trigger_data(trigger_event(1,tr):trigger_event(1,tr)+stim_duration-1));
  idx = find_cross(temp_data, trigger_threshold, 'down'); clear temp_data
  trigger_event(2,tr) = size(find(idx == 1),2) / (stim_duration / hdr.Fs); 
end 

trl       = [trigger_event(1, :) - stim_duration+1; trigger_event(1, :) + rest_duration]';
trl(:, 3) = ones(size(trl, 1), 1) * -stim_duration;

function idx = find_cross(data, thr, type)
% find peaks.
% data = 1 by n vector.
% thr = the crossing point.
% type = 'both', 'up', 'down'.
% default type: 'both'.

if size(data,1) > 1
  data = data.';
  if size(data,2) > 1
    error('data must be vector form')
  end
end

% up crossing
tidx1 = zeros(1,size(data,2)-1);
tidx2 = zeros(1,size(data,2)-1);
idx1 = zeros(1,size(data,2)-1);
tidx1(data(1,1:end-1) <= thr) = 1;
tidx2(data(1,2:end) > thr) = 1;
idx1(tidx1 + tidx2 == 2) = 1; clear tidx1 tidx2

% down crossing
tidx1 = zeros(1,size(data,2)-1);
tidx2 = zeros(1,size(data,2)-1);
idx2 = zeros(1,size(data,2)-1);
tidx1(data(1,1:end-1) >= thr) = 1;
tidx2(data(1,2:end) < thr) = 1;
idx2(tidx1 + tidx2 == 2) = 1; clear tidx1 tidx2

% both
idx0 = zeros(1,size(data,2)-1);
idx0(idx1 + idx2 > 0) = 1;

if nargin == 2
  idx = idx0;
elseif nargin == 3
  if strcmpi(type,'both')
    idx = idx0;
  elseif strcmpi(type,'up')
    idx = idx1;
  elseif strcmpi(type,'down')
    idx = idx2;
  end
end