function LX = fgex(tok,t,L,LX)
% Get initialization data for fge. 
% function LX = fgex(tok,t,L); % retrieves initial eq from FGS
% function LX = fgex(tok,t,L,LX); % provid initial eq explicitly
% For information about the content of LX, use help meqt
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

if nargin<=3
  fgsxtok = str2func(['fgsx',tok]);
  LX = fgsxtok(t(1),L);
end
LX = meqxconvert(L,LX,L); % fill potentially missing fields

if isempty(t)
  t = LX.t;
end

%% Time-varying quantities needed
% Need time-varying values for constraints and some other quantities
fields = cell(1,L.nC); % init
for iC = 1:L.nC
  fields{iC} = L.agconc{iC,3}; % field used for constraint equation
end
% other necessary quantities for FGE
fgefields = {'IniD','Ini','signeo', 'Lp', 'Rp'};
fields = [fields,fgefields];

% get time-varying fields into LX
for field=['t',fields]
  LXt.(field{:}) = LX.(field{:});
end

if numel(LXt.t)==1
  % copy single time slice to other times
  LXt = meqlpack(repmat(LXt,1,numel(t)));
  LXt.t = t;
end

%% Initial condition
% compute initial condition from first time slice of LX according to the
% code used (fge or rzp)
LX = L.codeinit(L,meqxk(LX,1)); 

%% re-insert required time-varying fields into LX0
for field = fieldnames(LXt)'
  LX.(field{:}) = LXt.(field{:});
end

% Time-varying feedforward Va trajectory to keep initial equilibrium
LX.Va = LX.Va(:,1) + LX.Vadot0*(LX.t-LX.t(1));
LX.Ia = LX.Ia(:,1) + LX.Iadot0*(LX.t-LX.t(1));

% Strip some unneeded FBT & LIUQE stuff
fieldsrm = {'Sp','Ep','chi','chie','Fb', 'cycle', 'dz', 'dzg', 'rst', 'chih','idoublet'};
for field = fieldsrm
  if isfield(LX,field{:}), LX = rmfield(LX,field{:}); end
end

LX = meqx(L,LX); % generic LX handling

end
