function [pdffile,count] = compilepdf(inputfile,varargin)
% COMPILEPDF  [Not a public function] Publish latex file to PDF.
%
% Backend IRIS function.
% No help provided.

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

opt = passvalopt('latex.compilepdf',varargin{:});

%**************************************************************************

thisdir = cd();

config = irisget();
if isempty(config.pdflatexpath)
    error('iris:latex',...
        'PDFLATEX path unknown. Cannot compile PDF files.');
end

[inputpath,inputtitle] = fileparts(inputfile);

if ~isempty(inputpath)
    cd(inputpath);
    inputpath = cd();
    cd(thisdir);
else
    inputpath = thisdir;
end

command = ['"',config.pdflatexpath,'" --halt-on-error "',inputtitle,'"'];

cd(inputpath);
count = 0;
rerun = true;
status = 0;
while (status ~= 0 || rerun) && count <= opt.maxrerun
    [status,result] = system(command);
    rerun = ~isempty(strfind(result,'Rerun')) ...
        || ~isempty(strfind(result,'undefined references')) ...
        || ~isempty(regexp(result,'No file \w+\.toc','once'));
    count = count + 1;
end

if opt.display || status ~= 0
    disp(result);
end

pdffile = fullfile(inputpath,[inputtitle,'.pdf']);
fprintf('\n');

cd(thisdir);

end
