## Copyright (C) 2016 Valentin Gehrke
## 
## This program is free software; you can redistribute it and/or modify it
## under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
## 
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.

## -*- texinfo -*- 
## @deftypefn {Function File} {@var{retval} =} phasenmodulation (@var{input1}, @var{input2})
##
## @seealso{}
## @end deftypefn

## Author: Valentin Gehrke <s7745593@e03101>
## Created: 2016-07-28

datalen = 10;

pilot = [ 1 0 1 0 ];

dr = rand(1,datalen) > 0.5;

signallen = datalen + size(pilot,2);

d = [ pilot dr ];
n = 0:signallen-1;
phases = [ -pi/2 pi/2 ];
Tb = 0.3;
fc = 40;
fa = 1000;

subplot(6,1,1)
stem(n,d)

timelen = (signallen*Tb - 1/fa);

t = 0:(1/fa):timelen;
phi = phases( d( floor(t/Tb) + 1) + 1);

subplot(6,1,2)
plot(t,phi)
axis([0 timelen -pi pi])

s = cos(2*pi*fc*t + phi);

[bs,as] = butter(5,2*1.5*fc/fa);

slow = filter(bs,as,s);

subplot(6,1,3);
plot(t,slow);
axis([0 timelen -1.5 1.5])

noise = 1 * randn(size(slow));

sn = slow + noise;

subplot(6,1,4);

[bbp,abp] = butter(5,[2*0.5*fc/fa , 2*1.5*fc/fa]);
sbp = filter(bbp,abp,sn);

plot(t,sn);
axis([0 timelen -3 3])


sr = sbp .* cos(2*pi*fc*t);
si = sbp .* sin(2*pi*fc*t);

[b,a] = butter(5,2*0.7*fc/fa);

srlow = filter(b,a,sr);
silow = filter(b,a,si);

cmplxs = srlow + j*silow;

phase = angle(cmplxs);

m = zeros(size(phase));

for i = 1:size(t,2)
  [tmp, idx] = min(abs(phase(i) - phases));
  m(i) = idx-1;
endfor

subplot(6,1,5);
plot(t,phase,t,phases(m+1));
axis([0 timelen -pi pi])

ds = zeros(1,signallen);
for i = 1:signallen;
  ts = (i-1) * Tb;
  te = i * Tb;
  q = t > ts & t < te;
  ds(i) = mean(m(q)) > 0.5;
endfor

subplot(6,1,6)
err = (ds != d);
cla
stem(n(~err),ds(~err))
hold on;
stem(n(err),ds(err),'rx')
hold off;