function [ ind_dect ] = RMUSIC_dict_prune( B,th,Pyort,Mp)
% The Robust MUSIC algorithm for endmember detection
% ------------------Input ----
% B: library
% th: the error boud
% Pyort: orthogonal projector to the complement of R(Y), Y is the M x L
% hyperspectral image, and L is the number of pixels
% Mp: the number of endemebers one wants to select
%------------------output ----
% ind_dect: detected endmember index

% reference:
%  X. Fu, W.-K. Ma, J. M. Bioucas-Dias, and T.-H. Chan,
% ''Semiblind Hyperspectral Unmixing in the Presence of Spectral Library Mismatches,''
%  IEEE Transactions on Geoscience and Remote Sensing, to appear, 2016.
%  coded by Jose Bioucas-Dias and Xiao Fu email: xfu@umn.edu


N = length(sel_mat);
nx = 256;

Lib = B;
b2 = Pyort*B;
b1 = B - b2;

b1 = sqrt(repmat(sum(b1.^2),nx,1));
b2 = sqrt(repmat(sum(b2.^2),nx,1));

x = repmat(linspace(0,1,nx)',1,size(Lib,2));

% solve the optimization problem
[aux, ~] = max(  (b1 + th*x) ./ abs(b2 - th*(1-x).^0.5));
err_C = sqrt(1./ (1 + aux.^2));

[~, ind_errC]=sort(err_C,'ascend');
ind_errCC = sort(ind_errC(1:Mp),'ascend');

% take out Mp endmembers with Mp smallest endmembers
ind_dect = ind_errCC(1:Mp);                 


end

