%******************** 
% Preparation part 
close all;
clear all;
Fs=256000.0;        % Symbol rate
Nd = 200;           % Number of symbols that simulates in each loop
R=1;                % Number of oversamples
%************************* 
% Filter initialization
N=64;                       % Number of taps
alpha=0.22;                 % Rolloff factor
[Rx_fir] = hrollfcoef(N,R,Fs,alpha,0);   %Receiver filter coefficients 
%************************* Filter coefficient quantization ****************
b_CAN=12;                 % number of bit for receiver filter input  
b_h_rx=12;                % number of bit for receiver filter coefficients
b_rx=b_h_rx+b_CAN;    % number of bit for receiver filter output  
Rx_fir_q = round(Rx_fir.*2^(b_h_rx-1));
Rx_fir = Rx_fir_q.*2^(1-b_h_rx);
%**************************** 
% START CALCULATION
% Entree aleatoire 
data = 2*(0.5 - rand(1,Nd));   
% FILTRAGE CONVOLUTION 
dataf = conv2(data,Rx_fir);   
%**************************** 
% Affichage 
figure;
subplot(2,1,1); stairs(data); title('Random Input Data'); AXIS([1 Nd -1.1 1.1]);
subplot(2,1,2); stairs(dataf); title('Filtered Random Data'); AXIS([1 Nd -1.1 1.1]);
%**************************** 
% Stockage dans des fichiers
% Donnees d'entree
fid = fopen('DATA.dat','w');
fprintf(fid,'Input Data\n%d\n',Nd);
for ii=1:Nd
    fprintf(fid,'%d\n',data(1,ii));
end
fclose(fid);
% Donnees filtrees
fid = fopen('DATAF.dat','w');
fprintf(fid,'Filtered Data: dataf \n%d\n',length(dataf));
for ii=1:length(dataf)
 fprintf(fid,'%d \n',round(dataf(1,ii)*2^(b_rx-2)));
end
fclose(fid);
%**************************** 
% Generation du package pour le test 
fid = fopen('CDMA_pack.vhd','w');
fprintf(fid,'package CDMA_pack is\n');
% Input data
fprintf(fid,'type tabNd is array (0 to %d) of integer ;',Nd-1);
fprintf(fid,'constant input_data : tabNd := (');
for ii=1:Nd-1
    fprintf(fid,'%d, ',round(data(1,ii)*2^(b_CAN-1)));
end
fprintf(fid,'%d);\n\n',round(data(1,ii+1)*2^(b_CAN-1)));
% Rx Fir coefficients
fprintf(fid,'type tabFilterSize is array (0 to %d) of integer ;',length(Rx_fir_q)-1);
fprintf(fid,'constant H_Rx_fir : tabFilterSize := (');
for ii=1:length(Rx_fir_q)-1
    fprintf(fid,'%d, ',Rx_fir_q(ii));
end
fprintf(fid,'%d);\n\n',Rx_fir_q(ii+1));   
fprintf(fid,'end CDMA_pack;\n');
fclose(fid);
%******************************** end of file ********************************