function LYnew = meqreprocess(L,LY)
% Reprocess LY structure recomputing meqpdom and meqpost outputs
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

warnid = sprintf('%s:INACCURATE_PROFILE_FIT',upper(mfilename));

% Init aq, aW
aq = []; aW = [];

for kt = 1:numel(LY.t)
  LYt = meqxk(LY,kt);
  
  % find plasma domain
  [rA,zA,FA,dr2FA,dz2FA,drzFA,rX,zX,FX,~,~,~,rl,zl,...
    rB,zB,FB,lB,lX,Opy] = meqpdom(LYt.Fx,LYt.Ip,L.P.isaddl,L); %#ok<ASGLU>
  
  % refit ag basis function coefficients (should do always because basis
  % functions may have changed)
  assert(L.nD==1, 're-fit of P'' and TT'' for multiple domains not available')
  LYt.ag = meqfitprof(L,L.pQ.^2,LYt.FA,LYt.FB,LYt.PpQ,LYt.TTpQ);
 
  % post-processing
  [F0,F1] = meqpdomlim(LYt.FA,LYt.FB,L.nD); % flux limits of various domains
  [~,TpDg,ITpDg] = L.bfct(1,L.bfp,LYt.Fx,F0,F1,Opy,L.ry,L.iry); % basis function evaluations for integrals
  
  LYtnew = struct('shot',LYt.shot,'t',LYt.t,'aq',aq,'aW',aW);
  
  LYtnew = meqpost(L,LYtnew,TpDg,ITpDg,LYt.ag,...
    LYt.Fx,FA,FB,rA,zA,dr2FA,dz2FA,drzFA,rB,zB,lB,lX,rX,zX,FX,...
    LYt.rBt,LYt.Ia,LYt.Iu,LYt.Iy,Opy);
  
  % check p',TT' profile fits
  if ( norm(LYt.PpQ-LYtnew.PpQ  ) / (norm(LYtnew.PpQ ) + eps) ) > 1e-6
    warning(warnid,'inaccurate fit of PpQ, basis functions may not accurately represent equilibrium')
  end
  if ( norm(LYt.TTpQ-LYtnew.TTpQ) / (norm(LYtnew.TTpQ) + eps) ) > 1e-6
    warning(warnid,'inaccurate fit of TTpQ, basis functions may not accurately represent equilibrium')
  end
  
  % add eventual missing fields
  for field = fieldnames(LYt)'
    if ~isfield(LYtnew,field{:})
      LYtnew.(field{:}) = LYt.(field{:});
    end
  end

  % Fix Bm,Ff terms due to dz shift in liu
  if isfield(LY,'dz') && all(LY.dz~=0)
    LYtnew.Bm = LYtnew.Bm + LYtnew.dz*L.G.dzBmx(:,L.lxy)*LYtnew.Iy(:);
    LYtnew.Ff = LYtnew.Ff + LYtnew.dz*L.G.dzMfx(:,L.lxy)*LYtnew.Iy(:);
  end

  % Update aq, aW
  aq = LYtnew.aq; aW = LYtnew.aW;
  
  LYnews(kt) = LYtnew; %#ok<AGROW> % store in array of struct
end

% pack
LYnew = meqlpack(LYnews,{'ppQg','TTpQg','FW'});

end


