function [LX] = fgsxtcv(t,Lo)
% FGSXTCV FGS Input data preparation for TCV
% LX = FGSXTCV(T,L) returns a structure with inputs for FGS
% The source can be set using L.P.insrc as either 'FBTE', 'LIUQE.M' or 'MAG'
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

switch lower(Lo.P.insrc)
  case 'fbt'
    [L,LX] = mds2meq(Lo.P.shot,'FBTE');
  case 'liu'
    [L,LX] = mds2meq(Lo.P.shot,'LIUQE.M');
  case 'mag'
    [L,LX] = mds2meq(Lo.P.shot,'MAG');
  case 'ids'
    error('case IDS not yet implemented');
  otherwise
    error(' case %s not recognized',Lo.P.insrc);
end

%% Select time indices for our t array
if isempty(t), t=LX.t; end
assert(~any( t>max(LX.t) | t<min(LX.t)),...
  'requested times [%4.2f,%4.2f] are out of range of available time [%4.2f,%4.2f]',...
      min(t),max(t),min(LX.t),max(LX.t));
  
fields= {'shot','t','Ip','Ia','Iu','Iv','Iy','rBt','Fx','FA','FB','qA','bt','li','Vp','bp','PpQ','TTpQ'};

% downselect fields and interpolate
LX = meqinterp(meqxk(LX,1:numel(LX.t),fields),t,Lo.P.interpmethod);  

% add missing fields
if Lo.P.idoublet
  LX = fgsxdoublet(Lo,LX); % add missing doublet fields
else
  L.nD = 1; 
end

% Convert to target L structure format
LX = meqxconvert(L,LX,Lo);
LX = meqreprocess(Lo,LX); % reprocess to get meqpdom/meqpost results

end

function LY=fgsxdoublet(L,LX)
% Recompute integrals and meqpdom outputs 
% for doublets since not stored in MDS

for kt=1:numel(LX.t)
  LXt = meqxk(LX,kt);
  
  [rA,zA,FA,dr2FA,dz2FA,drzFA,rX,zX,FX,~,~,~,~,~,...
    rB,zB,FB,lB,lX,Opy] = meqpdom(LXt.Fx,mean(LXt.Ip),L.P.isaddl,L);
  
  [F0,F1] = meqpdomlim(FA,FB,L.nD); % flux limits of various domains
  
  Iy(:) = 0; % init
  [~,TpDg,ITpDg] = L.bfct(1,L.bfp,LXt.Fx,F0,F1,Opy,L.ry,L.iry);
  
  ag = meqfitprof(L,L.pQ.^2,FA,FB,LXt.PpQ,LXt.TTpQ);
  
  LY0 = struct('shot',L.P.shot,'t',LX.t(kt)); % init
  LY(it) = meqpost(L,LY0,TpDg,ITpDg,ag,...
    Fx,FA,FB,rA,zA,dr2FA,dz2FA,drzFA,rB,zB,lB,lX,rX,zX,FX,...
    rBt,Ia,Iu,Iy,Opy); %#ok<AGROW>
end
LY = meqlpack(LY);
end
