function a1_prepare_preprocessing(id, rootpath)

% prepare (i.e. filter + downsample data) for ICA1

if ismac % run if function is not pre-compiled
    id = '1'; % test for example subject
    currentFile = mfilename('fullpath');
    [pathstr,~,~] = fileparts(currentFile);
    cd(fullfile(pathstr,'..', '..'))
    rootpath = pwd;
end

% inputs
pn.eeg_BIDS = fullfile(rootpath, 'data', 'inputs', 'rawdata', 'eeg_BIDS');
pn.channel_locations = fullfile(rootpath, 'data', 'inputs', 'rawdata', 'channel_locations');
pn.events = fullfile(rootpath, 'data', 'inputs', 'rawdata', 'events');
pn.tools = fullfile(rootpath, 'tools');
% outputs
pn.eeg_ft = fullfile(rootpath, 'data', 'outputs', 'eeg');
pn.history = fullfile(rootpath, 'data', 'outputs', 'history');

if ismac % run if function is not pre-compiled
     addpath(fullfile(pn.tools, 'fieldtrip')); ft_defaults;
     addpath(fullfile(pn.tools, 'helpers'));
end

%% define IDs for visual screening

% N = 33
IDs = tdfread(fullfile(pn.eeg_BIDS, 'participants.tsv'));
IDs = cellstr(IDs.participant_id);

id = str2num(id);

% load data
cfg_preproc           = [];
cfg_preproc.datafile  = ...
    fullfile(pn.eeg_BIDS, IDs{id}, 'eeg', [IDs{id}, '_task-xxxx_eeg.eeg']);

% load header & event information
config              = ft_read_header(cfg_preproc.datafile);
config.data_file    = cfg_preproc.datafile;
config.mrk          = ft_read_event(cfg_preproc.datafile);

% define reading & preprocessing parameters
cfg_preproc.channel     = {'all'};

% get all data first, then apply specific steps only for subsets
data_eeg = ft_preprocessing(cfg_preproc);

%% preprocessing

cfg_preproc               = [];                                 
cfg_preproc.channel       = {'all'};

cfg_preproc.continuous  = 'yes';
cfg_preproc.demean      = 'yes';

cfg_preproc.reref       = 'yes';
cfg_preproc.refmethod   = 'avg';
cfg_preproc.refchannel  = {'M1', 'M2'};
cfg_preproc.implicitref = 'POz';

cfg_preproc.hpfilter    = 'yes';
cfg_preproc.hpfreq      = 1;
cfg_preproc.hpfiltord   = 4;
cfg_preproc.hpfilttype  = 'but';

cfg_preproc.lpfilter    = 'yes';
cfg_preproc.lpfreq      = 100;
cfg_preproc.lpfiltord   = 4;
cfg_preproc.lpfilttype  = 'but';

data_eeg = ft_preprocessing(cfg_preproc, data_eeg);

% define settings for resampling
cfg_resample.resamplefs = 250;
cfg_resample.detrend    = 'no';
cfg_resample.feedback   = 'no';
cfg_resample.trials     = 'all';

data_eeg = ft_resampledata(cfg_resample,data_eeg);

% change data precision to single
for t = 1:length(data_eeg.trial)
    data_eeg.trial{t} = single(data_eeg.trial{t});
end; clear t

%% save outputs

save(fullfile(pn.eeg_ft, [IDs{id}, '_task-xxxx_eeg_raw.mat']),'data_eeg');
% save config if it does not exist yet (otherwise we risk overwriting manual segs)
if ~exist(fullfile(pn.history, [IDs{id}, '_task-xxxx_config.mat']),'file')
    save(fullfile(pn.history, [IDs{id}, '_task-xxxx_config.mat']),'config');
end
% clear variables
clear cfg_* config data_eeg

end