function [B,I]=minklidx(A,k,dim,varargin)
%A version of [B,I]=mink(A,___) in which the minimizing indices I are returned as
%linear indices, so that one can simply do B=A(I).
%
%The syntaxes below, analogous to those of mink(), are supported.
%
%         B = minklidx(A,k)
%         B = minklidx(A,k,dim)
%         B = minklidx(A,k,dim,___mink_options___)


    if nargin==2, , %get first singleton dimension 
        dim=find(size(A)>1,1); 
        if isempty(dim), dim=1; end
    end

    if nargout==1
        B=mink(A,k,dim,varargin{:});
        return
    end




    sz=size(A);
    N=numel(sz);

    if dim>N
        B=A;
        I=reshape(1:numel(A),sz);
        return
    end

    sub=num2cell(ones(1,N));
    sub{dim}=':';
    
    b=mink(A(sub{:}),k,dim,varargin{:}); %Just do one vector - to detect output size

    gv=arrayfun(@(a)1:a,sz,'uni',0);  %grid vectors
    gv{dim}=1:numel(b);

    [F{1:N}]=ndgrid(gv{:}); %full grid

    [B,F{dim}]=mink(A,k,dim,varargin{:});

    I=sub2ind(sz,F{:});