//Program:
//Simple OFDM system
//Fire Wada Lab
//
//Usage:
//Execute-> Load into Scilab (or Ctrl L)

clear;
num_symbol = 2 ; // number of symbols
num_point = 1024; // points in symbol 
M = 4;             // size of signal constellation
modqpsk= [1+%i, -1+%i, 1-%i, -1-%i];


//1 . create random data
rand("uniform");
data = floor(rand(num_point,num_symbol)*M);
//data = [0 1 2 3];


//2. mapping into I-Q constellation
data_1 = matrix(modqpsk(1+data),num_point,num_symbol);

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


//serial to parallel
data_2 = data_1;


//3. IFFT 
data_3 = ifft(data_2);
subplot(2,2,2);
a = get("current_axes");
xtitle("IFFT");
plot((real(data_3)),'ob-');


//4. GI add
data_4 = [data_3(897:1024,:);data_3] ;

//4.1 Add Noise
sigpower=mean(abs(data_4).^2);
sn= 10; // 10dB
rand("normal");
awgn = (rand(num_point+128,num_symbol)+%i*rand(num_point+128,num_symbol));
awgnpower=mean(abs(awgn).^2);
awgn = awgn/sqrt(awgnpower)*10^(-sn/20)*sqrt(sigpower);
data_4=data_4+awgn;

subplot(2,2,3);
a = get("current_axes");
xtitle("GI add");
plot(real(data_4),'*cya--');


//5. GI remove
data_5 = data_4(129:1152,:);


//6. FFT
data_6 = fft(data_5);


//Parallel to serial
data_7 = data_6;

subplot(2,2,4);
a = get("current_axes");
xtitle("The result after FFT");
a.data_bounds = [-3,-3;3,3];
plot(real(data_7),imag(data_7),'r.');

// data decode
for j=1:num_symbol
  for i=1:num_point
    if    (real(data_7(i,j))>=0 & imag(data_7(i,j))>=0) then 
      decdata(i,j)=0;
    elseif (real(data_7(i,j))<0 & imag(data_7(i,j))>=0) then 
      decdata(i,j)=1;
    elseif (real(data_7(i,j))>=0 & imag(data_7(i,j))<0) then 
      decdata(i,j)=2;
    else
      decdata(i,j)=3;
    end
  end
end

// calculate number of different data
diff1 = data - decdata;
diff2 = sign(abs(diff1));
serr = sum(diff2)            // error symbols
tsym = num_point*num_symbol  // total number of symols
mprintf(' SNR(dB)= %3d    SYMBOL ERROR RATE = % 5.4e \n', sn, serr/tsym);

