clc;
clear all;
close all;
fclose all;


ref=wavread('swisha.wav');

signal=wavread('foo.wav');

oldsignal=wavread('bar.wav');

len=2*length(ref)

slen=length(signal)

reft=fft(ref,len);

lb=signal(1:slen,2);
imp=signal(1:slen,1);

lbt=fft(lb,len);
impt=fft(imp,len);

lbtd=lbt ./ reft;

imptd=impt ./ reft;
oslen=length(oldsignal);

oldref=oldsignal(1:oslen,2);
oldsig=oldsignal(1:oslen,1);

oldrt=fft(oldref,len);
oldst=fft(oldsig,len);

oldrtd=oldrt ./ reft;
oldstd=oldst ./ reft;


close all;
lbtddb=abs(lbtd(1:len/2+1));
t=max(lbtddb)
lbtddb=lbtddb/t;
lbtddb=max(lbtddb, .001);
lbtddb=20*log10(lbtddb);
f=(0:len/2)*22050/(len/2);
f=f';
subplot(3,1,1)
plot(f,lbtddb);

oldstdb=abs(oldstd(1:len/2+1));
t=max(oldstdb);
oldstdb=oldstdb/t;
oldstdb=max(oldstdb,.001);
oldstdb=20*log10(oldstdb);




subplot(3,1,2);
imptdb=abs(imptd(1:len/2+1));
t=max(imptdb);
imptdb =imptdb /t;
imptdb=max(imptdb, .001);
imptdb=20*log10(imptdb);
plot(f,imptdb,'m');
hold on
plot(f,oldstdb,'c');

lbat(1:len)=0;
lbat(1:len/2+1)=lbtd(1:len/2+1);
lba=abs(ifft(lbat));
t=max(lba);
lba=lba/t;
lba=max(lba,.01);
lba=log10(lba);

subplot(3,1,3)


sat(1:len)=0;
sat(1:len/2+1)=imptd(1:len/2+1);
sa=abs(ifft(sat));
t=max(sa);
sa=sa/t;
sa=max(sa,.01);
sa=log10(sa);

orat(1:len)=0;
orat(1:len/2+1)=oldrtd(1:len/2+1);
ora=abs(ifft(orat));
t=max(ora);
ora=ora/t;
ora=max(ora,.01);
ora=log10(ora);

osas(1:len)=0;
osas(1:len/2+1)=oldstd(1:len/2+1);
osa=abs(ifft(osas));
t=max(osa);
osa=osa/t;
osa=max(osa,.01);
osa=log10(osa);

[junk1,ins]=max(osa);
[junk,inr]=max(ora);


[junk1,inds]=max(sa);
[junk,indx]=max(lba);
xx=-100:1000;
xx=xx/44100*1153;
plot(xx, sa(indx-100:indx+1000),'m');
hold on;
plot(xx, lba(indx-100:indx+1000),'b');
plot(xx, ora(inr-100:inr+1000),'k');
plot(xx, osa(inr-100:inr+1000),'c');


sdif=inds-indx
dist=sdif/44100*1153
