using PyCall
pygui(:qt)
using PyPlot
using WAV

using DSP
using MAT
push!(LOAD_PATH, "LOCALPKG/")
using LinearAcoustics_LOCAL
using ProximalOperators_LOCAL,RegLS_LOCAL


Lx = 7.34
Ly = 8.09
Lz = 2.87
Fs2 = 48000
Fs  =  8000

#src pos
pos = [2.000, 6.500, 1.425]

#mic pos
posm_all = [
	4.441 3.438 1.511; 
	4.441 3.388 1.511;
	4.441 3.338 1.511;
	4.441 3.288 1.511;
	4.441 3.238 1.511;
	4.441 3.188 1.511;
	4.441 3.138 1.511;

	4.561 3.559 1.511;
	4.611 3.559 1.511;
	4.661 3.559 1.511;
	4.711 3.559 1.511;
	4.761 3.559 1.511;
	4.811 3.559 1.511;
	4.861 3.559 1.511;

	4.441 3.526 1.556;
	4.441 3.526 1.606;
	4.441 3.526 1.656;
	4.441 3.526 1.706;
	4.441 3.526 1.756;
	4.441 3.526 1.806;
	4.441 3.526 1.856;
	    ]'

Nt2 = 8000
Nt  = ceil(Int,Nt2*(Fs/Fs2))
P2   = zeros(Nt2,21)
P = zeros(Nt,21)

for i = 1:21
	P2[:,i] = wavread("SMARD/1002_estimated_ir_ch$i.wav")[1][1:Nt2]
end

##resample at 8k
for i = 1:21
	P[:,i] = resample(P2[:,i],Fs//Fs2)
end

t2 = linspace(0,size(P2,1)*1/Fs2,size(P2,1))
t =  linspace(0,size(P ,1)*1/Fs ,size(P ,1))

P2 = [] #release some memory

#Nm = length(P)
#mic pos validation
V = [1;2;8;9;15;16]
#mic pos measurements
M = [3;4;5;6;7;10;11;12;13;14;17;18;19;20;21]

p_V = P[:,V] 
p_t = P[:,M] 
posV  = posm_all[:,V]
posm0 = posm_all[:,M]

Nt = size(p_t,1)
Nm = length(M) #mic number
X = norm(posm_all[:,1]-posm_all[:,2]) #distance between mics

### model source
#s = zeros(Nt)   #source signal
#s[1] = 1
#f2 = env.Fs/2*0.98#cut-off frequency of source
#filt!(s,digitalfilter(Bandpass(20,f2;fs = env.Fs),Butterworth(5)),s)
#s /= norm(s) #normalize
#
#

Nw = 700
xc = [
      minimum(posm_all[1,:]); 
      minimum(posm_all[2,:]); 
      minimum(posm_all[3,:]); 
     ]
r_w = 2.*minimum([Lx;Ly;Lz])/2      #radius of equivalent sources 
posw = SphFib(xc,r_w,Nw)           #position of equivalent sources


if acmod == pwdm
	p_t = fft(p_t,1)[1:floor(Int64,Nt/2)+1,:]
	p_V = fft(p_V,1)[1:floor(Int64,Nt/2)+1,:]
end
#
##plot(10*log10(abs(fft(sum([p_V p_t],2)))))
##plot(10*log10(abs(fft(s))))
#
#using PyPlot
#figure()
#plot(0:0.1:Lx,zeros(length(0:0.1:Lx)),"k")
#plot(zeros(length(0:0.1:Ly)),0:0.1:Ly,"k")
#plot(0:0.1:Lx,Ly*ones(length(0:0.1:Lx)),"k")
#plot(Lx*ones(length(0:0.1:Ly)),0:0.1:Ly,"k")
#plot(posw.pos[1,:]',posw.pos[2,:]',"r*")
##plot(posm_all[1,:]',posm_all[2,:]',"g*")
#plot(posm0[1,:]',posm0[2,:]',"g*")
#plot(posV[1,:]',posV[2,:]',"b*")
#
#
#
#
#
