function [bem_headmodel] = CreateBEMModel(cfg) %%folder,file,segmented)
%CreateBEMHeadmodel Segments MRI-Data and builds an BEM-Headmodel from it.
%Based on http://fieldtrip.fcdonders.nl/example/create_bem_headmodel_for_eeg

if(isstruct(cfg) == false)
    error('config must provide a struct');
end

mri = cfg.mri;

% construct the triangulated surfaces and compute the BEM model


cfg                = [];

numcompartments = max(max(max(mri.seg)));

disp(['Generiere BEM Modell mit ', num2str(numcompartments), ' compartments']);

cfg.tissue         = 1:numcompartments; % value of each tissue type in the segmentation
%cfg.numvertices    = (1:numcompartments)*1000;
cfg.numvertices = ones(1,numcompartments)*500;
cfg.conductivity   = ones(1,numcompartments)*1/3;
cfg.conductivity(2) = cfg.conductivity(2)/80;


if numcompartments==5
    cfg.conductivity(2)= 1/240;
    cfg.source         = 4;
end




cfg.isolatedsource = true;
cfg.method         = 'openmeeg';
%PC: Fix prepare_bemmodel was complaining about cfg not containing
%sourceunits field
cfg.sourceunits     = 'mm';
cfg.mriunits        = 'mm';
%cfg.dipoli = '/home/paulc/Matlab/fieldtrip-20091126/dipoli'; % where to find the executable
vol = ft_prepare_bemmodel(cfg, mri);

% make figures of the surfaces, note that the brain and skull surface
% should be slightly smoother an additional convolution and threshold of
% their respective segmentations probably would achieve that
% figure; triplot(vol.bnd(1).pnt, vol.bnd(1).tri, [], 'faces_skin'); rotate3d
% figure; triplot(vol.bnd(2).pnt, vol.bnd(2).tri, [], 'faces_skin'); rotate3d
% figure; triplot(vol.bnd(3).pnt, vol.bnd(3).tri, [], 'faces_skin'); rotate3d

% write the BEM model to a matlab file, it can be later specified in
% sourceanalysis or dipolefitting as cfg.hdmfile='vol.mat'
% save [folder,'vol.mat'] vol mri

bem_headmodel.vol = vol;
bem_headmodel.mri = mri;
%bem_headmodel.skin = skin;
%bem_headmodel.skull = skull;
%bem_headmodel.brain = brain;

end



----------------------------------
The aim of this list is to facilitate the discussion between users of the FieldTrip  toolbox, to share experiences and to discuss new ideas for MEG and EEG analysis. See also http://listserv.surfnet.nl/archives/fieldtrip.html and http://www.ru.nl/neuroimaging/fieldtrip.
