%function readlog(logname)
%
% PURPOSE: Read binary log files generated by the Auv QNX code directly into
%          Matlab. 
% CHANGE LOG:  1) Brian Schlining Jan 2004, log2nc.m
%              2) Converted to readlog.m, 20 May 05, Rob McEwen
%
% Inputs: logname = The log file to be read; excluding the .log extension.
% $Id: readlog.m,v 1.1 2005/05/23 21:35:57 rob Exp $
%
% Open the log file, get the device name from the header
fid = fopen(logname, 'r', 'l');
s = fgetl(fid); 
mnemonic = stringtokenizer(s, 3);
%
% Parse the header of the log file:
clear data;
i = 0;
while(~feof(fid))
  s = fgetl(fid);  
  i = i + 1;
  if (strcmp(stringtokenizer(s, 2), 'begin'))
    break    
  end
  
  % Parse the variable info
  data(i).type = stringtokenizer(s, 2);
  data(i).shortName = stringtokenizer(s, 3);
  data(i).format = stringtokenizer(s, 4);
  data(i).longName = stringtokenizer(s, 2, ',');

  %Put the variable name on the Matlab stack:
  eval([ char(data(i).shortName)  ' = '  num2str(i) ';']);
  
  switch data(i).shortName
    case 'time'
      data(i).units = 'seconds since 1970-01-01 00:00:00Z';
    otherwise         
      data(i).units = stringtokenizer(s, 3, ',');
  end
  
  % Map the dataformats correctly   
  switch lower(data(i).type)
    case {'float'}
      data(i).type = 'float32'; 
      data(i).size = 4;
    case {'integer'}
      data(i).type = 'int32';
      data(i).size = 4;
    case {'short'}
      data(i).type = 'int16';
      data(i).size = 2;
    otherwise
      data(i).type = 'double'; 
      data(i).size = 8;
  end
  
end

% Pre allocate memory
byteStart = ftell(fid);
fseek(fid, 0, 'eof');
byteEnd = ftell(fid);
fseek(fid, byteStart, 'bof');
nBytes = byteEnd - byteStart;
recordLength = 0;
for i = 1:length(data)          %length(data) is the number of variables
  recordLength = recordLength + data(i).size;
end
nCol = i;
nRecords = floor(nBytes/recordLength);
eval([ char(mnemonic) '(1:nRecords,1:nCol) = ones(nRecords,nCol) * NaN;']);

% Read the data from the log
for i = 1:length(data)
  byteStart = ftell(fid);
  eval([ char(mnemonic) '(1:nRecords,i) = fread(fid, nRecords, data(i).type, recordLength - data(i).size);']);
  fseek(fid, byteStart + data(i).size, 'bof');
end
fclose(fid);
