% generate a file of fec encoded data + noise
% mimics the demodulator output
% formatted to interface with the COM-1009 vhdl simulator
% Each new sample consists of 9 bits: 
%  4 bit soft-quantized demodulated sample
%
% 6/12/08 AZ
%
%---------------------------------------
% data source
%---------------------------------------
len = 6000; 
% Random data, array len x 1, randomly distributed integer between 0 and 1
msg = randint(len,1,2,94384); 
%msg=ones(len,1);

%---------------------------------------
% convolutional encoding
%---------------------------------------
% K=7, rate 1/2
t = poly2trellis(7,[133 171]); % Define trellis. G0=133 octal, G1=171octal
code = convenc(msg,t); % Length is 2*len.
tcode = 2*code-1; % Transmit -1s and 1s.

% puncturing (when enabled)
punctcode = tcode;  %disabled
% Puncture by removing every third value.
%punctcode(3:3:end)=[]; % Length is (2*len)*2/3.

%---------------------------------------
% channel = AWGN + 4-bit soft-quantization at the demodulator
%---------------------------------------
%add noise. 2nd argument is snr in dBs.
snr = 5; % in dBs
ncode = awgn(punctcode,snr,'measured',1234);

%4-bit quantization. symmetrical around zero
q = quantiz(7.5*ncode,[-7:1:7]);

%---------------------------------------
% convert to VHDL simulation format
%---------------------------------------
% 4 MSbits = 4-bit soft-quantized sample
% bit 3/2/1 = rate 1/2,3/4 or 7/8
% +8 = rate 1/2
% +4 = rate 3/4
% +2 = rate 7/8
qs(:,1:9) = dec2bin(q*32+8,9);
fid = fopen('fecdataout.txt','wt');
qssize = size(qs);
for i = [1:1:qssize(1)]
fprintf(fid,'%s\n',qs(i,:));
end;
status = fclose(fid);



%---------------------------------------
% Matlab fec decoding
%---------------------------------------
% Insert zeros.
%nicode = zeros(2*len,1); % Zeros represent inserted data.
%nicode(1:3:end) = ncode(1:2:end); % Write actual data.
%nicode(2:3:end) = ncode(2:2:end); % Write actual data.
%decoded = vitdec(nicode,t,96,'trunc','unquant'); % Decode.
%[number,ratio]=biterr(decoded,msg); % Bit error rate