% 
% Generate Samples of NRZ, Manchester and 4B5B/MTL-3 Line Codes
% Ed. Casas, 2016-4-6
% 

% number of bits and samples/bit

n=1E4 ;
ns=10 ;

% NRZ - rand() is uniformly distributed between 0 and 1.  The
% result of a comparison operator is 0 (false) or 1 (true).

x = rand(1,n) > 0.5 ;

% Manchester - alternate with the logical complement of each bit

y = [x ; ~x] ; 
y = y(:) ;

% 4B5B - random integers between 1 and 16 select a 5B output word

enc4b5b=[1,1,1,1,0;
   0,1,0,0,1;
   1,0,1,0,0;
   1,0,1,0,1;
   0,1,0,1,0;
   0,1,0,1,1;
   0,1,1,1,0;
   0,1,1,1,1;
   1,0,0,1,0;
   1,0,0,1,1;
   1,0,1,1,0;
   1,0,1,1,1;
   1,1,0,1,0;
   1,1,0,1,1;
   1,1,1,0,0;
   1,1,1,0,1] ;

m = floor(rand(n/4,1)*16)+1 ;
m = enc4b5b(m,:).' ;
m = m(:) ;

% MLT-3 - each '1' bit increments a count which, modulo-4, is the
% state of the encoder

encmlt3=[0.5,1,0.5,0] ;

m = mod(cumsum(m),4)+1 ;
m = encmlt3(m) ;

% replicate each value by ns (samples/bit)

x=ones(ns,1)*x ;
y=ones(ns/2,1)*y.' ;
m=ones(ns,1)*m ;

% write the samples in .RAF format

rafwrite('nrz.raf',x(:))
rafwrite('manchester.raf',y(:))
rafwrite('4b5bmlt3.raf',m(:))