//
// OFDM SCILAB SIMULATION
// 2008/DEC/5
// Tom WADA
num_symbol=100;
num_carrier=16;
M=4;
modqpsk=[1+%i, -1+%i, 1-%i, -1-%i];

//1 generate random data
rand("uniform");
data = floor(rand(num_carrier,num_symbol)*M);

//2 mapping to I-Q constellation
data_s = matrix(modqpsk(1+data),num_carrier,num_symbol);

subplot(2,2,1);
a=get("current_axes");
a.data_bounds=[-3,-3;3,3];
xtitle("SEND");
plot(real(data_s), imag(data_s),'r.');

//3 IFFT matrix WP
for row=1 : num_carrier
  for col=1 : num_carrier
    WP(row,col)=1/sqrt(num_carrier)*exp(%i*2*%pi*(row-1)*(col-1)/num_carrier);
  end
end

//4 OFDM signal generation
sdwv=WP*data_s;
sdwv2=mtlb_ifft(data_s);

//5 Channel Impulse Response
cir=[0;1;0.5;0.25;0;0;0;0;0;0;0;0;0;0;0;0];
//cir=[1;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0];
HH=[];
for I=1:16
  HH=[HH,[cir(16-(I-2):16);cir(1:16-(I-1))]];
end

//6 Receiver wave
rvwv=HH*sdwv;

//7 Add Noise
sigpower=mean(abs(rvwv).^2);
sn= 100; // 10dB
rand("normal");
awgn = (rand(num_carrier,num_symbol)+%i*rand(num_carrier,num_symbol));
awgnpower=mean(abs(awgn).^2);
awgn = awgn*sqrt(sigpower)/sqrt(awgnpower)*10^(-sn/20);
rvwv=rvwv+awgn;

//8 FFT matrix WPC
for row=1 : num_carrier
  for col=1 : num_carrier
    WPC(row,col)=1/sqrt(num_carrier)*exp(-%i*2*%pi*(row-1)*(col-1)/num_carrier);
  end
end

//9 FFT
data_r=WPC*rvwv;

subplot(2,2,2);
a=get("current_axes");
a.data_bounds=[-3,-3;3,3];
xtitle("RECEIVE");
plot(real(data_r), imag(data_r),'b+');

//10 D matrix
D=WPC*HH*WP;

//11 E (Equalizer matrx)
E=zeros(num_carrier,num_carrier);
for I=1:16
  E(I,I)=1/D(I,I);
end

//11 Equalize
data_eq=E*data_r;

subplot(2,2,3);
a=get("current_axes");
a.data_bounds=[-3,-3;3,3];
xtitle("EQUALIZED");
plot(real(data_eq), imag(data_eq),'r+');
