%GENE real data
function [MODELORDER endmembers_hysime] = GENE_RMVES_REALDATA(X,P_FA,N_max)
% load 18Jan_real_data_188_40000;
% X =real_data_188_40000/10000;
XXXXX_ori = X;
[www Rwww]=estNoise(X,'off'); %used Hysime
CNN=Rwww;
save CnCn CNN;
load CnCn ;
Rw=CNN;Rw_ori=Rw;      %----this is D hat
% pree= sqrtm(Rw);
% X=inv(pree)*X;Rw=inv(pree)*Rw*inv(pree);
% % % % % % % % % % % % % 
%_______________________ 
p=2; 

[M,L] = size(X); 
d = mean(X,2);
U = X-d*ones(1,L);
R = U*U';
Rx_true = (R./L) - Rw;
[eV D] = eig(Rx_true);
C = eV(:,end:-1:M-(N_max-2));
save CCCC C;
save dddd d;
Xd_t = C'*(X-d*ones(1,L));  % Dimension reduced data vectors (Xd is (N-1)-by-L)
Rw_small= C'*Rw*C;     % this is sigma

for N=3:N_max,
% %     disp('___________');
       N;

[index]=GENE_TRIP2_RMVES(XXXXX_ori,N_max,2,N_max);
% [index]=GENE_TRIP2_RMVES(XXXXX_ori,N,2,N_max);

ALPHA_est = Xd_t(:,index);
 A_k_1 = ALPHA_est(:,[1:N-1]);
 a_k= ALPHA_est(:,N);
 clear yessame;
if (N>3)
    % Do the following optimization problem
    cvx_quiet(true)
    cvx_begin   
    variable theta_opt(N-1,1);
    minimize norm(a_k-A_k_1*theta_opt);
    subject to             
      %theta_opt>=0;
      ones(1,N-1)*theta_opt==1;
    cvx_end

    b_vector= a_k-A_k_1*theta_opt;
    zeta= theta_opt'*theta_opt ;  
    var_b = (1+zeta)*Rw_small;
    r=(b_vector'*inv(var_b)*b_vector);
    format long e
    zero_to_r = gammainc(r/2,(N_max-1)/2,'lower');
    r_to_inf= 1- zero_to_r;
    if (r_to_inf>=P_FA)
          %yessame=1; %The endmember is in the convex hull of previously found endmember estimates
          MODELORDER=N-1; break;
end
end
    %if any(yessame)==1, MODELORDER(snrr,kk)=N-1;  break;  else MODELORDER(snrr,kk)=0; end
end

%HySiMe
Y = X;
Ry=(Y*Y')/L;
Rx=Ry-Rw_ori;
[V,D]=eig(Rx);
ALL=V'*(-Rx + Rw_ori)*V;
ALL_D=diag(ALL);
index11=find(ALL_D<0);
[row column]=size(index11);
endmembers_hysime = row;

%------------------- removing the candidate pixels 

PP_Index =index ;
NN = MODELORDER;
NNN= NN +10 ;
[PP_Index] =[PP_Index(:,1:NNN)];
Xr=X; 
Xr(:,[PP_Index])=[];
XXX=Xr;
save XXX  ;
