function [y,i] = sort_key(x,n)
%SORT_KEY - Sort with column keys
% function [y,i] = sort_key(x,n)
% function [y,i] = sort_key(x,n);
% Sort the columns of x using the key orders in n
%  e.g. sort_key(x,[2 1 3]) means sort first by the second column, then ties in
%  the second column are sorted in the first column, then finally the third
%  column.
%
% If n got given, then columns sorted in column order, i.e. [1 2 3 . . .].
%
% y is the sorted matrix, equal to x(i,:);

%<autobegin> ---------------------- 26-May-2004 11:34:26 -----------------------
% --------- Automatically Generated Comments Block Using AUTO_COMMENTS ---------
%
% CATEGORY: Utility - Numeric
%
% At Check-in: $Author: Mosher $  $Revision: 6 $  $Date: 5/26/04 10:02a $
%
% This software is part of BrainStorm Toolbox Version 2.0 (Alpha) 24-May-2004
% 
% Principal Investigators and Developers:
% ** Richard M. Leahy, PhD, Signal & Image Processing Institute,
%    University of Southern California, Los Angeles, CA
% ** John C. Mosher, PhD, Biophysics Group,
%    Los Alamos National Laboratory, Los Alamos, NM
% ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory,
%    CNRS, Hopital de la Salpetriere, Paris, France
% 
% See BrainStorm website at http://neuroimage.usc.edu for further information.
% 
% Copyright (c) 2004 BrainStorm by the University of Southern California
% This software distributed  under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPL
% license can be found at http://www.gnu.org/copyleft/gpl.html .
% 
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%<autoend> ------------------------ 26-May-2004 11:34:26 -----------------------


if ~exist('n','var'),
   n = [1:size(x,2)];
end

n = n(:)'; % ensure a row vector

% now flip its ordering
n = n(end:-1:1);
% initialize the indexing
i = [1:size(x,1)]';

for j = n,
   % sort the jth column, using the ordering of the previous recursion
   [ignore,ii] = sort(x(i,j)); 
   i = i(ii);
end
y = x(i,:);

