function seg_wf3(wave,dataset,samp_start,n_shred,prefs)
% MODULE
%
% syntax seg_wf3(wave,dataset,samp_start,no_shred,convdata,filtdata)
% filtdata = [(pthresh) (cutoff) (averaging kernel size)]
% convdata = [(overlap) (mincalltime)]

timeint=length(wave.wf)/(length(wave.spec)*wave.fs);

filtdata = [prefs.threshold prefs.FIRcutoff prefs.gaussLPF];
threshold=prefs.threshold;

if prefs.FIRon==0
    filtdata(2)=0;
end

if prefs.gaussLPFon==0
    filtdata(3)=0;
end
   
if prefs.thresholdon==0
    filtdata(1)=0;
end

if prefs.buttfilton==1
    wave.spec=butt_filt(wave,prefs.cutoff,prefs.slope);
end
pthresh_med=(2*median(wave.spec(:)));


[wave.spec, threshold]=filt_spec(wave,filtdata);

if pthresh_med>threshold
    threshold=pthresh_med;
    wave.spec2=wave.spec.*(wave.spec>=pthresh_med);
else
    wave.spec=wave.spec.*(wave.spec>=threshold);
end

%disp(' - convolving spectrogram in time dimension');
mask=wave.spec>=threshold;
h=ones(1,round(prefs.mincallsep/(2*timeint)));
mask=(conv2(double(mask),double(h),'same')>0);
mask=mask>0;
reg_arr=[];


% if no data above threshold, return.
if max(mask(:))==0;
    %disp(' - no vocalisations found (1)');  
    return
end 

regions=bwlabel(max(mask,[],1));
for n=1:max(regions)
    find_reg=find(regions==n);
    find_reg_spec=find(max(wave.spec(:,find_reg(1):find_reg(length(find_reg))),[],1)>0);
    if length(find_reg_spec)<=round((prefs.mincalltime/timeint)) || min(find_reg)==1 || max(find_reg)==length(regions)
        regions=regions.*(regions~=n);
    end
end    

cfact=length(wave.wf)/length(wave.spec);

regions=bwlabel(regions);
for n=1:max(regions(:));
    find_reg=find(regions==n);
    reg_arr(n,1)=round((find_reg(1))*cfact);
    reg_arr(n,2)=round((find_reg(length(find_reg)))*cfact);
end  


if ~isempty(reg_arr)
    reg_arr=reg_arr+samp_start-1;
    reg_arr(:,3)=n_shred;
    reg_arr(:,4)=1;
    filename=strcat(prefs.proj_dir,'seg_data_',strrep(dataset,'.wav',''));   
    load(filename);
    if ~isempty(seg_data.reg_arr)
        seg_data.reg_arr=cat(1,seg_data.reg_arr,reg_arr);
    else
        seg_data.reg_arr=reg_arr;
    end
    seg_data.timeint=timeint;
    save(filename,'seg_data');
    %disp(strcat(' -  ',int2str(size(reg_arr,1)),' vocalisations found'));
else
    %disp(' - no vocalisations found (2)');
end   
