close all
clear


%% Select 'role' of this script.
% 'Both' transmits and records/receives.
% TX and RX transmit only and recieve only, resp.
BOTH_MODE = 0;
TX_MODE   = 1;
RX_MODE   = 2;
MODE = TX_MODE;


rx_fs = 48000;

%% Input parameters

Rb = rx_fs/6%/12.5;   % bit rate [bit/sec]
fs = rx_fs; % Sampling frequency [Sample/s]
Ts = 1/fs; % Sample time [s/Sample]
fc = 21000;  % Carrier frequency [Hz]
span = 6;   % Pulse-width in symbol times.


decimation_factor = rx_fs/fs;

rolloff = 0.4; % Roll-off factor (ie. alpha) for Raised Cosine pulse.

%% Transmitter
%% Constellation (normalized to unit energy E=d^2)
% Implemented constellations:
% 'BPSK'
% '4-QAM'
% '8-PSK'
% '32-PSK'
% '16-QAM'
% '256-QAM'
% '1024-QAM'
constellation = generateConstellation('4-QAM');

if length(constellation) > 2 % Voronoi need at least 3 constellation points.
    voronoi(real(constellation), imag(constellation))
    title('Constellation plot')
    xlabel("Phase"); ylabel("Quadrature");
end



% Preamble (including initial delay where nothing is tx'd)
delay_time = randi([1,200], 1);       % Generate a random delay between 1 and 20 samples long.
delay = zeros(1, delay_time);


B2 = [1 -1]; %Barker-2
B3 = [1 1 -1]; %Barker-3
B4 = [1 1 -1 1]; %Barker-4
B5 = [1 1 1 -1 1]; %Barker-5%
B7 = [1 1 1 -1 -1 1 -1]; %Barker-7
B11 = [1 1 1 -1 -1 -1 1 -1 -1 1 -1]; %Barker 11
B13 = [1 1 1 1 1 -1 -1 1 1 -1 1 -1 1]; % Barker-13
preamble = kron(B7,B7);   % Select preamble here. if 1-dimensional barker, set first argument to 1.


%preamble_symbs = preamble.*(1+1i)./sqrt(2); % Map preamble to symbols, so that they are 180deg apart! MUST BE MODIFIED IF USING DIFFERENT CONSTELLATION.
preamble_symbs = preamble; % Do NOT need to map to valid symbols


%% Data source


b = genAllTenBit();
%b = genAllASCII();
b=[b b b b]
N = length(b);    % Number of bits to transmit
% N = 432
%b = randsrc(1,N,[0 1]); % Random message bits.

string = 'To be, or not to be: that is the question: Whether  "tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, And by opposing end them? To die: to sleep; No more; and by a sleep to say we end The heart-ache and the thousand natural shocks That flesh is heir to,  "tis a consummation Devoutly to be wish "d. To die, to sleep; To sleep: perchance to dream: ay, there "s the rub; For in that sleep of death what dreams may come When we have shuffled off this mortal coil, Must give us pause: there "s the respect That makes calamity of so long life; For who would bear the whips and scorns of time, The oppressor "s wrong, the proud man "s contumely, The pangs of despised love, the law "s delay, The insolence of office and the spurns That patient merit of the unworthy takes, When he himself might his quietus make With a bare bodkin? who would fardels bear, To grunt and sweat under a weary life, But that the dread of something after death, The undiscover "d country from whose bourn No traveller returns, puzzles the will And makes us rather bear those ills we have Than fly to others that we know not of? Thus conscience does make cowards of us all; And thus the native hue of resolution Is sicklied o "er with the pale cast of thought, And enterprises of great pith and moment With this regard their currents turn awry, And lose the name of action.--Soft you now! The fair Ophelia! Nymph, in thy orisons Be all my sins remember "d!';
b = string2bitStream(string);
N = length(b);
if length(b) > N
    disp('Source too long! Truncating...')
    b = b(1:N);
end
b = [b zeros(1, N-length(b))]; % Pad string with zeros to fill length 432 packet.
disp(['Sent message: ' string])

%% Bits to Messages
M = length(constellation);      % M unique messages/symbols.
bpsymb = log2(M);       % Bits per symbol
Rsymb = Rb/bpsymb;
Tsymb = 1/Rsymb;
sps   = fs/Rsymb; % Samples per symbol. [Sample/s / Symbol/s = Sample/Symbol] 
m = buffer(b, bpsymb)'; % Group information bits into bits per symbol
m_idx = bi2de(m, 'left-msb')'+1; % Bits to symbol index, msb: the Most Significant Bit

% Message to symbol
message_symbs = constellation(m_idx);    % Map messages to constellation symbols using indices
%symbs = [delay preamble_symbs ]; % Prepend variable delay and preamble to message.
symbs = [preamble_symbs message_symbs];

    % Plot phase-corrected samples.
    figure
    hold on
    plot((symbs), 'ob'); 
    if length(constellation)>2
        voronoi(real(constellation), imag(constellation))
    end
    %plot(real(constellation), imag(constellation), 'or')
    grid on; axis square;
    title('Sent symbols')
    hold off


% Generate basic pulse
[pulse t] = rtrcpuls(rolloff, Tsymb, fs, span); % Generate basis pulse.
figure
plot(t, pulse); grid on; title('Basic pulse');

% Pulse-modulation -> create baseband signal
sps = fix(sps); % Convert explicitly to integer !!UGLY HACK!!
x_upsample = upsample(symbs, sps); % Upsample to fs.
s = conv(pulse, x_upsample); % Pulse shaping the symbol-train by convolving with basis pulse.
t_s = (0:length(s)-1).*Ts; % Signal time-axis ie. x[n]*n*Ts.

% Normalize baseband amplitude to sqrt(2) (because pulse-convolution attenuates signal).
s = s.*(1/max(abs(s)));



figure
subplot(221) 
plot(real(s))
grid on; title('Real pulse-modulated baseband');

subplot(223)
stem(real(x_upsample))
grid on; title('Real symbol baseband');

subplot(222) 
plot(imag(s))
grid on; title('Imag pulse-modulated baseband');

subplot(224)
stem(imag(x_upsample))
grid on; title('Imag symbol baseband');

I = real(s);
Q = imag(s);

tx_sig = I.*cos(2*pi*fc*(t_s)) - Q.*sin(2*pi*fc*(t_s));
figure
plot(t_s, tx_sig); 
title('Carrier signal')
grid on;

if MODE == RX_MODE || MODE == BOTH_MODE 
    %% Record!
    my_sound = audiorecorder_example()
    if MODE == RX_MODE
        pause(10)
    end
end

% Play carrier wave in speakers!
% Create an audioplayer object to play the noise at a given fs.
if MODE == TX_MODE || MODE == BOTH_MODE 
    audio_player = audioplayer(tx_sig, fs);  
    playblocking(audio_player);   %Play the noise. Why blocking?
end

if MODE == RX_MODE || MODE == BOTH_MODE 
    figure
    plot(my_sound.getaudiodata); title('Recorded audio');


    % figure;
    % plot_fft(my_sound.getaudiodata.', 2*22050)

    s_noisy = my_sound.getaudiodata.';

 
end
