function [counts, bins] = counthist(spikes, w)
% computes count histogram and compare them  with Poisson distribution
% spikes: a cell array of vectors of spike times
% w: observation window duration for computing the counts

    % collect spike counts:
    tmax = spikes{1}(end);
    n = [];
    r = [];
    for k = 1:length(spikes)
        for tk = 0:w:tmax-w
            nn = sum( ( spikes{k} >= tk ) & ( spikes{k} < tk+w ) );
            %nn = length( find( ( spikes{k} >= tk ) & ( spikes{k} < tk+w ) ) );
            n = [ n nn ];
        end
        rate = (length(spikes{k})-1)/(spikes{k}(end) - spikes{k}(1));
        r = [ r rate ];
    end
    % histogram of spike counts:
    maxn = max( n );
    [counts, bins ] = hist( n, 0:1:maxn+10 );
    counts = counts / sum( counts );
    if nargout == 0
        bar( bins, counts );
        hold on;
        % Poisson distribution:
        rate = mean( r );
        x = 0:1:maxn+10;
        l = rate*w;
        y = l.^x.*exp(-l)./factorial(x);
        plot( x, y, 'r', 'LineWidth', 3 );
        hold off;
        xlabel( 'counts k' );
        ylabel( 'P(k)' );
    end
end