function LY = meqsk(LY,k,LX)
% Substitute LY data at index k by LX slice(s)
% LX must have number of times equal to indices
% k can be logical or numerical index
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

if islogical(k); k=find(k); end
assert(numel(LX.t)==numel(k),'number of slices in LXt (%d) does not match indices in k (%d)',numel(LX.t),numel(k))

for ik=1:numel(k)
  
  for ifield = fieldnames(LX)'
    myfield = ifield{:};
    switch myfield
      case {'shot','tokamak'}
        % do nothing
      case {'Fx','Iy','Opy'}
        LY.(myfield)(:,:,k(ik)) = LX.(myfield)(:,:,ik);
        % handle these directly
      otherwise
        
        LXfield = LX.(myfield);
        
        if ~isfield(LY,myfield)
          assert(k==1,'can not assign non-existing field other than at first index')
          LY.(myfield) = LXfield;
        else
          LYfield = LY.(myfield); % base size decision on target field
          
          if isempty(LYfield)
            LY.(myfield) = LXfield;
          elseif ismatrix(LYfield)
            n = numel(LXfield(:,ik)); m = size(LY.(myfield),1);
            if n>m, LY.(myfield) = [LY.(myfield);nan(n-m,size(LY.(myfield),2))]; end % extend original LY field with nans
            LY.(myfield)(:,k(ik)) = [LXfield(:,ik);nan(m-n,1)]; % pad with NaNs
          elseif ndims(LYfield)== 3
            LY.(myfield)(:,:,k(ik)) = LXfield(:,:,ik);
          else
            error('don''t know what to do');
          end
        end
    end
  end
end
