function BdBAv = spectogr (Sig, FSample, Nfft, NOverlap, NAverage)
%
% FUNCTION [S,T,F] = SPECTOGR (SIG, FSAMPLE, NFFT, NOVERLAP, NAVERAGE)
%
% DESCRIPTION
%   Plot spectogram of sequence Sig.
%
% PARAMETERS
%   Sig      - Time sequence 
%   FSample  - Sample frequency of time sequence
%   Nfft     - number of points per time step
%              to predict "current" spectrum
%   NOverlap - nr of points overlap between blocks
%   NAverage - nr of points to use for averaging spectrum
%
% RETURNS
%   Equivalent to SPECGRAM
%
%  ..Paul...
%

[B,F,T] = specgram (Sig, Nfft, FSample, hamming(Nfft), NOverlap);
NTimeBins = size(B,2);

if (nargin < 5) 
  DontAverage = 1;
else
  DontAverage = 0;
  NAvBlocks = floor(NAverage/(Nfft-NOverlap));
  Weight =  sin(0.5*pi/NAvBlocks*[1:NAvBlocks]') .^ 2;
  Weight = Weight/sum(Weight);
end;


BdB = 20 * log10(abs(B));
if DontAverage
  BdBAv = BdB;
else
  for i = 1:NTimeBins
    BMinIndex = max(1, i-NAvBlocks+1);
    WMinIndex = (NAvBlocks+1) - min(NAvBlocks, i);
    BdBAv(:,i) = BdB(:,BMinIndex:i) * Weight(WMinIndex:NAvBlocks);
  end;
end;

imagesc (T, F, BdBAv);
set(gca, 'ydir', 'normal');
xlabel ('Time (sec)');
ylabel ('Frequency (Hz)');


