%MEQXK  extracts samples from LX/LY structure
% LXK = MEQXK(LX,K,fields) extracts the K (logical or index array) samples from
% LX. K='last' selects last index.
% Optional parameter 'fields': cell array of fields to extract
% (default: all).
% 
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
function LXk = meqxk(LX,k,fields)

if islogical(k), k=find(k); end
if ischar(k) && strcmp(k,'last'), k = numel(LX.t); end
assert(all(k <= numel(LX.t)),...
  'requested index k=%d exceeds number of elements in LX.t (%d)',k,numel(LX.t))
assert(all(k>0),'can not request k<1');

if nargin==2
  fields = fieldnames(LX)';
else
  assert(iscell(fields),'fields must be a cell')
  if ~isrow(fields), fields=fields'; end
end

if islogical(k), k = find(k); end
for n = fields
  switch n{1}
    case 'shot'
      LXk.shot = LX.shot(min(k,numel(LX.shot))); % shot may be scalar or vector
    case 'tokamak'
      LXk.tokamak = LX.tokamak;
    otherwise
      datn = LX.(n{1});
      
      switch n{1}
        case {'Fx','Iy','Opy'}
         % handle special case when nry or nrx = nt
         if ndims(datn)==3, sellast = true; else, sellast = false; end
        otherwise
         sellast = (size(datn,ndims(datn))==numel(LX.t));
      end
          
      if sellast
      
        % Works for any rank
        siz = size(datn);
        datn = reshape(datn,[],siz(end));
        LXk.(n{1}) = reshape(datn(:,k),[siz(1:end-1),numel(k)]);
      else
        LXk.(n{1}) = datn;% else pass directly
      end
  end
end

