% pack = message to be transmitted (consists of 432 bits from the GUI, always!)
% fc = carrier frequency
function transmitter(pack,fc)

%% DEBUG: Hardcode carrier.
% fc = 2000;  % Carrier frequency [Hz]

Rb = 480;          % bit rate [bit/sec]    
tx_fs = 12000;  % Sampling frequency [Sample/s]
Ts    = 1/tx_fs;  % Sample time [s/Sample]
span    = 6;   % Decides truncation for used pulse
rolloff = 0.4; % Roll-off factor (ie. alpha) for Raised Cosine pulse.

%% Preambles
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); % Choose preamble type.
preamble_symbs = preamble; % OPTIONAL. Map preamble to symbols.

%% Constellation
constellation = generateConstellation('8-PSK');

%% Bits to Messages
M = length(constellation); % Number of symbols in the constellation
bpsymb = log2(M);  % Number of bits per symbol
                             
Rsymb  = Rb/bpsymb;% Symbol Rate
Tsymb = 1/Rsymb;   % symbol time
sps    = tx_fs/Rsymb; % Samples per symbol. [Sample/s / Symbol/s = Sample/Symbol] 

m = buffer(pack, bpsymb);     %divides the packet to be sent into a number of packages with length bpsymb.
m_idx = bi2de(transpose(m), 'left-msb')+1;   % Bits to symbol index, msb: the Most Significant Bit

%% Message to symbol
message_symbs = constellation(m_idx);                                     % Look up symbols using the indices
symbs = [preamble_symbs, message_symbs];                                  % Please note that preamble is not tied to symbols at all. Can be good to remember this!
    
%% Pulse modulation
[pulse ~]  = rtrcpuls(rolloff, Tsymb, tx_fs, span); % Generate basis pulse.
symbs_upsample = upsample(symbs, sps); % Upsample to fs.
s          = conv(pulse, symbs_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.*(sqrt(2)/max(abs(s)));

%% Split into I/Q streams
I = real(s); 
Q = imag(s);

%% Upmix to carrier frequency (MAKE SURE THIS IS REAL AND NOT COMPLEX!)
tx_sig = I.*cos(2*pi*fc*(t_s)) - Q.*sin(2*pi*fc*(t_s));

player = audioplayer(tx_sig, tx_fs);  %create an audioplayer object to play the noise at a given sampling frequency
playblocking(player);   %Play the noise 