function y = sparsespec(x, numffts, spacing, winlen, plotthis)
%y = sparsespec(x, numffts, spacing, window)
% this computes what I call a sparse spectogram.
% x is the data sample.
% numffts determines the number of ffts that we will compute, spaced
% evenly throughout the sample.
% spacing is the spacing within the fft (do we skip samples?).
% we arent going to window each frame, but we need a frame size: winlen
% if plotthis = 'y' we will plot it.
%
%
% a normal spectogram shifts its window by 1 for the next fft.
% this creates an output that requires n^2 blocks of data, which is way too
% much to store, and too much information to be useful (especially at high
% sampling frequencies).
%
% note that some infomation may be lost at the end
% you must make sure that the fftspacing is larger than the window
%
% I assume that the input vector is real-valued for plotting
%
% the columns of y are the ffts

len = length(x);

Lfft = winlen * spacing;

if Lfft*numffts <= len %we have room for pads
    pad = floor((len-Lfft*numffts)/(numffts-1));
    first = (Lfft+pad)*((1:numffts)-1)+1;
    last = first + Lfft - 1;
    %'case 1'
elseif len - Lfft + 1 < numffts
    len
    Lfft
    numffts
    'error: too many ffts, not a large enough sample'
else %must overlap the ffts
    %'case 2'
    overlap = ceil((Lfft*numffts-len)/(numffts-1)); %overlap between each frame
    first = (Lfft * ((1:numffts)-1) + 1) - ((1:numffts)-1)*overlap;
    last = first + Lfft - 1;
end

y = zeros(winlen, numffts);

for i = 1:numffts
    f = first(i); %this is the first element for this fft
    l = last(i);
    x1 = x(f:spacing:l);
    y(:,i) = x1;
end

y = abs(fft(y));
last = ceil((winlen + 1)/2);
y = y(1:last,:);

if 'y' == plotthis
    figure(1)
    mesh(y);

    figure(2)
    imagesc(y);
end