function [x, t] = ReadBinaryFileXT(fileName, N, Fs, scale)
%ReadBinaryFileXT    Read data from files generated by the MuddLogg16 data logger.
%
%   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:
%       x: a matrix containing a column data vector for each channel, 1 to N
%       t: a matrix containing a column time vector for each channel, 1 to N
%           (this includes the small delay between each sample in the sequence)
%
%   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.
%
%   Tyler_Smelt@hmc.edu
%   February 28, 2012

    % Check input
    if (mod(N,2) ~= 0)
        error('N must be an even number')
    else
        % 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
    end
end
