# Build layout
# ------------
# Auxiliary files go to output/, the two PDFs stay beside the sources, so the
# working directory holds only sources plus Manuscript.pdf and SI.pdf.
$aux_dir = 'output';
$out_dir = '.';

# SyncTeX, for ctrl/cmd-click between the PDF viewer and the source. latexmk
# does not pass -synctex=1 on its own, so it has to be requested here.
$pdflatex = 'pdflatex -synctex=1 %O %S';

# xr cross-references into the SI
# ------------------------------
# Manuscript.tex has \myexternaldocument{SI}, which prints the SI's section
# numbers (Section S2, S3, ...) by reading SI.aux. It never compiles the SI
# itself, and nothing else does either: Overleaf builds only the main document.
# Without the rule below those references come out as "??".
#
# The stock version of this rule could not be reconciled with $aux_dir: it ran
# a bare `latex SI`, which drops SI.aux in the working directory, while latexmk
# expects the rule's destination inside the aux directory -- hence the old
# "return code -1" and exit 12. Passing -output-directory puts the file exactly
# where latexmk looks for it, and the two settings then coexist.
#
# latexmk still insists on seeing the rule's destination at ./SI.aux, whatever
# $aux_dir says, and reports "return code -1" (exit 12) without it even though
# every output file is correct. So the pass writes into output/ and the .aux
# alone is lifted beside the sources. That one file is also what xr reads,
# since kpathsea searches the working directory and not output/. It is the
# only build artifact left in the source tree, and .gitignore covers it.
#
# One pdflatex pass, not the customary three plus biber: the manuscript refers
# to the SI only with \ref, which needs section numbers, and those are settled
# after a single pass -- no page numbers, no citations are taken across.
# -draftmode suppresses the PDF, so this does not spend time writing the SI's
# ~9.5 MB of figures on every manuscript compile, which matters against
# Overleaf's compile timeout.
#
# The guard keeps the rule from recursing when the SI is itself the root
# document, in which case latexmk is already building it properly.
add_cus_dep('tex', 'aux', 0, 'makeexternaldocument');
sub makeexternaldocument {
    return if $root_filename eq $_[0];
    system("pdflatex -draftmode -interaction=nonstopmode "
           . "-output-directory=$aux_dir \"$_[0]\"");
    system("cp -f \"$aux_dir/$_[0].aux\" \"$_[0].aux\"");
}
