function LX = fbtxtcv(t,L)
% LX = fbtxtcv(~,t,L)
% Build LX structure with FBT equilibrium definitions for TCV
% get data for fbt, take from P for now (since it is loaded from there in fbtptcv for now)
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

if ~isempty(t)
  kt = iround(L.P.t,t);
else
  kt = 1:numel(L.P.t); % take all
end

% time-dependent parameters being passed via fbtptcv
% pfields = {'idoublet','isaddl','issym','tol','capaj','niter'} these will be treated by fbtx
fields = {'t','Ip','qA','rBt'};

% add required fields to LX - augmenting where necessary
nt = numel(L.P.t); % time points passed from fbtptcv
for field=fieldnames(L.P)'
  myfield = field{:};
  if startsWith(myfield,'gp') % these should always have the correct size
    LX.(myfield) = L.P.(myfield);
  elseif ismember(myfield,fields)
    pvalue = L.P.(myfield);
    assert(size(pvalue,2)==nt,...
      'unexpected number of time slices for %s, found %d expected %d',myfield,size(pvalue,2),nt)
    LX.(myfield) = pvalue;
  end
end

% bffbt special
bfct = func2str(L.bfct);
if strcmp(bfct,'bffbt') || (strcmp(bfct,'bfgenD') && strcmp(func2str(L.bfp{1}),'bffbt'))
  LX.bfp = L.bfp;
end

% Downselect time indices
LX = meqxk(LX,kt);

end
