%******************************************************************************
% Copyright 1998 MBARI                                                      
%******************************************************************************
% Summary  : Reads binary logged MP data
% Filename : mpRead
% Author   : Michael B. Matthews                                                
% Project  : New ROV                                                        
% Version  : 1.0                                                          
% Created  : 11.8.98                                                     
% Modified :                                                              
% Archived :                                                              
% Notes    : Reads in m buffers
%          : x - (
%******************************************************************************

function [x,p,nBuff,s] = mpRead(filename,m)

if nargin < 2, m = -1; end

MMAX = 50;

disp(['opening file ' filename]);
fid = feval('fopen', filename, 'r');
if fid == -1, disp(['error opening ' filename]); end

time = fread(fid,1,'float64');	% read in time stamp
nBuff = fread(fid,1,'int16');	% read in number of buffers
n = fread(fid,1,'int16');	% read in buffer size

disp(['time - ' num2str(time)]);
disp(['number of buffers - ' int2str(nBuff)]);
disp(['size of buffers   - ' int2str(n)]);
 
if nBuff == 2
nBuff = 13;
s = strvcat('time', 'compass',	...
	    'ax', 'ay', 'az',	...
	    'rx', 'ry', 'rz',	...
	    'gyro');
p = 0;
y = zeros(n,9);
x = zeros(n,9);
[x,k] = fread(fid,[n,9],'float32');
if k == (n*9), p = p + 1; end
if m == -1
  while p < MMAX
    [y,k] = fread(fid,[n,9],'float32');
    if k ~= (n*9), break; end
    x = [x;y];
    p = p + 1;
  end
else
  for i=2:m
    [y,k] = fread(fid,[n,9],'float32');
    if k ~= (n*9), break; end
    x = [x;y];
    p = p + 1;
  end
end

else

% read in signal names
s = [];
for i=1:nBuff
  r = [];
  while 1
    p = fread(fid,1,'char'); 
    if p == 0, break; end
    r = [r setstr(p)];
  end
  s = strvcat(s,r);
end
disp('Signals :');
disp(s);

p = 0;
y = zeros(n,nBuff);
x = zeros(n,nBuff);
[x,k] = fread(fid,[n,nBuff],'float32');
if k == (n*nBuff), p = p + 1; end
if m == -1
  while p < MMAX
    [y,k] = fread(fid,[n,nBuff],'float32');
    if k ~= (n*nBuff), break; end
    x = [x;y];
    p = p + 1;
  end
else
  for i=2:m
    [y,k] = fread(fid,[n,nBuff],'float32');
    if k ~= (n*nBuff), break; end
    x = [x;y];
    p = p + 1;
  end
end

end

fclose(fid);
