% COMPLETE THE TRANSMITTER!

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

preamble = [1 1 1 1 1 -1 -1 1 1 -1 1 -1 1]; % length-13 Barker code

fs = 5000;  %sampling frequency
Tsamp = 1/fs;    % Sampling time
const = [(1 + 1i), (1 - 1i), (-1 -1i), (-1 + 1i)]/sqrt(2);      %4-QAM
% const = [-1 1] % BPSK
M = length(const);                                    % Number of symbols in the constellation
bpsymb = log2(M);                                     % Number of bits per symbol
Tsamp = 1/fs;                                         % Sampling time
Rb = 250;                                             % bit rate [bit/sec]
N = 432;                                     % number of bits to transmit
fsymb = Rb/bpsymb;                                    % Symbol rate [symb/s]
Tsymb = 1/fsymb;                                      % symbol time
fsfd = fs/fsymb;                                      % Number of samples per symbol (choose fs such that fsfd is an integer for simplicity) [samples/symb]
span = 6;   % Decides truncation for used pulse
a    = 0.2; % Roll off factor for our pulse

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

x = const(m_idx);                                     % Look up symbols using the indices



    x_upsample = upsample(x, fsfd);      % Space the symbols fsfd apart, to enable pulse shaping using conv.
   % figure; stem(real(x(1:5))); hold on
    %figure; stem(real(x_upsample))
    
    
    s = conv(rtrcpuls(a,Tsymb,fs,span),x_upsample); % Convolute 'pulse' with 'x_upsample'
    figure;
    p2 = plot(Tsamp*(-floor(length(rtrcpuls(a,Tsymb,fs,span))/2):length(s)-ceil(length(rtrcpuls(a,Tsymb,fs,span))/2)), real(s), 'b', 'LineWidth', 3);
    legend(p2,'s using convolution')
    
    figure
    stem(x_upsample)



%tx_signal = randn(1,1e4);  %vector of noise

tx_signal = s;


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