% ReadBinaryFileTX
% Tyler_Smelt@hmc.edu
% February 28, 2012
% Read data from files generated by the MuddLogg16 data logger.
%
% Files consist of unsigned 16-bit values in big-endian format,
% in the order 2, 1, 4, 3 ... N, N-1 where N is the # of channels (even).
% The channels are actually sampled in order (1, 2, 3, 4 ... N-1, N), and
% this function outputs them in the correct sampled order.
%
% Inputs:
%   fileName: a string containing the file name to read (.DAT)
%   N: the number of channels set in config.txt (default = 16)
%   Fs: the overall sampling rate set in config.txt (default = 64000)
%   scale: a boolean choosing whether or not to scale the data values to
%           the A/D converter reference voltage (3.3V)
% Outputs:
%   t: a matrix containing a time vector for each channel, 1 to N
%       (this includes the small delay between each sample in the sequence)
%   x: a matrix containing a data vector for each channel, 1 to N

function [t, x] = ReadBinaryFileTX(fileName, N, Fs, scale)
    if (mod(N,2) == 0)
        % Read the data
        fileID = fopen(fileName, 'r', 'b');
        x = fread(fileID, [N, inf], 'uint16', 0, 'b')';
        fclose(fileID);
        
        % Create time matrix
        samples = numel(x);
        t = reshape(0:samples-1, N, [])'/Fs;

        % Swap adjacent columns in data matrix
        for n=1:2:N
            ch1 = x(:,n);
            ch2 = x(:,n+1);
            x(:,n) = ch2;
            x(:,n+1) = ch1;
        end

        % Scale to voltages
        if (scale)
            x = x*3.3/(2^16);
        end
    else
        error('N must be an even number')
    end
end
