function liuanasrv(shot,~,analysis)
%LIUANASRV  Called by ANASRV to compute and write in RESULTS tree
% LIUANASRV(SHOT,VERSION,ANALYSIS)
%
% ANALYSIS can currently be either:
%  - THOMSON: LIUQE and PSITBX run at Thomson times only.
%  - FAST:    LIUQE and PSITBX run with millisecond time resolution and at
%      Thomson times. [default]
%  - MAX:    LIUQE run for the whole magnetics time based, PSITBX as in
%      FAST mode.
%
% The PSI and J_TOR nodes are stored only at PSITBX times.
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

if nargin < 3, analysis = 'fast'; end
analysis = validatestring(lower(analysis),{'thomson','fast','max'},mfilename,'analysis',3);

switch lower(analysis)
 case 'thomson'
  type_psi  = 'thomson';
  type_fast = 'none';
 case 'fast'
  type_psi  = 'mixed';
  type_fast = 'none';
 case 'max'
  type_psi  = 'mixed';
  type_fast = 'magnetics';
end

% Run comment
comment = sprintf('Standard LIUQE.M run with TYPE_PSI=%s and TYPE_FAST=%s',type_psi,type_fast);

% Handle extra times
psi_extra  = [];
fast_extra = [];
if ~strcmpi(analysis,'thomson')
 meqmdsopen(shot,'results');
 psi_extra  = mdsvalue('if_error(\TOP.EQUIL_1.TIME_REQUEST:PSI_EXTRA,*)').';
 fast_extra = mdsvalue('if_error(\TOP.EQUIL_1.TIME_REQUEST:FAST_EXTRA,*)').';
end

% Assemble time arrays
[time_psi,time_fast] = liuqe_times(shot,type_psi,type_fast,psi_extra,fast_extra);

[L,LX,LY] = liuqe(shot,time_fast);            % Note LX.t has same number of elements as time_fast
conv = ismember(LX.t,LY.t);                   % Has LIUQE converged for each time?
has_psi = ismember(time_fast(conv),time_psi); % Does this converged slice require psitbx results?
it_psi = find(has_psi);                       % List of converged slices requiring psitbx results
% List of node dependencies
dep = {'\MAGNETICS::TOP.MEASUREMENTS.*:*:*',...
       '\RESULTS::DML:BO%%%.PARAM:*',...
       '\RESULTS::DML:CK%%%:*',...
       '\RESULTS::TOP.EQUIL_1.PARAMETERS:*',...
       '\RESULTS::TOP.EQUIL_1.TIME_REQUEST:*',...
      };
if ~L.P.idml
 dep(startsWith(dep,'\RESULTS::DML')) = [];
end
% Run psiwtcv first so that all the writing comes after the PSITBX comp.
psiwtcv(shot,'RESULTS','\TOP.EQUIL_1.RESULTS',L,LY,it_psi,dep)
meqwtcv(shot,'RESULTS','\TOP.EQUIL_1.RESULTS',L,LY,it_psi,dep)
liuwtcv(shot,'RESULTS','\TOP.EQUIL_1.RESULTS',L,LY,it_psi,dep)
codwtcv(shot,'RESULTS','\TOP.EQUIL_1.CODE','LIUQE.M',comment);
if L.P.idml, dmlbo(shot,'BOSIG'), end