%Hecho con Álvaro
function y=peaks(x,w,N,H,t) 
%Analysis/sysntesis of a sound using the peaks 
%of the short-time fourier transform 
%x: input sound 
%w: analysis window (odd size) 
%N: FFT size 
%H: hop size 
%t: treshold in negative dB 
%y: output sound 
  
%Internal variables 
M=length(w); 
N2=N/2+1; 
soundlength=length(x); 
hM=(M-1)/2; 
 
%Pointers 
pin=1+hM; 
pend=soundlength-hM; 
  
%Initialize buffers 
fftbuffer=zeros(N,1); 
yw=zeros(M,1); 
y=zeros(soundlength,1); 
 
while pin<pend 
    xw=x(pin-hM:pin+hM).*w(1:M);           %Frame selector 
    fftbuffer=zeros(N,1);                  %Zero-phase windowing 
    fftbuffer(1:(M+1)/2)=xw((M+1)/2:M); 
    fftbuffer(N-(M-1)/2+1:N)=xw(1:(M-1)/2); 
     
    X=fft(fftbuffer);           %FFT Performance 
    mX=20*log10(abs(X(1:N2)));  %Compute FFT Magnitude 
    pX=phase(X(1:N2));     %Compute FFT Phase 
     
    ploc=1+find((mX(2:N2-1)>t).*(mX(2:N2-1)>mX(3:N2)).*(mX(2:N2-1)>mX(1:N2-2)));        %Peak search (levels above threshold) 
    pmag=mX(ploc);              %Find the peak magnitude 
    pphase=pX(ploc);            %Find the peak phase 
    % posipeak=length(ploc)/2;    %Just positive peaks 
 
    axis=linspace(0,pi,abs(N2));    %Axis for the whole frequency plotting 
    axis_peak=axis(ploc);%Axis for just the peaks plotting 
  
    subplot(2,1,1); plot(axis,mX); hold on ; %Magnitude plotting 
    plot(axis_peak,pmag,'rx');hold off;%Magnitude peaks plot red x’s 
    subplot(2,1,2); plot(axis,pX); hold on ;%Phase plotting 
    plot(axis_peak,pphase,'rx');hold off;%Phase peaks plot red x’s 
    getframe;
    pin=pin+H;                  %Advance the pointer 
end 
