function publish_documentation
% Function to publish all MEQ documentation
%
% [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.


thisdir = fileparts(mfilename('fullpath'));
meqdir = fileparts(thisdir);
targetDir = fullfile(meqdir,'html');
mydir = pwd;

cleanup = onCleanup(@()myCleanupFun(mydir));

if ~exist(targetDir,'dir')
  mkdir(targetDir);
end

opts = struct(...
  'format','html',...
  'outputDir',targetDir);

%%
publish_main(meqdir,opts)

%%
publish_doc(thisdir,opts)

%%
addpath(meqdir);
addpath(fullfile(meqdir,'genlib'));

tutorialdir = fullfile(thisdir,'tutorials');
publish_tutorials(tutorialdir,opts)

end

function publish_main(contentsdir,opts)
cd(contentsdir);
publish('Contents.m',opts);
end

function publish_doc(docdir,opts)
cd(docdir);
publish('Getting_started.m',opts);
publish('MEQ_toolbox.m',opts);
end

function publish_tutorials(tutorialdir,opts)
% add paths to run scripts
files = dir(fullfile(tutorialdir,'*.m'));
opts.format = 'html';
opts.showCode = true;
opts.outputDir = fullfile(opts.outputDir,'Tutorials');

% to tutorial dir
cd(tutorialdir)

excludedfiles = {mfilename,'open_as_livescript'}; % files excluded from publishing

for ifile = 1:numel(files)
  myfile = files(ifile);
  if ~contains(myfile.name,excludedfiles)
    % move shadowing mlx file out of the way
    mlxname = strrep(myfile.name,'.m','.mlx');
    if exist(mlxname,'file')
      tmpfile = fullfile(myfile.folder,['tmp_',mlxname]);
      movefile(mlxname,tmpfile);
      cleanupObj = onCleanup(@() movefile(tmpfile,mlxname));
    end
    % publish this file to html
    fprintf('publishing %s\n',myfile.name)
    outfile = publish(myfile.name,opts);
    fprintf('saved to: %s\n',outfile);
  end
end
end

function myCleanupFun(olddir)
% go back to previous dir
cd(olddir)
% close open windows
close all
end