function [hdr] = read_brainstorm_header(filename)

% READ_BRAINSTORM_HEADER reads the header information from .EEG files 
% that have been generated by the Nihon Kohden system. The function 
% constitutes a wrapper around BrainStorm3 functionalities 
%
% Use as
%   [hdr] = read_brainstorm_header(filename)
%
% See also READ_BRAINSTORM_DATA, 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$


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

% create the header file by pulling values from the output
hdr.orig        = sFile.header;
hdr.nChans      = sFile.header.num_channels;
hdr.Fs          = sFile.header.sample_rate;
if isfield(sFile.epochs, 'samples')     
  hdr.nSamples    = sFile.epochs.samples(end) - sFile.epochs.samples(1) + 1;
elseif isfield(sFile.epochs, 'times') % accommodates a change to in_fopen_nk in 2021
  hdr.nSamples    = (sFile.epochs.times(end) - sFile.epochs.times(1)) * hdr.Fs + 1;
end
hdr.nSamplesPre = 0;
hdr.nTrials     = length(sFile.epochs);
hdr.label       = cell(hdr.nChans, 1);
for n = 1:hdr.nChans
  hdr.label{n} = ChannelMat.Channel(n).Name;
end
hdr.chanunit = cell(hdr.nChans, 1);
for n = 1:hdr.nChans
  hdr.chanunit{n} = 'unknown';
end
hdr.chantype = cell(hdr.nChans, 1);
for n = 1:hdr.nChans
  hdr.chantype{n} = 'unknown';
end
