function [d, r, b_error] = qpsk(N,M,snr)
%Spring 2000 ECOMMS Class Demo
%S. Mandayam, ECE Dept. Rowan University
%
%Quadrature Phase Shift Keying Demo
%Digital Bandpass Communications in the presence of Gaussian noise
%Function Usage:
%[d, r, b_error] = qpsk(N,M,snr)
%Function Inputs:
%N: Number of digital symbol data
%M: No. of M-ary states
%snr: SNR in fB
%Function Outputs:
%d: Digital Symbol Data Stream (generated randomly for M levels)
%r: Received, demodulated symbol data
%b_error: Number and ratio of bit errors

close all; 

%Assign digital data frequency, Fd (the baud rate), the carrier frequency, Fc and
%the computation sampling frequency, Fs.
%   Fs >> Fc >> Fd
Fd=1; Fc=10; Fs=100;

%Digital message source
d=randint(N,1,M);

%Digital data to analog signal mapping (Line Encoding)
m=modmap(d,Fd,Fs,'ask',M);
subplot(3,1,1);plot(m);
title('Baseband digital data');

%Modulation
s=dmod(d,Fc,Fd,Fs,'qask',M);
subplot(3,1,2);plot(s);
title('Bandpass modulated signal');

%Add effects of noise
%Compute signal variance 
var_s = cov(s); 
%Calculate required noise variance 
var_noise=var_s/(10^(snr/10)); 
%Generate noise 
n=sqrt(var_noise)*randn(length(s),1);

%Add signal to noise and generate message 
sn=s+n; 
subplot(3,1,3);plot(sn);
title(['Bandpass signal corrupted with noise, SNR = ' num2str(snr) 'dB']);

%Demodulation
fprintf(1,'Press any key to continue\n');
pause;
r=ddemod(s,Fc,Fd,Fs,'qask/scat',M);
title(['M = ' num2str(M) ', I-Q Constellation: No Noise']); 
fprintf(1,'Press any key to continue\n');
pause;
r=ddemod(sn,Fc,Fd,Fs,'qask/scat',M);
title(['M = ' num2str(M) ', I-Q Constellation: SNR = ' num2str(snr) 'dB']);

[number, ratio]=biterr(d,r);
fprintf(1,'No. of Bit Errors = %d\n',number);
fprintf(1,'Bit Error Ratio = %d\n',ratio);

b_error=[number, ratio];



