function counthist(spikes, w)
% Plot histogram of spike counts.
%
% counthist(spikes, w)
%
% Arguments:
%   spikes: a cell array of vectors of spike times in seconds
%   w: duration of window in seconds for computing the counts
    % collect spike counts:
    tmax = spikes{1}(end);
    n = [];
    r = [];
    for k = 1:length(spikes)
        times = spikes{k};
%       alternative 1: count the number of spikes in each window:
%         for tk = 0:w:tmax-w
%             nn = sum((times >= tk) & (times < tk+w));
%             %nn = length(find((times >= tk) & (times < tk+w)));
%             n = [n, nn];
%         end
%     alternative 2: use the hist() function to do that!
        tbins = 0.5*w:w:tmax-0.5*w;
        nn = hist(times, tbins);
        n = [n, nn];
    end

    % histogram of spike counts:
    maxn = max(n);
    [counts, bins] = hist(n, 0:1:maxn+10);
    % normalize to probabilities:
    counts = counts / sum(counts);

    % plot:
    bar(bins, counts);
    xlabel('counts k');
    ylabel('P(k)');
end