function edges = ceqspace(X, nb, par)
% CEQSPACE Build edges for centered equi-spaced binning.

%   Copyright (C) 2009 Cesare Magri
%   Version: 1.0.2

% -------
% LICENSE
% -------
% This software is distributed free under the condition that:
%
% 1. it shall not be incorporated in software that is subsequently sold;
%
% 2. the authorship of the software shall be acknowledged and the following
%    article shall be properly cited in any publication that uses results
%    generated by the software:
%
%      Magri C, Whittingstall K, Singh V, Logothetis NK, Panzeri S: A
%      toolbox for the fast information analysis of multiple-site LFP, EEG
%      and spike train recordings. BMC Neuroscience 2009 10(1):81;
%
% 3.  this notice shall remain in place in each source file.

% Changes-log:
% 6  Apr 2009, Cesare: added optional D parameter
% 9  jul 2009, Cesare: incomplete error message fixed

meanX = mean(X(:));

minX  = min(X(:));
maxX  = max(X(:));

if nargin==3
    if isscalar(par)
        D = par;
        
        if minX<meanX-D || maxX>meanX+D
            msg = 'Values out of range provided.';
            error('ceqspace:XoutOfInterval', msg);
        end
    else
        msg = 'Invalid parameter.';
        error('ceqspace:invalidParameter', msg);
    end
else
    D = max(meanX-minX, maxX-meanX);
end

leftEdge  = meanX - D;
rightEdge = meanX + D;

spacing = (rightEdge-leftEdge) / nb;

edges = zeros(nb+1, 1);
edges(:) = leftEdge:spacing:rightEdge;
% Stretching last edge to accomodate maxX:
edges(nb+1) = edges(nb+1) + 1;