function [ CI, results, cfg ] = CI_glmqpoptim_fct( cfg, y, ~, X, U )

% Calculating GLM with smooth prior

fprintf('\n%% Calculating GLM with smoothness prior %%\n');

if strcmp(cfg.prior,'weight decay')
    qf = speye(size(X,2)+size(U,2));
    Q = tailmdx(qf,cfg.lambda_1);
elseif strcmp(cfg.prior,'none')
    qf = 0*speye(size(X,2)+size(U,2));
    Q=qf;
elseif strcmp(cfg.prior,'smoothness')
    [~,~,qf1,qf2] = qfsmooth(length(cfg.t), length(cfg.f));
    qfs = zeros([size(qf1)+size(U,2),2]);
    qfs(1:size(X,2),1:size(X,2),1) = qf1;
    qfs(1:size(X,2),1:size(X,2),2) = qf2;
    qf0 = 0*speye(size(qf1)+size(U,2));
    clear qf1 qf2
    qf = qfs(:,:,1) + qfs(:,:,2);
    clear qfs
else
    error('The specified prior does not exist');
end

if ~isfield(cfg,'Nfolds')
    cfg.Nfolds=5;
end
cfg.folds = getcvfolds(length(y),cfg.Nfolds);
opts.family = 'binomlogit';
opts.getH = 0;
if isfield(cfg,'lambda0')
    opts.lambda0 = cfg.lambda0;
end
if isfield(cfg,'stepsize')
    opts.stepsize = cfg.stepsize;
end
if isfield(cfg,'lambdamax')
    opts.lambdamax = cfg.lambdamax;
end
if isfield(cfg,'precision')
    opts.precision = cfg.precision;
end
if isfield(cfg,'maxiter')
    opts.maxiter = cfg.maxiter;
end

results = cvglmfitqp(y,[X,U],qf,cfg.folds, opts);
CI = reshape( results.w(1:end-size(U,2)), length(cfg.f), length(cfg.t));

if isyes(cfg.filtrage) % Filtrage si demande
    [ CI ] = lowpass_CI( CI, cfg.t, cfg.f, cfg.flt_freqcoup, cfg.flt_quefrcoup );
end

end
