%CREATEF  CREATE(ITER) Locates equilibrium file
% [FILE,EQUIL,CNL] = CREATEF(EQUIL,CNL) returns the FILE path, the EQUILibrium
% numbers and a flag marking CNL equilibria. Without input arguments, it returns
% all equilibria. If CNL is not specified, it may return both CL and CNL.
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

function [file,equil,cnl] = createf(equilin,cnlin)

if nargin >= 1
  if iscell(equilin), equilin = equilin{1}; end
  
  if ischar(equilin)
    file  = {equilin};
    try
      if numel(cnlin)>0
        cnl = cnlin;
      else
        t     = load(equilin,'time');
        cnl   = t.time;
      end
      equil = 0;    % equilibrium number
    catch
      cnl   = NaN;  % To be updated
      equil = NaN;
    end
    
    return
  end
end

switch nargin
  case 0
    datadir = '/Lac8_D/CREATE0883/equil';
    assert(~~exist(datadir,'dir'),'CREATEF:DirNotFound','Directory %s does not exist',datadir);
    systemcmd = ['find ',datadir,' -regextype grep -regex  ".*/Equil_.*[0-9]\{5\}\(d[0-9]\)\?_C[N]\?L4E[2]\?.mat"'];
    [~,file] = system(systemcmd);
    assert(~contains(file,'No such file or directory'),...
      'CREATEF:NoFilesFound','find command did not find anything;\n %s\n',systemcmd);
    
    file = split(file(1:end-1),newline);
    et = regexp(file,'.*Equil_.*([0-9]{5})d?([0-9]?)_C([N]?)L4E[2]?.mat','tokens');
    n = length(et);
    [equil,cnl] = deal(zeros(n,1));
    for k = 1:n
      equil(k) = str2double([et{k}{1}{1:2}]);
      cnl    (k) =     strcmp(et{k}{1}{3},'N');
    end
    [~,k] = sortrows([equil cnl]);
  case 1
    [file,equil,cnl] = createf;
    [~,k] = intersect(equil,equilin(:));
  case 2
    if length(cnlin) == 1; cnlin = repmat(cnlin,length(equilin),1); end
    [file,equil,cnl] = createf;
    [~,k] = intersect([equil cnl],[equilin(:) cnlin(:)],'rows');
end
equil = equil(k);
cnl   = cnl  (k);
file  = file (k);
end