function [ aBitStream ] = BPSKDemod( aDigitalSignal, A, f, fs, rate)
% A simple BPSK correlator demodulator
% Inputs
%   aDigitalSignal = modulated digital signal
%   A = max amplitude of carrier (in Volts)
%   f = carrier frequency (in Hz)
%   fs = sampling rate (in sps)
%   rate = data rate (in bps)
% Output
%   aBitStream = an array of bits
% determine the number of samples per bit
spb = fs/rate; % samples/bit
% determine sample period
ts = 1/fs;
% determine the number of bits
n = length(aDigitalSignal) / spb;
% initialize the output
aBitStream = [];
% generate corresponding time instants
t = (0:spb-1) * ts;
% orthonormal basis
phi = sqrt(2 * rate)*cos(2*pi*f*t);
% determine weighting factor for each symbol
s1 = A * sqrt(1/2 * 1/rate); % for bit zero
s2 = -A * sqrt(1/2 * 1/rate); % for bit one
% demodulate the BPSK signal symbol-by-symbol
for i=0:n-1
    % determine index of symbol's first sample
    j = i * spb;
    % determine values of weighting coefficients
    r = sum( aDigitalSignal(j+1:j+spb) .* phi ) * ts;
    % determine binary value
    bit = abs(r - s1) > abs(r - s2);
    % append value to ouput buffer
    aBitStream = [ aBitStream bit ];       
end
end
