function [x, e,nvsave] = AdaDGS_BGColor(A, y, paras)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% AdaDGS for video background substraction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Input:
%%%   A:   collected background image matrix
%%%   y:  Current test image.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Output:
%%%   e:      the obtained foreground image
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%  J. Huang, et al., ”Learning with Dynamic Group Sparsity”, ICCV 2009. 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if iscell(y)  
    Jy = length(y); 
else Jy = 1; 
    A = {A}; y = {y}; 
end
m=size(A{1}, 1); T=size(A{1}, 2);
Jy=length(y);

maxnorm=0;
for i=1:Jy,
    normy(i) = norm(y{i}, 2);
end    
maxnorm=norm(normy, 2)/sqrt(Jy*m);

OptTol = 1e-6;  sigma = maxnorm*OptTol;
iter_num = 0; prev_stg_w = 0; 
resnv = maxnorm;

kxmax=paras{1}.k; kemax=paras{2}.k;
kstep1=2; kstep2=min(100, round(kemax/10));
kstep2=100;
% Tol1=log10(kstep1)*((m+T)/m)^4*1e-2;
Tol1=0.5e-1;
Tol2 = log10(kstep2)*((m+T)/m)^4*1e-2;
% Tol2=1e-2;


paras0=paras;
active_set=[];

%%%%%%%%%%%% (2) adjust the ke
% paras{2}.k=kstep2;
paras{2}.k=1;
resnv = maxnorm;
iter_num=1; nvsave(iter_num)=resnv;
x0=[]; e0=[];
while (resnv>sigma & paras{2}.k<paras0{2}.k)
    
    [x, e, normsave] = DGS_BGColor(A, y, x0, e0, paras);  
    for jj=1:Jy,
        yr((jj-1)*m+1:jj*m,1)=y{jj}-A{jj}*x((jj-1)*T+1:jj*T,1)-e((jj-1)*m+1:jj*m,1);
    end
%     index=find(e==0); 
    index2=find(e~=0); 
    yr(index2)=0;
    new_resnv=norm(yr, 2)/sqrt(Jy*m-length(index2));
%     new_resnv1=norm(yr, 2)/(Jy*m-length(index2))
%     new_resnv=normsave(end-1);
    w=[x(:);e(:)];
    new_active_set=find(w~=0);
    diff_set = setdiff(new_active_set, active_set);
    
%     extra_crit = (length(diff_set)<Tol1*length(active_set));
%     halt_crit = (abs(norm(w)-norm(prev_stg_w)) <Tol2*norm(prev_stg_w));
    halt_crit = (abs(new_resnv-resnv)) <Tol2*resnv;
%      halt_crit=0;
    if new_resnv>=resnv | halt_crit
            break;
    else % shift into a new stage
        disp('entering a new stage...')        
        kcurr2=paras{2}.k;
        paras{2}.k=kcurr2+kstep2;
        prev_stg_w = w;
        iter_num = iter_num +1;
        resnv = new_resnv;
        w_curr=w;
        x0=x; e0=e;
        nvsave(iter_num)=resnv;
    end
end

x(:,1)=w_curr(1:Jy*T,1); e(:,1)=w_curr(Jy*T+1:end,1);

return