function [dat] = read_brainstorm_data(filename, hdr, begsample, endsample, chanindx)

% READ_BRAINSTORM_DATA reads .EEG files that have been generated by
% the Nihon Kohden system. The function constitutes a wrapper around
% BrainStorm3 functionalities
%
% Use as
%   [dat] = read_brainstorm_data(filename, hdr, begsample, endsample, chanindx)
%
% The function has not been tested on NK1200 files with multiple epochs
%
% See also READ_BRAINSTORM_HEADER, READ_BRAINSTORM_EVENT

% Copyright (C) 2018, Arjen Stolk & Sandon Griffin
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$


% default is to select all channels
if nargin<5
  chanrange{1} = [1 hdr.nChans]; % all channels
else
  if isempty(find(diff(chanindx)~=1)) % if chanindx is consecutively numbered
    chanrange{1} = [chanindx(1) chanindx(end)];
  else % otherwise loop around the chanindx entries
    chanrange = cell(numel(chanindx), 1);
    for c = 1:numel(chanindx)
      chanrange{c} = [chanindx(c) chanindx(c)];
    end
  end
end

% call BrainStorm's in_fopen_nk
[sFile] = in_fopen_nk(filename);

% check number of epochs/trials
if hdr.nTrials>1
  ft_warning('support for multiple epochs/trials has not been tested')
end

% call BrainStorm's in_fread_nk
num = [];
dat = [];
for e = 1:hdr.nTrials
  for c = 1:numel(chanrange)
    sfid = fopen(filename);
    tmp = in_fread_nk(sFile, sfid, e, [begsample-1 endsample-1], chanrange{c}); % NK1200 samples starts at 0
    num = [num; tmp]; clear tmp % stack channels
    fclose(sfid);
  end
  dat = [dat num]; clear num % append epochs/trials
end
