function [header, eegData, eventData, outputLog, outputLog2, outputLog3] = readRaw(fileName, eventText);
%READRAW - Reads an EGI epoch-marked simple binary format (epoch-marked raw format) file.
% function [header, eegData, eventData, outputLog, outputLog2, outputLog3] = readRaw(fileName, eventText);
% Reads an EGI epoch-marked simple binary format (epoch-marked raw format) file.
%
% Epoch-marked raw format: Unsegmented simple binary format (raw format,
%                          version # 2, 4 or 6) with event codes <epoc> and <tim0>.
%
% The single sample records (SSR) are extracted to form the eegData matrix, where
% each column of the matrix (array) is one SSR.
% The  corresponding event records, one per SSR, are extracted to form the
% eventData matrix, where each column of the matrix (array) is one event record.
%
% Input Arguments: fileName - Name of the EGI epoch-marked simple binary format
%                             file, without the .raw extension.
%                             It must be a MATLAB string.
%
% Output Arguments: header - MATLAB structure array containing the header info.
% 
%                   eegData - m1 by n array containing the continuous EEG data.
%                             m1 = # of channels, n = # of time samples.
%
%                   eventData - m2 by n array containing the corresponding event info.
%                               m2 = # of event types, n = # of time samples
%
%                   outputLog - Character array of header information.
%
%                   outputLog2 - Reports back on the # of data elements
%                                succesfully read.

%<autobegin> ---------------------- 12-Oct-2004 12:02:46 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Utility - General
%
% At Check-in: $Author: Mosher $  $Revision: 2 $  $Date: 10/12/04 10:24a $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 12-Oct-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> ------------------------ 12-Oct-2004 12:02:46 -----------------------



% ----------------------------- Script History ---------------------------------
% JCM 11-Oct-2004 Commenting header
% ----------------------------- Script History ---------------------------------

%fid = fopen([fileName '.raw'],'r','b');
fid = fopen([fileName],'r','b'); %Dimitrios change; file already has extension

if (fid == -1)  % File not found.
    
    errorMsg = sprintf('\n!!! File %s.raw Not Found !!!\n', fileName);
    error(errorMsg);
    
end

outputLog = ['inputFile = <' fileName '.raw>'];  % Seed the outputLog.

% ----------------- Read the header info into the structure variable 'header'. -----------------

header.versionNumber = fread(fid, 1, 'integer*4');
outputLog = strvcat(outputLog, ['versionNumber = ' int2str(header.versionNumber)]);

switch header.versionNumber
   case {3, 5, 7}
       errorMsg = sprintf...
           ('\n!!! The File %s.raw Must Contain Unsegmented EEG Data !!!\n', fileName);
       error(errorMsg);
end

header.recordingTimeYear = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['recordingTimeYear = ' int2str(header.recordingTimeYear)]);

header.recordingTimeMonth = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['recordingTimeMonth = ' int2str(header.recordingTimeMonth)]);

header.recordingTimeDay = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['recordingTimeDay = ' int2str(header.recordingTimeDay)]);

header.recordingTimeHour = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['recordingTimeHour = ' int2str(header.recordingTimeHour)]);

header.recordingTimeMinute = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['recordingTimeMinute = ' int2str(header.recordingTimeMinute)]);

header.recordingTimeSecond = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['recordingTimeSecond = ' int2str(header.recordingTimeSecond)]);

header.recordingTimeMillisec = fread(fid, 1, 'integer*4');
outputLog = strvcat(outputLog, ['recordingTimeMillisec = ' int2str(header.recordingTimeMillisec)]);

header.samplingRate = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['samplingRate = ' int2str(header.samplingRate)]);

header.numChans = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['numChans = ' int2str(header.numChans)]);

header.boardGain = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['boardGain = ' int2str(header.boardGain)]);

header.numConvBits = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['numConvBits = ' int2str(header.numConvBits)]);

header.ampRange = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['ampRange = ' int2str(header.ampRange)]);

header.numSamples = fread(fid, 1, 'integer*4');
outputLog = strvcat(outputLog, ['numSamples = ' int2str(header.numSamples)]);

header.numEvents = fread(fid, 1, 'integer*2');
outputLog = strvcat(outputLog, ['numEvents = ' int2str(header.numEvents)]);

if (header.numEvents ~= 0)  % File contains event info.
    
    for i = 1:header.numEvents
        
        header.eventCodes(i) = {fread(fid, [1 4], 'uchar')};
        ithEventCode = char(header.eventCodes{i});
        outputLog = strvcat(outputLog, ['eventCode # ' int2str(i) ' = ' ithEventCode]);
        
    end
    
else  % File does not contain event info.
    
    usrMsg = sprintf...
       ('\nThe file %s.raw does not contain event information.', fileName);
    disp(usrMsg); outputLog = strvcat(outputLog, usrMsg);
    
end

% ----------------------------- Finished reading the header. -----------------------------------

switch header.versionNumber
   case 2
       precision = 'integer*2';  % Integer
   case 4
       precision = 'real*4';  % Single Precision Real
   case 6
       precision = 'real*8';  % Double Precision Real
end

% -------- Read SSRs into array eegData and corresponding events into array eventData. --------

eegDataCount = 0; eventDataCount = 0;
eegData = zeros(header.numChans, header.numSamples);

if (header.numEvents ~= 0)  % File contains event info.
    
    eventData = zeros(header.numEvents, header.numSamples);
    
    for j = 1:header.numSamples
        
        [eegData(:,j), eegTempCount] = fread(fid, header.numChans, precision);
        [eventData(:,j), eventTempCount] = fread(fid, header.numEvents, precision);
        eegDataCount = eegDataCount + eegTempCount;
        eventDataCount = eventDataCount + eventTempCount;
        
    end
    
else  % File does not contain event info.
    
    eventData = [];
    
    [eegData, eegDataCount] = fread(fid, [header.numChans, header.numSamples], precision);
    
end

% ---------------------- Finished reading SSRs and event data. ------------------------

% Verify that all the data was read.

if (header.numEvents ~= 0)  % File contains event info.
    
    if ((eegDataCount ~= header.numChans * header.numSamples) | ...
          (eventDataCount ~= header.numEvents * header.numSamples))
      
       errorMsg = sprintf...
          ('\n!!! The Data Read Failed.  Could Not Fill EEG & Event Data Arrays !!!\n');
       error(errorMsg);
       
    end
    
else  % File does not contain event info.
    
    if (eegDataCount ~= header.numChans * header.numSamples)
        errorMsg = sprintf...
            ('\n!!! The Data Read Failed.  Could Not Fill EEG Data Array !!!\n');
    end
    
end

outputLog2 = ['# of eeg data values read = ' int2str(eegDataCount)];  % Seed outputLog2.
outputLog2 = strvcat...
    (outputLog2,['Array eegData: ' int2str(header.numChans) ' x ' int2str(header.numSamples)]);

if (header.numEvents ~= 0)  % File contains event info.
    
    outputLog2 = strvcat(outputLog2,['# of event markers read = ' int2str(eventDataCount)]);
    outputLog2 = strvcat...
        (outputLog2,['Array eventData: ' int2str(header.numEvents) ' x ' int2str(header.numSamples)]);
    
end

fclose(fid);

if (header.numEvents ~= 0)
    if nargin == 1
        eventText = 'N';
    end
    %eventText = input('\nOutput events to NetStation compatible text file (Y/N)? ', 's');
    if (eventText == 'Y') | (eventText == 'y')
        [outputLog3] = writeEvents(fileName, header, eventData);
    else
        outputLog3 = [];
    end
else
    outputLog3 = [];
end

% That's All Folks.
