function [s,f,t] = chunkspectrogram(filename,d_windo,d_nOverlap,d_nFFT, maxf)
%%
% d_ are the downsampled things
% o_ are the original things


d_fs = 11025;

[temp, o_fs] = wavread(filename,'size');

if mod(o_fs/d_fs,1) ~= 0
    error('The sample frequency of the wave file has to be an integer multiple of %1.0f.',d_fs);
end

o_nSample = temp(1);
d_nSample = floor(o_nSample*d_fs/o_fs);

o_nOverlap = d_nOverlap * o_fs/d_fs;


d_nSamplePerChunk = d_windo+200*(d_windo-d_nOverlap);

if d_nSample < d_nSamplePerChunk
    d_nSamplePerChunk = d_nSample;
end

d_endsample = d_nSamplePerChunk:d_nSamplePerChunk:d_nSample;

o_startsample = [1, d_endsample * o_fs / d_fs + 1];
o_endsample = d_endsample * o_fs / d_fs;
o_endsample = min(o_endsample + o_fs / d_fs * d_nOverlap, o_nSample); % extend so that chunks overlap

% in most cases the file length is not exactly a multiple of 
if o_endsample(end) < o_nSample
    o_endsample = [o_endsample o_nSample];
end

%%

nChunk = length(o_startsample);

for iChunk = 1:nChunk
    fprintf(1,'_');
end
leftpad = zeros(d_windo/2,1);
fprintf(1,'\n.')
x = resample(mean(wavread(filename,[o_startsample(1) o_endsample(1)]),2),d_fs,o_fs);
s = spectrogram([leftpad; x], d_windo,d_nOverlap,d_nFFT, d_fs);
f = (0:d_nFFT/2-1)/d_nFFT*d_fs;
if maxf < max(f)
    maxbin = find(f>maxf,1)-1;
else
    maxbin = length(f);
end
s = s(1:maxbin,:);
f = f(1:maxbin);
for iChunk = 2:nChunk-1
    fprintf(1,'.')
    temps = spectrogram(resample(mean(wavread(filename,[o_startsample(iChunk) o_endsample(iChunk)]),2),d_fs,o_fs), ...
        d_windo,d_nOverlap,d_nFFT, d_fs);
    s = [s(1:maxbin,:),temps(1:maxbin,:)];
end
x = resample(mean(wavread(filename,[o_startsample(nChunk) o_nSample]),2),d_fs,o_fs);
if length(x)>d_windo
    temps = spectrogram(x, ...
        d_windo,d_nOverlap,d_nFFT, d_fs);
    s = [s(1:maxbin,:),temps(1:maxbin,:)];
end
fprintf(1,'.\n')
t = (0:size(s,2)-1) * (d_windo-d_nOverlap)/d_fs;
