function [data] = resampledata(cfg, data);

% RESAMPLEDATA performs a resampling of the data according to cfg
%
% Use as
%   [data] = resampledata(cfg, data)
%
% The data should be organised in a structure as obtained from
% the PREPROCESSING function. The configuration should be according to
%   cfg.resamplefs = frequency at which the data will be resampled (default 256 Hz)
%   cfg.detrend    = 'no' or 'yes' (default) prior to resampling
%
% the following fields in the structure 'data' are changed
%   data.trial
%   data.fsample
%   data.offset
%   data.time
%
% the following fields are added and filled with original values
%   data.origfsample
%   data.origoffset
%   data.origtime

% Copyright (c) 2003, FC Donders Centre, Markus Siegel
%
% $Log: resampledata.m,v $
% Revision 1.3  2004/11/02 14:32:28  roboos
% included cfg.detrend in help
% fixed bug in timeaxis (inconsistent with offset due to rounding error)
% added cfg, cfg.version and cfg.previous to output
%
% Revision 1.2  2004/09/02 09:42:43  marsie
% initial CVS release
% included linear detrending (default)
%

% set the defaults
if ~isfield(cfg, 'resamplefs'), cfg.resamplefs = 256;  end
if ~isfield(cfg, 'detrend'),    cfg.detrend = 'yes';   end

% compute the ratio between new and old sampling frequencies
rfact = cfg.resamplefs/data.fsample;

% remember these original fields
data.origfsample = data.fsample;
data.origoffset  = data.offset;
data.origtine    = data.time;

% recompute these fields
data.fsample = cfg.resamplefs;
data.offset  = ceil(data.offset * rfact);

nch = length(data.label);
ntr = length(data.trial);
fprintf('resampling data\noriginal sampling rate: %d Hz\nnew sampling rate: %d Hz\n',data.origfsample,cfg.resamplefs);
for itr = 1:ntr
  fprintf('processing trial: %d\n',itr);
  if strcmp(cfg.detrend,'yes')
    data.trial{itr} = resample(detrend(data.trial{itr}'),cfg.resamplefs,data.origfsample)';
  else
    data.trial{itr} = resample(data.trial{itr}',cfg.resamplefs,data.origfsample)';
  end
  % remember and recompute the time axis
  data.origtime{itr} = data.time{itr};
  data.time{itr}     = offset2time(data.offset(itr), data.fsample, size(data.trial{itr},2));
end

% add version information to the configuration
try
  % get the full name of the function
  cfg.version.name = mfilename('fullpath');
catch
  % required for compatibility with Matlab versions prior to release 13 (6.5)
  [st, i] = dbstack;
  cfg.version.name = st(i);
end
cfg.version.id = '$Id: resampledata.m,v 1.3 2004/11/02 14:32:28 roboos Exp $';
cfg.previous = data.cfg;
data.cfg = cfg;
