function [Aavg] = FNSL_Stock_Crossvalidation(X, Y, A0, kmax, lambda0)


% FNSL_Stock_Crossvalidation    Calculate sparse transition matrix
% through stocks data
% [Aavg] = FNSL_Stock_Crossvalidation(X, Y, A0, kmax, lambda0)
% X - Data matrix
% Y - Measurement matrix
% A0 - Initial point
% kmax - Maximum iteration
% lambda0 - Penalized parameter
% Avag - Estimated transition matrix


[n, d] = size(X);

alpha0 = 1;
etaMin = max(eig(X.' * X)) / 10;
eta00 = etaMin;

Aavg0 = A0;
Q0 = 0;

k = 1;

epsilon = 1e-2;

while k <= kmax
    
    while 1
    if k == 1
        alpha = alpha0;
        eta = alpha * eta00;
    else
        alpha = (- alpha0 * eta0 + sqrt(alpha0^2 * eta0^2 + 4 * eta00 * alpha0 * eta0)) / 2 / eta00;
        eta = alpha * eta00;
    end
    
    Amd = (1 - alpha) * Aavg0 + alpha * A0;
    
    temp = A0 - 1 / eta * X' * (X * Amd - Y);
    
    vecA = prox_operator_l1(reshape(temp, d*d, 1), lambda0, 1 / eta);
    
    A = reshape(vecA, d, d);
    
    Gamma = norm(A - A0)^2  - alpha / eta * norm(X * (A - A0), 'fro')^2;
    
    Q = (1 - 1 / k)^2 * Q0 + Gamma;
    
    if Q < - 1 / k^2
        eta00 = 2 * eta00;
    else
        break
    end
    end
    
    Aavg = (1 - alpha) * Aavg0 + alpha * A;

    k = k + 1;
    
    if norm(Aavg - Aavg0, 'fro') < epsilon 
        break
    end
    

    eta00 = max(etaMin, norm(X*(A - A0), 'fro')^2 / norm(A - A0, 'fro')^2);
    alpha0 = alpha;
    Aavg0 = Aavg;
    A0 = A;
    Q0 = Q;
    eta0 = eta;    
    
end

end
