function [G,mx,P,A] = LPC_analysis(s,K,Pmin,Pmax,vthr)
%
%  function:  [G,mx,P,A] = LPC_analysis(s,K,Pmin,Pmax,vthr)
%
%  LPC analysis of signal frame with optional pitch detection
% 
%  inputs:   s      input signal (one frame) 
%            K      predictor order
%            Pmin   minimum pitch period (number of sampling intervals)
%            Pmax   maximum pitch period (number of sampling intervals)
%            vthr   voiced threshold in normalized autocorrelation
%                   (vthr < 0 --> pitch detection off)
%
%  outputs:  G      gain factor (RMS of prediction error) 
%            mx     maximum of ACF r(i), i = Pmin...Pmax
%            P      pitch period (number of sampling intervals)
%            A      coefficients of inverse filter
% 

s = s(:);                             % make column vector
winSize = length(s);
sw = s.*hamming(winSize);             % windowing the input signal
[A,E] = lpc(sw,K);                    % evaluate predictor coefficients
G = sqrt(E)/0.54;                     % gain factor for unity excitation
                                      %   (compensation of window shape)

if vthr > 0,
  r = zeros(1,Pmax);    	      % pitch detection
  r0 = sw(1:winSize)'*sw(1:winSize);
  for i = Pmin:Pmax,                          % normalized autocorrelation
    r(i) = sw(1:winSize-i)'*sw(1+i:winSize);
    r(i) = r(i)/r0;
  end
  [mx P] = max(r(Pmin:Pmax));                 % maximum detection
  P = P+Pmin-1;
  if mx < vthr                                % unvoiced decision
    P = 0;
  end
else
  P = -1;                             % no pitch detection
  mx = 0;
end
