% LP_ANALYSIS.M
% Model a signal using LPC coefficients from HCode

LPWindow = 160;	% 10ms window
HalfWindow = 80;
LP = zeros(1,Size);
R = zeros(1,Size);
C = zeros(Size,17);

% Linear prediction is not applicable for the Header or the first LPWindow
LP(1:Header_size+LPWindow) = In(1:Header_size+LPWindow);

n_wins = fix((Size-Header_size)/HalfWindow);
shift = fix((Size-Header_size)/HalfWindow) - n_wins;

% compute LPC coefficients at end of each window
for n_win = 1:n_wins-2
	win_start = Header_size + (n_win+shift)*HalfWindow;
	win_end = win_start + LPWindow;
  [a,g] = lpc(In(win_start:win_end),16);
	C(win_end,:) = a;
%	C(win_end,:) = [1 LPC(n_win,:)];
end

% linearly interpolate intermediate samples
for n = Header_size+LPWindow+1:Header_size+((shift+n_wins-1)*HalfWindow)
        if C(n,1) == 0
        prev_win_no = fix((n-Header_size)/HalfWindow);
        next_win_no = prev_win_no+1;
        prev_n = Header_size+(next_win_no*HalfWindow);
        next_n = prev_n+HalfWindow;
        prev_C = C(Header_size+(next_win_no*HalfWindow),:);
        next_C = C(Header_size+((next_win_no+1)*HalfWindow),:);
        C(n,:) = prev_C + ((next_C - prev_C)/(n - prev_n));
        end
end

% model signal and estimate error
for n = Header_size+LPWindow+1:Size
	LP(n) = sum(-C(n,:).*[-1 LP(n-1) LP(n-2) LP(n-3) LP(n-4) LP(n-5) LP(n-6) LP(n-7) LP(n-8) LP(n-9) LP(n-10) LP(n-11) LP(n-12) LP(n-13) LP(n-14) LP(n-15) LP(n-16)]);
	R(n) = In(n)-LP(n);
	LP(n) = LP(n)+R(n); % if this is not added back the error accumulates 
end

LP(Header_size+1:Size) = In(Header_size+1:Size)-R(Header_size+1:Size)';

subplot(4,1,1)
plot(In(Header_size+1:Size))
title('Original signal (In)')
subplot(4,1,2)
plot(LP(Header_size+1:Size))
title('Linear prediction (LP)')
subplot(4,1,3)
plot(R(Header_size+1:Size))
title('Linear prediction residual (R)')


