%Funciton THR_ADAPT - Adaptive threshold for general VAD criterial function.
%
%Usage: [out,Dv,Dpv]=thr_adapt(Dv,[q,init]);              
%Input parameters:
%  Dv     - vector with dsitance function (criterial function)
%Optional input parameters:                                    <Default values>
%  q      - adaptation constant for mean value and variance averaging    <0.95>
%  init   - number of initial phase segments                          <2/(1-q)>
%Output parameters:
%  out    - output vector with values 0 or 1 for pause or speech
%  Dv     - vector with current distance (input)
%  Dpv    - vector with current thresholds 

%                              Made by PP
%                             CVUT FEL K331
%                           Last change 25/11/2005

function [out,Dv,Dpv]=thr_adapt(Dv,q,init);

if nargin<2,
  q=0.9
end;
if nargin<3,
  init=2*floor(1/(1-q))
end;

za=2;

Dmean=Dv(2);
Dmean2=Dv(2)*Dv(2);
Dvar=0;

out=[];
Dpv=[];

wnum=length(Dv);

for i=1:wnum,

  D=Dv(i);
  Dp=Dmean+za*sqrt(Dvar);

  Dpv=[Dpv Dp];

  if ( D>Dp & i>init ),
    out=[out 1];
  else
    out=[out 0];

    Dmean=q*Dmean+(1-q)*D;
    Dmean2=q*Dmean2+(1-q)*D*D;
    Dvar=Dmean2-Dmean*Dmean;
  end;

end;


out=out(:);
Dv=Dv(:);
Dpv=Dpv(:);  

if nargout < 1,
  figure(gcf); clf;
  x=1:length(out);
  subplot(211);
  plot(x,Dv,'r-',x,Dpv,'b--');
  title('Distance and adaptive threshold');
  xlabel('Frame No.');
  ylabel('Dv');

  subplot(212)
  plot(x,out,'g.-');
  title('Final detection');
  xlabel('Frame No.');
  ylabel('out');

end;

