function edg = eqspace(X, nb, range)

% EQSPACE Build edges for equi-spaced binning.
%
% USAGE
% -----
%
%       EDG = EQSPACE(X, NB)
%       EDG = EQSPACE(X, NB, RANGE)
%
% edg = eqspace(X, nb) return bin edges for quantizing all the values in X
% into NB bins equispaced in the range [min(X(:)), max(X(:))].
%
% edg = eqspace(X, nb, range) returns edges for quantizing all values of X
% into NB equispaced bins in the specified by the user with the variable
% RANGE.

%   Copyright (C) 2010 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.

% ----------
% DISCLAIMER
% ----------
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
% IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
% THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
% PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
% CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
% PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
% PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

% Changes-log:
% 30 Mar 2009, Cesare: added optional range parameter input

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

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

edg = linspace(lftEdg, rgtEdg, nb+1);
edg(nb+1) = edg(nb+1) + 1;