
clear all

nfft = 2048 ;
ampthreshold = -20 ;
max_freq_plot = 600 ;
render_method = 'fast_1_dot' ;
fft_overlap = fix(nfft*0.9) ;

pathname = 'C:\Documents and Settings\Bruce\My Documents\Octave\RA\' ;
fname = 'j_k_0421_growl_1.wav';

[y,Fs] = wavread([pathname,fname]);

%y = y(21000:31000,1);
%y = y(fix(2*Fs):fix(3.0*Fs),1) ;

figure(1);clf;
specgram(y(:,1),nfft,Fs,[], fft_overlap);
colormap gray
set(gca,'ylim', [0 max_freq_plot])
drawnow

figure(2);clf;
%raspecgram(y(:,1), nfft, Fs, [], fft_overlap, ampthreshold, render_method);
set(gca,'ylim', [0 max_freq_plot])
hold on
[X,F,T] = raspecgram(y(:,1), nfft, Fs, [], fft_overlap, ampthreshold, render_method);
plot(T,F,'.k')
set(gca,'ylim', [0 max_freq_plot])
hold on 
%parameters for median extractions
dt = 0.05 ;
NFreq = max_freq_plot/(Fs/nfft) ;
FFTdelta = Fs/nfft ;
SpaceFactor = 0.5 * FFTdelta ;
Nmin = 15 ; %min number of points in a group to consider it valid
timeIndex = 1;
time = 0:dt:length(y)/Fs-dt;

for t=0:dt:length(y)/Fs-dt
  
  sliceIndex = find(T>t & T<=(t+dt));
  Ts = T(sliceIndex);
  Fs = F(sliceIndex);
  Forder = sort(Fs);
  Fdiff = diff(Forder);
  Fdiff_edge = find(Fdiff>SpaceFactor) ;
  % get freq group averages
  clear Fmean Fmedian Fmin Fmax F1q F3q
  Fmedian = [] ;
  Fgroup = 1 ;
  Fstart = 1 ;
  if (~isempty(Forder))
    for i=1:length(Fdiff_edge)+1
      
      if i==length(Fdiff_edge)+1
        Fend = length(Forder) ;
      else
        Fend = Fdiff_edge(i)  ;
      end
      Fsel = Forder(Fstart:Fend);
      if length(Fsel) >= Nmin 
        Fmedian(Fgroup) = median(Fsel) ;
        Fmax(Fgroup) = max(Fsel) ;
        Fmin(Fgroup) = min(Fsel) ;
        F1q(Fgroup) = Fsel(max(1, fix(length(Fsel) * 0.25))) ;
        F3q(Fgroup) = Fsel(max(1, fix(length(Fsel) * 0.75))) ;
        line([(t+dt/2),(t+dt/2)],[F1q(Fgroup), F3q(Fgroup)],'markeredgecolor','r');
        Fgroup = Fgroup + 1 ;
      end
      Fstart = Fend + 1 ;
      
    end
    if ~isempty(Fmedian)
      plot(t+dt/2,Fmedian,'+r');
    end
  end
end

return
%Fhist = hist(F, NFreq);
%Fhist_starts = find (Fhist(3:end-3)>0 & Fhist(2:end-4)==0 & Fhist(1:end-5)==0);
%Fhist_ends = find (Fhist(3:end-3)>0 & Fhist(4:end-2)==0 & Fhist(5:end-1)==0);

figure(3);clf;
hist(F, NFreq)
set(gca,'xlim', [0 max_freq_plot])

%find the next T within delta in F

return

figure(3);clf;
specgram(y(:,1),nfft,Fs,[], fft_overlap);
colormap gray
hold on
render_method = 'fast_1_dot' ;
raspecgram(y(:,1), nfft, Fs, [], fft_overlap, ampthreshold, render_method);
set(gca,'ylim', [0 max_freq_plot])

