clear all;
[d, fs]=wavread('sample.wav');
d=d(:,1);% an prokeitai gia stereo, alliws den xreiazetai
t=(0:length(d)-1)/fs;
max_1=max(abs(d));
d1=d/max_1;
figure; plot(t,d1); xlabel('time s'), ylabel('amplitute');

g=fft(d1(2001:3024).*hamming(1024, 'periodic'));
g1=fftshift(g);
f1=fs*(0:length(g)/2)/length(g);
figure;plot(f1,log(abs(g(1:length(g)/2+1)))); xlabel('frequency Hz'), ylabel('log(|F(normalized_signal)|) db');

s=real(ifft(log(abs(g))));
z=s(1:length(s)/2);

qufre=(0:length(s)/2-1)/fs;

figure; plot(qufre,z);xlabel('qufrency s'), ylabel('cepstrum');

%Pitch detection
x=xcorr(d1,fs/40,'coeff' );
t1=(-length(x)/2:length(x)/2-1)/fs;
figure;plot(t1,x); xlabel('time s'), ylabel('autocorrelationcoeff');
ms2=floor(fs/400); % 2ms an allaksete to fs allazei to 400 kai to 40
 ms20=floor(fs/40); % 20ms
 x1 = x(floor(length(x)/2)+1:end);
 [maxi,idx]=max(x1(ms2:ms20));
 f0 = fs/(ms2+idx-1); % i f0 xaraktirizei to pitch
 %One-sided signal 
 %genika filtrarw me parathiro evrous mikroteroy toy idx
 %p.x idx-10
 l=10;
 fwnitikos_swlinas=z(1:idx-l);%.*rectwin(idx-l);
 figure;plot(qufre(1:idx-l), fwnitikos_swlinas(1:idx-l));
  q_xordes=z(idx-l:length(z));
 figure;plot(qufre(idx-l:length(qufre)), q); axis([qufre(idx-l) qufre(end) -1 1]);
 
%Two-sided signal
 %b(length(s)/2+1:length(s))=s(1:length(s)/2);
%b(1:length(s)/2)=s(length(s)/2+1:end);
%figure;plot(b);
%fwnitikos_swlinas_all=b(length(b)/2-idx+l:length(b)/2+idx-l);
%figure;plot(fwnitikos_swlinas_all);
 
 

