%%% OFDM - ECE 376 - 21.04.2010 %%%
clc ;clf reset;close all;warning off MATLAB:divideByZero
sitil = ['-k  ';'--k ';':k  ';'-.k ';'-*k ';'--sk';':ok ';'-.^k';'-sk ';'--sk';':sk ';'-.sk'];linwid = [2 3 3 2 2 2 1 2 2 2 2 2];
W = 100; N = 8;k = 1:N;T = N/W;inc = 0.001;
t = 0:inc:T-inc;ctmat = [];Fi = zeros(1,N);Fi = [1 3.7 5.5 2.5 0.1 0.3 0.7 1.2];lent = length(t);
for ik = 1:length(k);ct = cos(2*pi*W*k(ik)/N*t + Fi(ik));ctmat = [ctmat;ct];end
figure(1)
for ik = 1:N;plot(t/1e-3,ctmat(ik,:),sitil(ik,:),'LineWidth',linwid(ik));hold on;end
hold off;set(gcf,'Color',[1 1 1]);set(gca,'FontSize',18)
xlabel('Time (mseconds)','FontSize',16,'FontWeight','bold');
ylabel('Amplitude','FontSize',16,'FontWeight','bold')
title('OFDM carriers with and without phase differences','FontSize',16);
%%%% Frequency Spectrum 
NFFT = 2^nextpow2(length(t) + 600); Cfmat = [];Fs = 1000;
for ik = 1:N;Cf = fft(ctmat(ik,:),NFFT)/length(t);Cfmat = [Cfmat;Cf];end
f = Fs/2*linspace(0,1,NFFT/2);
figure(2)
for ik = 1:length(k);plot(f,(2*abs(Cfmat(ik,1:NFFT/2))),sitil(ik,:),'LineWidth',linwid(ik));hold on;end 
%for ik = 1:length(k);plot(f,10*log10(2*abs(Xfmat(ik,1:NFFT/2))),sitil(ik,:),'LineWidth',linwid(ik));hold on;end 
hold off;set(gcf,'Color',[1 1 1]);set(gca,'FontSize',18)
title('Frequency spectrum of modulated OFDM subcarriers ','FontSize',16);
xlabel('Frequency (Hz)','FontSize',16,'FontWeight','bold')
ylabel('Amplitude','FontSize',16,'FontWeight','bold')

%%%% Orthogonality test
Rtmat = [];
for ik = 1:N;Rtr = [];for ij = 1:N;
    Rt = ctmat(ij,:)*ctmat(ik,:)'/(ctmat(ij,:)*ctmat(ij,:)');
    Rtr = [Rtr Rt];end;Rtmat = [Rtmat;Rtr];end
Rtmat
%%%% Creating sysmbols and placing them onto carriers
s1 = 1*ones(1,length(t));s3 = j*ones(1,length(t));s5 = -1*ones(1,length(t));s7 = -j*ones(1,length(t));
s2 = 1*ones(1,lent) + j*ones(1,lent);s4 = -1*ones(1,lent) + j*ones(1,lent);s6 = -1*ones(1,lent) - j*ones(1,lent);s8 = 1*ones(1,lent) - j*ones(1,lent);
sxt = [s1;s2;s3;s5;s6;s8;s7;s4].*ctmat; %%% Modulation
st = sum(sxt,1); %%% Sum of modulated signals
figure(3)
plot(t/1e-3,st,sitil(1,:),'LineWidth',linwid(1));
set(gcf,'Color',[1 1 1]);set(gca,'FontSize',18)
xlabel('Time (mseconds)','FontSize',16,'FontWeight','bold');
ylabel('Amplitude','FontSize',16,'FontWeight','bold')
title('Sum of OFDM signals along time axis','FontSize',16);
%%%% Demodulation
yt = st*ctmat(4,:)'/length(t)*2  % Demodulated symbol
figure(4)
plot(t/1e-3,yt,sitil(1,:),'LineWidth',linwid(1));
set(gcf,'Color',[1 1 1]);set(gca,'FontSize',18)
xlabel('Time (miliseconds)','FontSize',16,'FontWeight','bold');
ylabel('Amplitude','FontSize',16,'FontWeight','bold')
title('Demodulated QAM symbol','FontSize',16);