function edges = eqspace(X, nb, par)
% EQSPACE Build edges for equi-spaced binning.

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

% -------
% 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.

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

if nargin==2
    leftEdge  = minX;
    rightEdge = maxX;
else
    range = par;
    if length(range)==2 && range(1)<range(2)
        leftEdge  = range(1);
        rightEdge = range(2);
    else
        msg = 'Invalid range.';
        error('eqspace:invalidInterval', msg)
    end
    
    if minX<leftEdge || maxX>rightEdge
        msg = 'Values out of provided range.';
        error('eqspace:XoutOfInterval', msg);
    end
end

spacing = (rightEdge-leftEdge) / nb;

edges = zeros(nb+1,1);
edges(:)    = leftEdge:spacing:rightEdge;
edges(nb+1) = edges(nb+1) + 1;