function edges = gseqspace(X, Nb, varargin)
% GSEQSPACE Builds edges for gaussian 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.

edges = zeros(Nb+1,1);

meanX = mean(X(:));
stdX = std(X(:));

if ~isempty(varargin)

    if isscalar(varargin{1}) && varargin{1}>0
        N = varargin{1};
    else
        msg = 'Parameter must be a positive scalar.';
        error('gseqspace:wrongParameterType', msg);
    end
else
    N = 2;
end
    
minEdge = meanX - N.*stdX;
maxEdge = meanX + N.*stdX;
spacing = (maxEdge-minEdge)/Nb;

edges(:)    = minEdge:spacing:maxEdge;
edges(Nb+1) = edges(Nb+1)+1;

% Stretching lower edge:
minX = min(X(:));
if minX<edges(1)
    edges(1) = minX;
end

% Stretching upper edge:
maxX = max(X(:));
if maxX>edges(end)
    edges(end) = maxX + 1;
end