function Sim=sim_sortcat(Sim,varargin)
%--------------------------------------------------------------------------
% sim_sortcat function                                             ImBasic
% Description: Sort SIM catalogs by specific column.
% Input  : - SIM array of images or any valid input for images2sim.m
%          * Arbitrary number of pairs of arguments: ...,keyword,value,...
%            where keyword are one of the followings:
%            'SortCol' - Index or name of column to sort by.
%                        Default is 'YWIN_IMAGE'.
%            --- Additional parameters
%            Any additional key,val, that are recognized by one of the
%            following programs:
%            image2sim.m, images2sim.m, addcat2sim.m
% Output : - SIM array in whic the catalog entry is sorted by the
%            requested column.
% License: GNU general public license version 3
% Tested : Matlab R2015b
%     By : Eran O. Ofek                    Feb 2016
%    URL : http://weizmann.ac.il/home/eofek/matlab/
% Example: Sim=sim_sortcat(Sim,'SortCol','DELTAWIN_J2000');
% Reliable: 2
%--------------------------------------------------------------------------

CatField         = 'Cat';
CatColCellField  = 'ColCell';

DefV.SortCol = 'YWIN_IMAGE';
InPar = set_varargin_keyval(DefV,'n','use',varargin{:});


if (issim(Sim)),
    % do nothing
else
    % read images and populate catalog
    Sim = addcat2sim(Sim,varargin{:});
end

Nsim = numel(Sim);
for Isim=1:1:Nsim,
    % get the index of the column to sort by
    [~,ColSort]=col_name2ind(Sim(Isim).(CatColCellField),InPar.SortCol);

    % sort
    Sim(Isim).(CatField) = sortrows(Sim(Isim).(CatField),ColSort);
end

  