function [data]=eeg2bs(fnamein,fnameout,type,Channel)
%EEG2BS - (fnamein,fnameout,type,channel)
% function [data]=eeg2bs(fnamein,fnameout,type,Channel)
% this function converts EEG data files into BrainStorm readable format
% fnamein = input file name
% fnameout = output filename for BrainStorm format. If fnameout is [],
% nothing is saved.
% type = input data format 
%      = 'avr' BESA ASCII format
%      = 'avg' NeuroScan binary format
%      = 'raw' EGI binary format
% data = returns brainstorm data structure
%       data.ChannelFlag good or bad channels. default = 1
%       data.Comment     Comment. default = 'EEG data'
%       data.Device      Type of device. default = 'EEG amplifier'
%       data.F           Spatiotemporal data. default = 0
%       data.NoiseCov    the noise covariance. default =[]
%       data.Project     Project ?. default =[]
%       data.Projector   Subspace projector. default =[]
%       data.SourceCov   Source covariance. default = []
%       data.Time        time in [s]. default =0;
% channel = the BrainStormChannel structure

%<autobegin> ---------------------- 02-Nov-2004 16:14:17 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Data Processing
%
% Alphabetical list of external functions (non-Matlab):
%   toolbox\eeg_load_scan3avg.m
%   toolbox\read_besa.m
%   toolbox\readraw.m
%   toolbox\save_fieldnames.m
%
% At Check-in: $Author: Mosher $  $Revision: 7 $  $Date: 11/02/04 2:35p $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 02-Nov-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 02-Nov-2004 16:14:17 -----------------------


% ----------------------------- Script History ---------------------------------
% (c) 2004 Felix Darvas, Ph.D. , SIPI University of Southern California
% JCM 11-0ct-2004 Commenting header
% ----------------------------- Script History ---------------------------------

% setting defaults

data.ChannelFlag=1;
data.Comment='EEG data';
data.Device='EEG amplifier';
data.F=0;
data.NoiseCov=[];
data.Project=[];
data.Projector=[];
data.SourceCov=[];
data.Time=0;
if(strcmp(type,'avr')) % import ASCII data in BESA format
    [F,t,npts,tsb,di,sb,sc]=read_besa(fnamein);
    data.F=F'/1e6; % avr files are in uV scale
    data.Time=t/1000; % no ms in BS!
    data.ChannelFlag=ones(1,size(F,2));% all channels are good!
    % done! that was easy!
end
if(strcmp(type,'avg')) % import binary data in NeuroScan format
    F=eeg_load_scan3avg(fnamein); % uses eeg_load_scan3avg from eeg toolbox from Darren Weber
    data.F=F.signal;
    data.F=F.signal/1e6;% avg files are in uV scale
    dt=(F.xmax-F.xmin)/F.pnts;
    t=F.xmin+((1:F.pnts)-1)*dt;
    data.Time=t/1000; %no ms in BS!
    data.ChannelFlag=ones(1,size(F.signal,1)); % all channels are good!
end
if(strcmp(type,'raw'))  % import binary data in EGI format
    [header, eegData, eventData, outputLog, outputLog2, outputLog3] = readRaw(fnamein);
    t=0:(1/header.samplingRate):(header.numSamples-1)/header.samplingRate;
    ix = 0; %CD!!!
    for i=1:header.numEvents
        if(strcmp('tim0',char(header.eventCodes{i})))
            ix=i;
            break
        end
    end
    ix0 = []; %CD!!!
    if ix ~= 0 %CD!!!
        ix0=find(eventData(ix,:)>0);
    end %CD!!!
    if(~isempty(ix0))
        ix0=ix0(1);
    else
        ix0=1;
    end
    t0=t(ix0);
    t=t-t0;
    data.F=eegData/1e6;
    data.Time=t;
    data.ChannelFlag=ones(size(data.F,1),1);
end
% more formats to follow ...
% squeeze in the reference channel with zeroes
ixref=1;
lc=length(Channel);
ld=size(data.F,1);
ix=-1;
for i=1:lc
    if(strcmp(Channel(i).Type,'EEG REF'))
     ix=i;    
    end
end

if(lc>ld) % there is no reference channel in the data
    if(ix==lc) % fill end of data with zeros
        data.F=[data.F;zeros(1,size(data.F,2))]; % adding reference channel with all zeroes.
    end
    if(ix==1) % fill beginning of data with zeros
        data.F=[zeros(1,size(data.F,2));data.F]; % adding reference channel with all zeroes.
    end
    if(ix>1 & ix<lc) % fill in between
        data.F=[data.F(1:ix-1,:);zeros(1,size(data.F,2));data.F(ix:end,:)]; % adding reference channel with all zeroes.
    end
    if(ix<0) % no reference found, probably we have an average reference
          data.F=[data.F;mean(data.F,1)]; % fill last channel with average 
    end
    data.ChannelFlag=[data.ChannelFlag 1];
else
    if(ix>0) % CD!!!
        if(lc==ld) % there was a reference channel in the data
            data.F=data.F-ones(lc,1)*data.F(ix,:); % subtract reference channel data from all other channels
        end
    end % CD!!!
end

% finished conversion
if(~isempty(fnameout))
save_fieldnames(data,fnameout); % saving data in braistorm format
end
