function [x,count,sz]=NCEIC(N,g,alpha,beta,k,y,c,sig0)

% [x,count,sz]=NCEIC(N,g,alpha,k,y,c,sig0)

% perhaps i should restrict centroids to be only

% in [0,1], as image only takes values in this range



% does componentwise updating ... mu_1(1)..mu_1(d),mu_2(1)....mu_2(d),...,mu_k(1),...,mu_k(d)

% WITH INJECTION!



%  ff=0; % force better or not?

Sb=inf;



R_best=inf; R = nan;   







if nargin <6,

    fprintf('\nPlease supply parameters and data.\n')

    x=0;

    return;

end



[n,d]=size(y);



if nargin<7, % starting means if none supplied

c =   ones(k,1)*min(y)  + (diag(max(y) - min(y))*rand(d,k))';

end

if nargin<8,

sig0=max(max(y) - min(y))*1.0;

end



sig=ones(k,d).*sig0;

epsilon=10^-5;

ind=1;



dd=10;

ddd=2;

st=rand(dd,1)+n*n;

count=0;

tnew=0;

gentime=0;

sorttime=0;

updatetime=0;

tta=0;

tt=0;

qq=zeros(n,d);

nn=zeros(n,k);



    X=zeros(k,d,N);

    S=zeros(N,1);

co=zeros(k,d);

mu = zeros(size(c));

ccc=mu;



inj_cnt=0;

while inj_cnt < 100 % stop when injected x times 



    count=count+1;

pi=randperm(k*d);

for ij=1:k*d,

pp=pi(ij);

ii=floor((pp-1)/d)+1;

jj=mod((pp-1),d)+1;





    for i=1:N,

    ccc=c;

ccc(ii,jj)=ccc(ii,jj)+sig(ii,jj).*randn(1);



        X(:,:,i)=ccc;



for j=1:k,

    nnn(:,j)=sum((y-ones(n,1)*ccc(j,:)).^ddd,2);

end

S(i)=sum(min(nnn.^(1/ddd),[],2));



for j=1:k,



		for jjj=1:d,



				if (ccc(j,jjj)<0),



				S(i)=S(i) + 50 + 10*(-ccc(j,jjj));



elseif(ccc(j,jjj)>1),



S(i)=S(i)+50 +10*(ccc(j,jjj));



end



end



end



    end

    

    % Order Scores

    [S,I]=sort(S);

%%%%%%

%        fprintf('t = %d , g_hat_t = %g , S_star_t = %g, maximum sigma = %g\n',count,S(g),S(1),max(max(sig)))

%%%%%%



mu=sum(X(ii,jj,I(1:g)))./g;

co=std(X(ii,jj,I(1:g)),0,3);



%if ff==1,

%if S(1)<Sb,

%Sb=S(1);

%        c(ii,jj)=alpha*mu+(1-alpha)*c(ii,jj);

%        sig(ii,jj)=beta*co+(1-beta)*sig(ii,jj);

%end

%else

        c(ii,jj)=alpha*mu+(1-alpha)*c(ii,jj);

        sig(ii,jj)=beta*co+(1-beta)*sig(ii,jj);

        %end





R_old = R;

R=S(1); 

if R<R_best  E=X(:,:,I(1));  R_best=R;end

%injection

 if  max(max(sig))<0.01      

					  if (abs(R-R_old)*50)<.05,

     sig=sig+ones(k,d).*abs(R-R_old)*50;

%					  fprintf('inj : %g\n',abs(R-R_old)*50)

					  else

     sig=sig+ones(k,d).*.05;

%					  fprintf('inj : %g\n',.05)

end

     inj_cnt = inj_cnt + 1;





   end   





end

end



x=X(:,:,I(1));



sz=S(1);

