function [LL, speechseg, nspeechseg]=speechdetector (wav, f, resolution, maxtime)
%  [LL, speechseg, nspeechseg] = speechdetector (wav, f, resolution, maxtime);
% speechdetector parse the sound input (wav) into speech and nonspeech
% parts.
% f: sampling frequency of the waveform wav
% resolution: in milisecond window length of detection (default is 250ms);
% maxtime: in seconds maximum segment for continues analysis. default is 10
%   seconds
% LL: likelihood of speech at each time. Sampled at resolution.

% Nima Mesgarani, Neural Systems Lab, June 2005, mnima@glue.umd.edu

if nargin<4 maxtime=10;end
if nargin<3 resolution = 250;end
% parameters defintion
speechseg=[];
nspeechseg=[];
fs=16000; % in Hz, is the sampling frequency of the training set
cf= 7;cr=5;css=4;  % number of PCs in subspaces of frequency, rate and scale
rv=2.^(0:5);   % in Hz, specifies the rates (temporal modulations) being used
sv=2.^(-1:3);  % in Cyc/Oct, specifies the scales (spectal modulations) being used
frame=8;  % in miliseconds, is the sampling time of the auditory spectrogram
timestep=1; % in frames, specifies the amount of shift of the sliding window
sampstep=floor((resolution/2)/frame); % is the number of time frames that are averaged divided by 2
%%
figure;loadload;close;
paras=[frame frame -2 log2(fs/16000)];
if f~=fs wav=resample(wav,fs,f);end % adjust the sampling frequency
load (['HOSVD' num2str(resolution)]);
load (['net' num2str(resolution)]);
%
wav=[zeros(resolution/2*fs/1000,1); wav; zeros(resolution/2*fs/1000,1)];
for cnt1=1:ceil(length(wav)/fs/maxtime)
    disp(sprintf('processing %d of %d', cnt1, ceil(length(wav)/fs/maxtime)));
    wavstart=max(1,(1+(cnt1-1)*fs*maxtime)-resolution/2*fs/1000);
    wavend=min(length(wav),wavstart+fs*maxtime+2*resolution/2*fs/1000-1);
    sound=wav(wavstart:wavend);
    if strcmpi(computer,'pcwin')
        aud=cochlear_filt(unitseq(sound),paras);
        cor=c_aud2cor_calling_matlab_gencort(aud,[paras],rv,sv);
        cor=abs(double(permute(cor,[3 4 2 1 ])));
    else
        aud=wav2aud(unitseq(sound),paras);
        cor=abs(aud2cor(aud,[paras],rv,sv,'tmp',0));
    end
    for cnt2=1+sampstep:timestep:size(cor,3)-sampstep-1
        % rsf=squeeze(mean(cor(:,:,cnt2-sampstep:cnt2+sampstep,:),3));
        % ^ the above line can be written in the folowing way to make it 3
        % times faster:
        if cnt2==1+sampstep
            rsf=squeeze(sum(cor(:,:,cnt2-sampstep:cnt2+sampstep,:),3));
        else
            rsf=rsf-squeeze(cor(:,:,cnt2-sampstep-1,:))+squeeze(cor(:,:,cnt2+sampstep,:));
        end
        A=(rsf-mean2(rsf))/std2(rsf);
        A=tmuln(A,U{1}(:,1:css)',1);
        A=tmuln(A,U{2}(:,1:cr)',2);
        if length(size(A))<3 A=reshape(A,[1 size(A,1) size(A,2)]);end
        A=tmuln(A,U{3}(:,1:cf)',3);
        A=(A-mean2(A))/std2(A);
        [res(cnt2-sampstep:cnt2-sampstep+timestep-1,cnt1), ...
            LL(cnt2-sampstep:cnt2-sampstep+timestep-1,cnt1)]=svmfwd(net,A(:)');
    end
end
res=res(:);
LL=LL(:);
wav=wav(resolution/2*fs/1000:end-resolution/2*fs/1000);
res(floor(length(wav)/fs*1000/frame):end)=[];
LL(floor(length(wav)/fs*1000/frame):end)=[];
% segmentation
cnt1=1;
while cnt1<length(res)
    if res(cnt1)==1
        speechstart=cnt1;
        temp=find(res(cnt1+1:end)==-1);
        if isempty(temp) temp=length(res)-cnt1;end
        speechend=min(cnt1+temp(1)-1,length(res));
        cnt1=cnt1+temp(1);
        speechseg=[speechseg; wav(speechstart*frame*fs/1000:speechend*frame*fs/1000)];
    else
        nspeechstart=cnt1;
        temp=find(res(cnt1:end)==1);
        if isempty(temp) temp=length(res)-cnt1;end
        nspeechend=min(cnt1+temp(1)-1,length(res));
        cnt1=cnt1+temp(1);
        nspeechseg=[nspeechseg; wav(nspeechstart*frame*fs/1000:nspeechend*frame*fs/1000)];
    end
end
% resampling the sound and original sampling rate
if f~= fs
    if ~isempty(speechseg)
        speechseg = resample(speechseg,f,fs);
    end
    if ~isempty(nspeechseg)
        nspeechseg = resample(nspeechseg,f,fs);
    end
end
