function [yVec, tVec, tStart] = loadNIdata(datadir,filename,Tp,Fsr,tSeek,precision)
% Loads a segment of complex IQ samples from a binary file recorded using
% a National Instruments RFSA device. The binary file contains interleaved
% 16-bit signed integers representing I and Q samples.
% INPUTS
%
% datadir ---- Directory where binary file is located
%
% filename --- Name of binary file (without .bin extension)
%
% Tp --------- Interval of data to load (sec)
%
% Fsr -------- Complex sampling rate (Hz)
%
% tSeek ------ Seek time into data (sec)
%
% precision -- To control memory usage, optional input to change output
%              from double (default) to single.
% 
% OUTPUTS
%
% yVec ------- Ny-by-1 complex vector of IQ samples
%
% tVec ------- Ny-by-1 vector of time points corresponding to yVec
% 
% tStart ----- Actual seek time (sec), adjusted to match sample boundaries.
%              Useful if you need time in file after nearest-sample
%              adjustment, as in example.
%
% EXAMPLE USAGE
% -------------
%   datadir  = 'data';
%   filename = 'capture001';
%   Tp       = 0.01;       % Load 10 ms of data
%   Fsr      = 20e6;       % 20 MHz sample rate
%   tSeek    = 0.5;        % Seek 0.5 s into file
%   [yVec, tVec, tStart] = loadNIdata(datadir, filename, Tp, Fsr, tSeek);
%   plot(tVec + tStart, real(yVec));
%   xlabel('Time (s)');
%   ylabel('Amplitude');
%   title('Real Part of IQ Signal');
%
%+------------------------------------------------------------------------------+
% References:
%
%
% Author:  Todd Humphreys
%+==============================================================================+%

if nargin<6
    precision = 'double';
end
assert(any(strcmpi(precision, {'single','double'})))

fid = fopen([datadir '/' filename '.bin'], 'r', 'n');
if fid == -1
    error('loadNIdata:FileOpenFailed', 'Could not open file %s', filename);
end

Ns = floor(Tp*Fsr);
% 4 bytes per complex sample
seekOffset = floor(tSeek*Fsr)*4;
tStart = seekOffset/4/Fsr;
status = fseek(fid,seekOffset,-1);
if status == -1
    fclose(fid);
    error('loadNIdata:SeekFailed', 'tSeek of %.3f s is beyond file limit', tSeek);
end

yVec = fread(fid, [2,Ns], 'int16')';

if size(yVec, 1) < Ns
    error('loadNIdata:InsufficientData', 'Requested %.3f s of data, but file had too few samples', Tp);
end

yVec = complex(yVec(:,1),yVec(:,2));
Ny = length(yVec);
tVec = (0:Ny-1)'/Fsr;

if strcmpi(precision, 'single')
    yVec = single(Ny);
end

fclose(fid);