% S-72.341 Coding Methods, spring 2004
%
% A script for simulating performance of 
% binary convolutional codes over 
% a BSC under Viterbi decoding. NN frames,
% each containing N information bits are
% transmitted per SNR value.
%
% You may modify this script as needed.






% SIMULATION PARAMETERS
%%%%%%%%%%%%%%%%%%%%%%%


N=10000;       % number of information bits in frame 
NN=100;   % number of frames to simulate for each SNR value

snr_in_db=[-4:6]; % SNR values per _information_ bit to be simulated



% code definition, replace with your personal code parameters
% trellis = poly2trellis([5],[25 33 37]);
trellis = poly2trellis([4],[13 15 17]);
code_rate=log2(trellis.numInputSymbols)/log2(trellis.numOutputSymbols);
memory=log2(trellis.numStates);


channel_snr=snr_in_db+10*log10(code_rate);  % SNR per coded bit
noise_var=0.5*10.^(-0.1*channel_snr);       % map channel snr to noise variance


num_err_coded=zeros(length(channel_snr),1);





t=cputime;

% simulation loop begins
for k=1:length(channel_snr)
disp([num2str(snr_in_db(k)) ' dB'])
for i=1:NN


% TRANSMITTER
%%%%%%%%%%%%%


x=[randint(N-memory,1,2);zeros(memory,1)];  % Notice that the encoder will now be terminated to zero state  
y=convenc(x,trellis,0);                     % convolutional encoding, initial state =0
z=1-2*y;                                    % map bits to BPSK symbols



% AWGN CHANNEL
%%%%%%%%%%%%%%

z_r=z+sqrt(noise_var(k))*randn(size(z));





% RECEIVER
%%%%%%%%%%

y_r=-0.5*(sign(z_r)-1);                     % map BPSK symbols to bits
x_r=vit_bsc(y_r,trellis, .. more args?..);  % YOUR VITERBI DECODER


% You can verify that your decoder works correctly with the following MATLAB function
% x_r=vitdec(y_r,trellis,N,'term','hard'); 



num_err_coded(k)=num_err_coded(k)+biterr(x,x_r); % number of errors after decoding

end 
end % end of simulation loop


disp(['CPU time: ' num2str(cputime-t)])



ber_coded=num_err_coded/N/NN;
save ber ber_coded snr_in_db










