function LY = liutsim(L,LX,varargin)
%LIUTSIM  Equivalent function to liut.m to run liutsim.slx from existing L,LX
% liutsim.slx has 2 referenced subsystems;
% liuxslx.slx outputs the LX bus object (from LX data in its data dictionary)
% liutslx.slx is the time stepper that receives LX and outputs LY.
% Data dictionaries are automatically created, linked and deleted as necessary
% see also LIUSIMC
% Custom parameters:
% .bslvdprec    flag for real precision in block solver
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

for k = 1:2:length(varargin)
  L.P.(varargin{k}) = varargin{k+1};
end

[L] = liusimc(L,LX); % consolidate for Simulink use

liusmodel = 'liusim';

%% Simulate model
out = sim(liusmodel);

%% Convert timeseries results to LY
LY = ts2meq(L,out.LY);
LY.t = LX.t; % Restore original time

%% FX,rX,zX clipping and set NaN when not an X point
for xX = {'rX','zX','FX'}
  LY.(xX{:}) = LY.(xX{:})(1:max(LY.nX),:);
  for it=1:numel(LY.t)
    LY.(xX{:})((LY.nX(it)+1):end,it) = NaN;
  end
end

%% Isconverged flag
LY.isconverged = ~LY.rst;

%% Close without saving
close_system(liusmodel,0);
close_system('liutslx.slx',0);
close_system('liuxslx.slx',0);

%% Plot for debug
if L.P.debug
  for it = 1:numel(LY.t)
    meqplott(L,meqxk(LY,it));
    drawnow;
  end
end
end