function [neighbours]=neuromag_prepare_neighbours(inp, data)

% This function extracts the neighbours based on the type of the original channel
% (magnotometer, vertical or horizontal channel) depending on the distance you
% allow the neighbours to be. It needs as input:
% inp.neighbourdist 
% !!!NOTE!!!: it doesn't work with grad definition yet only with layoutfile.
% Addapted from fieldtrip by Hanneke van Dijk.

cfg=[];
%cfg.layout = 'neuromag306all.lay';
cfg.grad = grad;
sens = ft_fetch_sens(cfg);% This function only exists in the lates version of Fieldtrip
nsensors = length(sens.label);

% compute the distance between all sensors
dist = zeros(nsensors,nsensors);
for i=1:nsensors
  dist(i,:) = sqrt(sum((sens.chanpos(1:nsensors,:) - repmat(sens.chanpos(i,:), nsensors, 1)).^2,2))';
end;

% find the neighbouring electrodes based on distance
% later we have to restrict the neighbouring electrodes to those actually selected in the dataset
channeighbstructmat = (dist<inp.neighbourdist);

% electrode istelf is not a neighbour
channeighbstructmat = (channeighbstructmat .* ~eye(nsensors));

% construct a structured cell array with all neighbours (horizontal and
% vertical taken into account
neighbours=struct;
buren = [];
for i=1:306;%nsensors
  neighbours(i).label       = sens.label{i};
  nextdoor = sens.label(find(channeighbstructmat(i,:)));
  k = str2num(char(neighbours(i).label(7)));
  if k == 1; %find(ismember(neighbours(i).label, '1' )) == 7;
      neighbours(i).neighblabel = ft_channelselection('***1', nextdoor);
  elseif k ==2;%find(ismember(neighbours(i).label, '2' )) == 7;
      neighbours(i).neighblabel = ft_channelselection('***2', nextdoor);
  elseif k ==3;%find(ismember(neighbours(i).label, '3' )) == 7;
      neighbours(i).neighblabel = ft_channelselection('***3', nextdoor);
  end
end
