%Project 
%Test basic modulation methods such as BPSK and QAM
%Two parts
%   1. show wav form, constellation, eye diagram and BER
%   2. transmit your own photo.
%
%please devide to two files
clear all; close all;

%N oversample ratio
%Fd symbol per second
%Fs sample per second
%Delay filter dealy
%Symb number of samples
%M modulation level, M=2, BPSK, M=4, QPSK, M=16, MQAM
N = 16; Fd = 1; Fs = N * Fd; Delay = 3; Symb = 60; M = 2;

%random generate the symbols
msg_orig = randsrc(Symb,1,[0:M-1]);
%modulation: need to design your own
msg_tx = qammod(msg_orig,M);
%filter
[y, t] = rcosflt(msg_tx, Fd, Fs);

% Plot transmit data, there is no ISI
figure(1)
tx = [Delay : Delay+ Symb - 1] ./ Fd;
stem(tx, msg_orig*2-1, 'kx');hold on
plot(t, real(y));

% Plot Eye Diagram, very clear
h1 = eyediagram(y([Delay *Fs+0.5: 1: (Delay+ Symb - 1)*Fs]+0.5 ), N);
% Plot scatter plot, no scatter
h6 = scatterplot(y, N);

%pass through AWGN channel
SNR = 10;
sig_rx = awgn(msg_tx,SNR);
%raise cosine filter
[fsig_rx, t2] = rcosflt(sig_rx, Fd, Fs);
%alignment
tfsig_rx = fsig_rx(1+Delay*N:end-Delay*(N+1),:);
%time domain data, with ISI
figure(1)
plot(t, real(y),'b-', t2, real(fsig_rx),'r-');
%with scatter and closed eyes
h6 = scatterplot(tfsig_rx, N);
h1 = eyediagram(tfsig_rx, N);

%calculate the BER
%see the example of basicsimdemo
%for SNR=0dB, SNR=2.5dB, and SNR=5dB
%compared with the theoretical 

pause 
%Image part
%read image
%image_data is 512*512 8 bit matrix
image_data=imread('lena.bmp');
image_rec=zeros(512:512);
for i=1:1:512
    %put decimal to binary, matrix to a vector
    b=de2bi(image_data(i,:));
    image_orig=reshape(b',512*8,1);
    %transmit through the above channel for 
    image_tx = qammod(image_orig,M);
    %filter
    [y, t] = rcosflt(image_tx, Fd, Fs);
    
    %consider 
    SNR = 0;
    image_rx = awgn(y,SNR);

    %down sample and alignment
    sample_error=0; %sample_error can be from 0 to 15.
    image_rx_down = image_rx(1+sample_error:N:1+4101*16+sample_error);
    tfimage_rx = image_rx_down(1+Delay:1:4096+Delay);

    %need your receiver to decode
    image_dec= qamdemod(tfimage_rx,M);
    %reconstruct image
    image_rec(i,:)=bi2de((reshape(image_dec,8,512))');
    disp(i)
end
image_final=uint8(image_rec);
%write image
imwrite(image_final,'lena_received.bmp','BMP')
