function [ ind_dect detect_MUSIC err_A] = MUSIC_endm_detect( B,Pyort,Mp,sel_mat )
% The Robust MUSIC algorithm for endmember detection
% ------------------Input ----
% B: library
% Pyort: orthogonal projector to the complement of R(Us)
% Mp: the number of endemebers one wants to select
% sel_mat: selected materials, which is the true endmember index set
%------------------output ----
% ind_dect: detected endmember index
% detect_MUSIC: 1: sucess; 0: failure

N = length(sel_mat);

Lib = B;

err_A = sqrt(sum((Pyort*Lib).^2))./sqrt(sum(Lib.^2));

[sort_err_A ind_errA]=sort(err_A,'ascend');

ind_errAA=sort(ind_errA(1:Mp),'ascend');
LibA = Lib(:,ind_errAA);

ind_dect = ind_errAA(1:Mp);
correct_set = sel_mat;

% check whether we correctly detect the signatures
ind_dect = ind_errAA(1:Mp);
correct_set = sel_mat;

inter_set = intersect(ind_dect, correct_set);

inter_set = sort(inter_set,'ascend');

detect_MUSIC=0;
if length(inter_set)==N
    if inter_set == sel_mat;
        detect_MUSIC=1;
    end
else
    detect_MUSIC=0;
end


end

