%% Extract time from audio file

%% User input
dr=dir('*.wav');   % wave file
fr=44100;          % sample frequency
boff=13;         % time of begining 
eoff=[];        % time of end
cut=.16;           % cutoff for peak value

idr=dir('*.JPG');  % image files
info=imfinfo(idr(1).name);
base=info.DateTime([3 4 6 7 9 10 12 13 15 16 18 19]);

%% Calculated parameter

buf=fr*100;  % buffer size
lap=fr;      % overlap for buffer
off=boff*fr; % offset in samples

fsiz=wavread(dr(1).name,'siz');  % size of wav file
if(isempty(eoff))
	eoff=(fsiz(1)-lap)/fr;
end
siz=fix(eoff*fr)+lap;
Nbuf=fix((siz-off)/buf);
Nrem=(siz-off)-Nbuf*buf;

%% main loop

fprintf(1,'Processing...');
Nc=length(sprintf('%d',Nbuf+1));
fmt=sprintf('[%%0%dd/%%0%dd]',Nc,Nc);
fprintf(1,fmt,0,Nbuf+1);

tt=[];
for n=1:Nbuf+1
	if(n<=Nbuf)
		ss=wavread(dr(1).name,[(n-1)*buf+off+1-lap (n)*buf+off+lap]);
	else
		ss=wavread(dr(1).name,[(n-1)*buf+off+1-lap siz]);
	end
	p1=find(diff(ss(lap+1:end-lap)>cut)==1);
	p1=(p1(diff([1; p1])>fr/441));
	[mx pp1]=max(ss(mdiff(-fr/5:fr/5,-p1-lap)));
	tmp=[tt pp1+p1'+lap-fr/5-1+(n-1)*buf];
	tt=tmp;
	backspace(1,fmt,n,Nbuf+1);
	fprintf(1,fmt,n,Nbuf+1);
end
fprintf(1,'Done.\n');
tt=unique(tt);

save([base '_time.mat'],'tt','fr');






%% Correlation techique
% dr=dir('*.wav');
% ss=wavread(dr(1).name);
% ss=ss(:,1);
% ssp=0*ss;
% for n=1:NN
% 	tmp=(conv2(ss((1:60000)+3.1e5+20000*(n-2)),flipud(ss((1:20000)+3.1e5)),'same'));
% 	tmp=abs([conv2(tmp.*exp(2*pi*i*(7811)/60000*(1:60000)'),[1:19 18:-1:1]','same')]);
% 	ssp((1:20000)+(n-1)*20000)=tmp(20001:40000);
% 	plot(tmp);
% 	drawnow;
% 	n
% end
% i1=find(diff(ssp>80)==1);
% i2=find(diff(ssp>80)==-1);
% tt=(i1+i2)/2/44100;
