function [xnlt1, LYt1] = fgetk_implicit(xnl0,L,LXt1,LYt,Prec)
% Implicit Euler dt step for NL system
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

assert(~strcmp(L.code,'rzp'),'rzip is only a linear model for now, so can not run nonlinear time stepper');

%% Initial guess
Iet = [LYt.Ia;LYt.Iu];

MM = L.Mee; % + L.lin.Xee; % to eventually add plasma part
Iet1 = (MM + diag(LXt1.dt*L.Re))\...
  ([LXt1.dt*LXt1.Va;zeros(L.G.nu,1)] + MM*Iet); % linear step of coil-only circuit equation

% NL residual operator and initial guess
switch lower(L.P.algoNL)
  case 'picard'
    % initial guess passed via LXt1
    LXt1.Ie = Iet; % initial guess: from above
    LXt1.Iy = LYt.Iy; % initial guess: previous Iy
    F = @(xnl,doplot) fgeFpicard(xnl,L,LXt1,LYt,doplot);
  case 'all-nl'
    % initial guess passed via xnl0
    xnl0([L.ind.ia,L.ind.iu]) = Iet1; % assign in xnl0
    F = @(xnl,doplot) fgeF(xnl,L,LXt1,LYt,doplot);
  otherwise
    error('unknown solver method algoNL=%s]\n',L.P.algoNL)
end

%% Solve the equation F(xnl)=0
[xnlt1, solverinfo] = solveF(...
  F,xnl0,'algoF',L.P.algoF,'mkryl',L.P.mkryl,'Prec',Prec,...
  'relax',L.P.relax,'debug',L.P.debug,'kmax',L.P.kmax, ...
  'tolF',L.P.tolF,'robust_on',1,'algoGMRES',L.P.algoGMRES, ...
  'nrestarts',L.P.nrestarts);


if solverinfo.isconverged
  % Compute post processing
  [~,LYt1] = F(xnlt1,L.P.debug>2);
else
  % Keep previous solution
  xnlt1 = xnl0;  LYt1 = LYt;
  meqmsge('i',mfilename,L.P.tokamak,LXt1.t,solverinfo.niter,...
    L.P.shot,'Newton solver did not converge','FGE:nosolution');
end

%% other specific FGE outputs directly from LX
% append FGE-specific fields
LYt1.Va      = LXt1.Va;
LYt1.Ini     = LXt1.Ini;
LYt1.IniD    = LXt1.IniD;
LYt1.signeo  = LXt1.signeo;
LYt1.Lp      = LXt1.Lp;
LYt1.Rp      = LXt1.Rp;
LYt1.t       = LXt1.t;

%% Add convergence info
LYt1.res    = solverinfo.res;
LYt1.mkryl  = solverinfo.mkryl;
LYt1.nfeval = solverinfo.nfeval;
LYt1.niter  = solverinfo.niter;
LYt1.isconverged = solverinfo.isconverged;


end
