function data=bdat_read(fn,ncolumns)
%Reads a .bdat file.  You need to specify the number of columns.
%USAGE: data=bdat_read('lefa7_091020-194000.bdat',5)
%USAGE: data=bdat_read(fn,ncolumns);
% file_name -> name of file to load, may include directory info.
% ncolumns-> Number of columns in the given bdat file.
%  ncolumns = 5 for files with good GPS
%  (time, GPS, I, M, S)
%  ncolumns = 4 for files without good GPS (the time is omitted)
%
% Author: This is Victor Alvidrez's from_bdatfile.m v1.3.
% Sonnenfeld merely removed the unneeded "jump" capability.
% Also, ncolumns is now an argument instead of hard-coded.
%
% About: This function will read *.bdat binary data
% files produced by process_bin_file. 
% The function will return a matlab matrix of 
% size = (cnt/ncolumns, ncolumns) , where cnt is the number
% of samples read from the file.
%
% $Id:$

fid=fopen(fn,'rb');
% fo -> open file descripter
% inf -> read the entire file
% 'float64' -> precision the data file was written with.
% 0 -> specifies number of bytes to skip after each sample, in this case zero.
% 'ieee-le' -> the format used to write binary data , in this case MSB first, LSB last
% [val,cnt] -> val is a 1-D array containing all 'float64' values read from file, 
% 		cnt should be the number of elements in val.

[val,cnt]=fread(fid,inf,'float64',0,'ieee-le');
% val is a 1-D vertical 
% reshape(val,ncolumns,cnt/ncolumns) returns an array of the form
%  [ col1 
%    col2 
%    ...
%    coln ]
% so take the transpose.
size(val);
data=reshape(val,ncolumns,cnt/ncolumns)';
fclose(fid);
return 