function [uval,lidx,uidx,sidx] = bssuniqueidx(x)
%BSSUNIQUEIDX - Find the unique elements (rows) of a vector (matrix).
%
% INPUTS:
%
%    x:
%        A data column vector or matrix whose elements are the rows.
%
% OUTPUTS:
%
%    uval:
%        A vector of the unique elements (rows) of x.
%
%    lidx:
%        A vector of lower index values for the unique sorted values in X.
%
%    uidx:
%        A vector of upper index values for the unique sorted values in X.
%
%    sidx:
%        The order vector for the rows of X.
%
%
% DESCRIPTION:
%
%     Find the unique values, their beginnning and ending positions
%     when sorted, and the order vector from the the input data array.
%

if ( isempty(x) )
    uval = [];
    lidx = [];
    uidx = [];
    sidx = [];
    return
end

if (~(iscolumn(x) || ismatrix(x)))
    error('The input must be a column vector, or a matrix.');
end

if ( any(isnan(x(:))) )
    error('NaN values are not allowed.');
end

if (iscolumn(x))
    if(~issorted(x))
        [x,sidx] = sort(x);
    else
        sidx(:,1) = 1:size(x,1);
    end
    uidx = [find(x(1:end-1)~= x(2:end));size(x,1)];
    uval = x(uidx);
elseif(ismatrix(x))
    if(~issorted(x,'rows'))
        [x,sidx] = sortrows(x);
    else
        sidx(:,1) = 1:size(x,1);
    end
    uidx = [find(any(x(1:end-1,:)~= x(2:end,:),2)); size(x,1)];
    uval = x(uidx,:);
end
lidx = [1;uidx(1:end-1)+1];
end

