
%NOT DONE Need a list of bag labels first corresponding to the WAV files!


wavlist = dir(fullfile(mildatapath,'birds', 'wavs', '*.wav'));


mildata = [];
instlab=[];
bagid = [];

for j=1:length(wavlist)
    [signal,fs] = wavread(fullfile(mildatapath,'birds','wavs',wavlist(j).name));

    
    fmax = 256;
    [S,f,t] = spectrogram(signal,512,256,fmax,fs);
    
    s2 = specwhiten(S,fmax); 
    G = fspecial('gaussian',[5 5],2); 
    I = imfilter(abs(s2),G,'same');
    t = dd_threshold(I(:),0.95);
    mask = (I>t);
    mask(f<2000,:) = 0;


    labeledx = bwlabel(mask);
    Nseg = max(unique(labeledx)); %Segment labels, segment 0 is background

    absim = abs(S);
    realim = real(S);
    imagim = imag(S);

    

    maskfeats = nan(Nseg,3);
    absfeats = nan(Nseg, 7);
    
    
    bagjlab = baglabs(j,:);
    
    for i=1:Nseg

        ix = (labeledx == i);

        pixtotal = sum(sum(ix));
        pixheight = max(sum(ix,1));
        pixwidth = max(sum(ix,2));

        maskfeats(i,:) = [pixtotal pixheight pixwidth];


        seg = absim(ix);
        absfeats(i,1) = mean(seg); 
        absfeats(i,2) = std(seg); 

        absfeats(i,3) = quantile(seg(:),0);
        absfeats(i,4) = quantile(seg(:),0.25);
        absfeats(i,5) = quantile(seg(:),0.5);
        absfeats(i,6) = quantile(seg(:),0.75);
        absfeats(i,7) = quantile(seg(:),1);
        
        instlab = [instlab; bagjlab];
        bagid = [bagid; j];
    end
    
    segdata = [maskfeats absfeats];
    mildata = [mildata; segdata];
end

    
a = genmil(mildata, instlab, bagid, 'presence');
