% waveform / trial / response averaging; save timesteps in a matrix
%
% Input:
%   colData ... raw or preprocessed data of a single channel (column)
%   nstim   ... vector pointing to the first timestep
% Output:
%   avgData   ... data structure containing
%    .mtx   ... averaged trials aligned in the rows of a matrix
%    .nrw   ... number of rows (i.e., trails)
%    .ncl   ... number of columns (i.e., time steps per trial)
%    .offst ... offset of time step zero
%    .time  ... time vector
%
% (c) Gerald Fischer 2021
% =======================================================================
function [avgData] = trialAverage(colData,nstim,fsample)
  % default sample rate 
  if nargin < 3
    fsample = 9600; % default sample rate
  end
  % align data
  [alignData] = alignData01(colData,nstim); 
  % build structure
  avgData.mtx = zeros(alignData.nrw,alignData.ncl);
  avgData.nrw = alignData.nrw;
  avgData.ncl = alignData.ncl;
  avgData.offst = alignData.offst;
  %
  % first order averaging
  % ---------------------
  avgData.mtx(1,:)=alignData.mtx(1,:);
  for n=2:avgData.nrw
      avgData.mtx(n,:)=avgData.mtx(n-1,:)+alignData.mtx(n,:);
  end % end for
  for n=2:avgData.nrw
      avgData.mtx(n,:)=avgData.mtx(n,:)/n;
  end % end for
  % time vector
  % -----------
  avgData.time(1,:)=([1:avgData.ncl]-avgData.offst)/fsample;
end % function

