% Plain document class

\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{plain}[2026-08-20 Plain document]
% Coded by Paul Tol

% Header options:
% * largeheader - big;
% * smallheader - small with project logo;
% * compactheader (default) - smaller with project name;
% * largefirstheader - only first page large.
\DeclareOption{largeheader}{
  \def\@firstheadertype{largeheader}
  \def\@headertype{largeheader}
}
\DeclareOption{smallheader}{
  \def\@firstheadertype{logoheader}
  \def\@headertype{smallheader}
}
\DeclareOption{compactheader}{
  \def\@firstheadertype{logoheader}
  \def\@headertype{compactheader}
}
\DeclareOption{largefirstheader}{
  \def\@firstheadertype{largeheader}
}

% Front page options:
% * largetitle - use full width for title;
% * nosigs - no signature boxes or CCB data.
\newif\iflargetitle\largetitlefalse
\DeclareOption{largetitle}{\largetitletrue}
\newif\ifsigs\sigstrue
\DeclareOption{nosigs}{\sigsfalse}

% Math typeface option:
% * mathastext - use the same typeface for math as for text.
\newif\ifmathastext\mathastextfalse
\DeclareOption{mathastext}{\mathastexttrue}

% Switch monospace typeface from DejaVu Sans Mono to Space Mono, if installed.
\newif\ifspacemono\spacemonofalse
\DeclareOption{spacemono}{\spacemonotrue}

\DeclareOption*{\ClassWarning{plain}{Unknown option '\CurrentOption'}}
\ExecuteOptions{compactheader}
\ProcessOptions\relax
\ifspacemono
  \IfFileExists{spacemono.sty}{}{%
    \ClassWarningNoLine{plain}{Typeface Space Mono not installed, using DejaVu Sans Mono}
    \spacemonofalse
  }
\fi
\LoadClass{article}

\RequirePackage[table]{xcolor}
\definecolor{sapphire}{RGB}{34, 85, 170}

% Bibliography
\RequirePackage[UKenglish]{babel}
\RequirePackage{csquotes} % gets rid of recommendation warning from biblatex
% backend=biber is better if you have many references, want Unicode support or want to sort in Danish
% backend=bibtex can give an error that \ifprefchar is not defined, when encountering a "van der" name
\newcommand{\ifprefchar}{\ifpunctmark{'}}
\RequirePackage[backend=biber, sorting=none, defernumbers=true]{biblatex}
\DeclareBibliographyCategory{AD}
\defbibheading{AD}{\section*{Applicable documents}\addcontentsline{toc}{section}{Applicable documents}}
\DeclareBibliographyCategory{RD}
\defbibheading{RD}{\section*{Reference documents}\addcontentsline{toc}{section}{Reference documents}}
\DefineBibliographyStrings{english}{version = {issue}}
% remove ordinal suffix from day
\DefineBibliographyExtras{british}{%
  \protected\def\mkbibdatelong#1#2#3{%
    \iffieldundef{#3}
      {}
      {\stripzeros{\thefield{#3}}%
       \iffieldundef{#2}{}{\nobreakspace}}%
    \iffieldundef{#2}
      {}
      {\mkbibmonth{\thefield{#2}}%
       \iffieldundef{#1}{}{\space}}%
    \iffieldbibstring{#1}
      {\bibstring{\thefield{#1}}}
      {\dateeraprintpre{#1}\stripzeros{\thefield{#1}}}}%
}

% DVI/PDF dependent packages
% - compile your tex file with "latex" to create a DVI file
% - compile your tex file with "pdflatex" to create a PDF file
% - compile the bibliography with "biber" in both cases
\RequirePackage{ifpdf}
\ifpdf
 \pdfcompresslevel=9
 \RequirePackage[pdftex, a4paper, hmargin=2cm]{geometry}
 \RequirePackage[pdftex]{graphicx}
 \DeclareGraphicsExtensions{.pdf, .jpg, .png, .mps}
 \RequirePackage[pdftex, pdfa, unicode]{hyperref}
 \RequirePackage[pdftex]{pict2e}
\else
 \RequirePackage[dvips, a4paper, hmargin=2cm]{geometry}
 \RequirePackage[dvips]{graphicx}
 \DeclareGraphicsExtensions{.eps, .ps}
 \RequirePackage[dvips, pdfa, unicode]{hyperref}
 \RequirePackage[dvips]{pict2e}
\fi
\RequirePackage{hyperxmp}

\RequirePackage{fancyhdr}
\setlength{\topmargin}{-0.5in}
\setlength{\headsep}{20pt}
\setlength{\footskip}{1cm}
\setlength{\marginparsep}{10pt}
\setlength{\marginparwidth}{42pt}
% headheight and textheight are set in header definitions later
% temporary values given here are valid before \maketitle is called
\setlength{\headheight}{70pt}
\setlength{\textheight}{\dimexpr\paperheight-1in-\voffset-\topmargin-\headheight-\headsep-2cm}

\hypersetup{
  pdfstartview={FitH},
  linktocpage=true,
  colorlinks=true,
  anchorcolor=black,
  linkcolor=sapphire,
  citecolor=sapphire,
  filecolor=sapphire,
  urlcolor=sapphire,
  runcolor=sapphire,
  menucolor=sapphire
}

\RequirePackage[Export]{adjustbox} % \includegraphics can use all \adjustbox keys


% Fonts and titles

\RequirePackage[T1]{fontenc}
% DejaVu Sans is an extended version of Vera Sans, which resembles Verdana.
\RequirePackage{dejavu}
\ifmathastext
  \RequirePackage{arevmath}
  \DeclareMathAlphabet{\mathrm}{\encodingdefault}{\sfdefault}{m}{n}
  % Avoiding warnings about bold mathematical symbols
  \SetSymbolFont{symbols}{bold}{OMS}{zavm}{m}{n}
  \RequirePackage{anyfontsize}
  \RequirePackage{amsmath}
  % redefining operators with I, a or u for the right typeface
  \let\arcsin\relax \DeclareMathOperator{\arcsin}{\mathrm{arcsin}}
  \let\arccos\relax \DeclareMathOperator{\arccos}{\mathrm{arccos}}
  \let\arctan\relax \DeclareMathOperator{\arctan}{\mathrm{arctan}}
  \let\arg\relax \DeclareMathOperator{\arg}{\mathrm{arg}}
  \let\tan\relax \DeclareMathOperator{\tan}{\mathrm{tan}}
  \let\tanh\relax \DeclareMathOperator{\tanh}{\mathrm{tanh}}
  \let\max\relax \DeclareMathOperator*{\max}{\mathrm{max}}
\else
  % The Erewhon package provides Utopia text and Fourier mathematical and
  % Greek symbols with some tweaks and additions.
  \RequirePackage[scaled=1.185, space]{erewhon}
  \RequirePackage[scaled=1.185, erewhon, vvarbb]{newtxmath} % loads amsmath as well
\fi
\renewcommand*\familydefault{\sfdefault}
\RequirePackage{bm}

% justify typewriter font
\newcommand{\@fixfontdimens}{%
  % \fontdimen2\font is standard width of a space
  \fontdimen3\font=0.5\fontdimen2\font % interword stretch
  \fontdimen4\font=0.2\fontdimen2\font % interword shrink
}
\ifspacemono
  % not found on CTAN and some symbols are not available
  % https://github.com/AnymouseProphet/SpaceMono-LaTeX
  \RequirePackage{spacemono}
  \DeclareFontFamily{T1}{spacemono}{}
  \DeclareFontShape{T1}{spacemono}{b}{n}{<->ecspacemonob}{\@fixfontdimens}
  \DeclareFontShape{T1}{spacemono}{b}{it}{<->ecspacemonobi}{\@fixfontdimens}
  \DeclareFontShape{T1}{spacemono}{bx}{n}{<->ssub * spacemono/b/n}{}
  \DeclareFontShape{T1}{spacemono}{bx}{it}{<->ssub * spacemono/b/it}{}
  \DeclareFontShape{T1}{spacemono}{m}{n}{<->ecspacemono}{\@fixfontdimens}
  \DeclareFontShape{T1}{spacemono}{m}{it}{<->ecspacemonoi}{\@fixfontdimens}
  \renewcommand*\ttdefault{spacemono}
\else
  \expandafter\ifx\csname DejaVuSansMono@scale\endcsname\relax
    \let\DejaVuSansMono@@scale\@empty
  \else
    \edef\DejaVuSansMono@@scale{s*[\csname DejaVuSansMono@scale\endcsname]}%
  \fi
  \DeclareFontFamily{T1}{DejaVuSansMono-TLF}{}
  \DeclareFontShape{T1}{DejaVuSansMono-TLF}{b}{it}%
    {<->\DejaVuSansMono@@scale DejaVuSansMono-BoldOblique-tlf-t1}{\@fixfontdimens}
  \DeclareFontShape{T1}{DejaVuSansMono-TLF}{b}{n}%
    {<->\DejaVuSansMono@@scale DejaVuSansMono-Bold-tlf-t1}{\@fixfontdimens}
  \DeclareFontShape{T1}{DejaVuSansMono-TLF}{m}{it}%
    {<->\DejaVuSansMono@@scale DejaVuSansMono-Oblique-tlf-t1}{\@fixfontdimens}
  \DeclareFontShape{T1}{DejaVuSansMono-TLF}{m}{n}%
    {<->\DejaVuSansMono@@scale DejaVuSansMono-tlf-t1}{\@fixfontdimens}
  \DeclareFontShape{T1}{DejaVuSansMono-TLF}{m}{sl}{<->ssub * DejaVuSansMono-TLF/m/it}{}
  \DeclareFontShape{T1}{DejaVuSansMono-TLF}{b}{sl}{<->ssub * DejaVuSansMono-TLF/b/it}{}
  \DeclareFontShape{T1}{DejaVuSansMono-TLF}{bx}{sl}{<->ssub * DejaVuSansMono-TLF/b/it}{}
  \DeclareFontShape{T1}{DejaVuSansMono-TLF}{bx}{it}{<->ssub * DejaVuSansMono-TLF/b/it}{}
  \DeclareFontShape{T1}{DejaVuSansMono-TLF}{bx}{n}{<->ssub * DejaVuSansMono-TLF/b/n}{}
  \renewcommand*\ttdefault{DejaVuSansMono-TLF}
\fi
%\renewcommand*\familydefault{\ttdefault} % all text in typewriter style

% Font sizes are roughly (25/3)*\sqrt{6/5}^x with
% x=-8,-4,-2,-1,0,2,4,6,8,10 and the \baselineskip is 1.6 times larger.
\renewcommand{\tiny}{\fontsize{4}{6.4}\selectfont}
\renewcommand{\scriptsize}{\fontsize{5.8}{9.3}\selectfont}
\renewcommand{\footnotesize}{\fontsize{6.9}{11.1}\selectfont}
\renewcommand{\small}{\fontsize{7.6}{12.2}\selectfont}
\renewcommand{\normalsize}{\fontsize{8.6}{13.5}\selectfont}
\renewcommand{\large}{\fontsize{10}{16}\selectfont}
\renewcommand{\Large}{\fontsize{12}{19.2}\selectfont}
\renewcommand{\LARGE}{\fontsize{14.4}{23.1}\selectfont}
\renewcommand{\huge}{\fontsize{17.28}{27.7}\selectfont}
\renewcommand{\Huge}{\fontsize{20.74}{33.2}\selectfont}

% DejaVu Sans does not have small capitals, but \fakesc is an approximate replacement for \textsc.
\def\fakesc{\bgroup\obeyspaces\@fakesc}
\def\@fakesc#1{\@@fakesc #1\relax\relax\egroup}
\def\@@fakesc#1{%
  \ifx\relax#1\else \ifcat#1\@sptoken{} \expandafter\expandafter\expandafter\@@fakesc\else
  \ifnum`#1=\uccode`#1 {\normalsize #1}\else {\fontsize{6.45}{10.3}\selectfont \uppercase{#1}}\fi%
  \expandafter\expandafter\expandafter\@@fakesc\expandafter\fi\fi%
}

\RequirePackage{titlesec}
\titleformat*{\section}{\ttfamily\Large\bfseries}
\titleformat*{\subsection}{\ttfamily\large\bfseries}
\titleformat*{\subsubsection}{\ttfamily\large\mdseries\itshape}
% Use paragraph as subsubsubsection and subparagraph as paragraph
\titleformat{\paragraph}{\ttfamily\large\mdseries}{\theparagraph}{1em}{}
\titleformat*{\subparagraph}{\ttfamily\normalsize\mdseries\itshape}
\titlespacing*{\paragraph}{0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex}
\titlespacing*{\subparagraph}{0pt}{3.25ex plus 1ex minus .2ex}{1em}
\setcounter{secnumdepth}{4}
\setcounter{tocdepth}{4}
\counterwithin{figure}{section}
\counterwithin{table}{section}
\counterwithin{equation}{section}


% Additional style settings

\RequirePackage{ragged2e}
%\RaggedRight % left justified with hyphenation
\justifying
\frenchspacing
\setlength{\emergencystretch}{2em} % stretch spaces if line doesn't fit otherwise

\RequirePackage[perpage, symbol*, hang, bottom, stable]{footmisc}
\setlength{\footnotemargin}{0pt}
\RequirePackage{booktabs}
\RequirePackage[font=small]{subcaption}
\RequirePackage[section]{placeins} % command \FloatBarrier automatically added before sections

\setlength{\parindent}{2pc}
\setlength{\belowcaptionskip}{2pt}
\setlength{\abovecaptionskip}{2pt}

\RequirePackage{enumitem}
\setitemize{nolistsep,leftmargin=*}
\setenumerate{nolistsep,leftmargin=*}

% Alter some LaTeX defaults for better treatment of figures:
% See p.105 of "TeX Unbound" for suggested values.
% See pp. 199-200 of Lamport's "LaTeX" book for details.
% General parameters, for ALL pages:
\renewcommand{\topfraction}{0.9} % max fraction of floats at top
\renewcommand{\bottomfraction}{0.8} % max fraction of floats at bottom
% Parameters for TEXT pages (not float pages):
\setcounter{topnumber}{2}
\setcounter{bottomnumber}{2}
\setcounter{totalnumber}{4}  % 2 may work better
\setcounter{dbltopnumber}{2} % for 2-column pages
\renewcommand{\dbltopfraction}{0.9} % fit big float above 2-col. text
\renewcommand{\textfraction}{0.07} % allow minimal text with figs
% Parameters for FLOAT pages (not text pages):
\renewcommand{\floatpagefraction}{0.7} % require fuller float pages
% N.B.: floatpagefraction must be less than topfraction
\renewcommand{\dblfloatpagefraction}{0.7} % require fuller float pages


% Header parameters

% Project name.
\newcommand{\project}[1]{\def\@project{#1}}
\project{}
% File name of project logo including extension.
% If not found, text of \project is used.
\newcommand{\projectlogo}[1]{\def\@projectlogo{\detokenize{#1}}}
\projectlogo{}
\newcommand{\documenttype}[1]{\def\@documenttype{#1}}
\documenttype{}
\newcommand{\documentnumber}[1]{\def\@documentnumber{#1}}
\documentnumber{} % official document number
\newcommand{\institutenumber}[1]{\def\@institutenumber{#1}}
\institutenumber{} % extra document number for internal use, never used
\newcommand{\issue}[1]{\def\@issue{#1}}
\issue{}
% The Level and Class form a classification:
% Level 1: issued by Customer ('them').
% Level 2: issued by Contractor ('us'), sent to Customer for approval
%          (Class A) prior to implementation. After approval, these
%          documents are contractually binding.
% Level 3: any other issued by Contractor, sent to Customer either for
%          review (Class R, identified discrepancies shall be corrected
%          prior to implementation) or for information (Class I).
% Level -: issued by Contractor, not sent to Customer, i.e. internal
%          documents for information (Class I).
% Class A, R or I as described above.
% If a project does not use it, leave level and class empty.
\newcommand{\level}[1]{\def\@level{#1}}
\level{} % one of: 1, 2, 3, -
\newcommand{\class}[1]{\def\@class{#1}}
\class{} % one of: A, R, I
% The category indicates the authorization level of the document:
% 1. Document to be authorized by client, first authorization by PM.
% 2. End-to-end of system level documents; authorization by PM.
% 3. Document concerning units; authorization by the Unit Manager.
% 4. Document concerning assemblages/sub-assemblages; authorization by the (sub) assembly manager.
% If a project does not use it, leave category empty.
\newcommand{\category}[1]{\def\@category{#1}}
\category{} % one of: 1, 2, 3, 4, N/A


% Title page parameters

% redefine \title command as \title[Short title]{Title}
\renewcommand*{\title}[2][]{\gdef\@shorttitle{#1}\gdef\@title{#2}}
% \title{Title} is made equivalent to \title[Title]{Title}
\edef\title{\@nx\@dblarg\@xp\@nx\csname\string\title\endcsname}

\title{}
\author{}
\newcommand{\checkedby}[1]{\def\@checkedby{#1}}
\checkedby{}
\newcommand{\agreedby}[1]{\def\@agreedby{#1}}
\agreedby{}
\newcommand{\authorisedby}[1]{\def\@authorisedby{#1}}
\authorisedby{}
\newcommand{\pdfauthor}[1]{\def\@authorinproperties{#1}}
\pdfauthor{\@author} % for PDF properties, not title page, default the same as \author
% Optional entries for a configuration item (CI)
\newcommand{\cinumber}[1]{\def\@cinumber{#1}}
\cinumber{} % often a 4-digit number
\newcommand{\model}[1]{\def\@model{#1}}
\model{} % one of: DM, EM, QM, FM, FS (or similar)
\newcommand{\baseline}[1]{\def\@baseline{#1}}
\baseline{} % one of: As Required, As Planned, As Designed, As Built, As Verified
\newcommand{\workpackage}[1]{\def\@workpackage{#1}}
\workpackage{}


% Definitions needed for header

\RequirePackage{lastpage}
\RequirePackage{tabularx}
\RequirePackage{tabularray}
\UseTblrLibrary{booktabs, varwidth}

\RequirePackage[calc]{datetime2}
\DTMnewdatestyle{mydateformat}{%
  \renewcommand{\DTMdisplaydate}[4]{%
    \number##3\nobreakspace%
    \DTMmonthname{##2}\space%
    \number##1%
  }%
  \renewcommand{\DTMDisplaydate}{\DTMdisplaydate}%
}
\AtBeginDocument{\DTMsetdatestyle{mydateformat}}

% squeeze text to a full line but don't stretch if the text is too short
\newcommand{\squeeze}[1]{%
  \if\relax#1\relax\else
    \resizebox{\ifdim\width>0.995\linewidth0.995\linewidth\else\width\fi}{!}{#1}%
  \fi
}

\RequirePackage[immediate]{silence}
\newlength{\headerboxsize}
\newcommand{\@head}[2][]{
  \WarningFilter[temp]{latex}{Reference `LastPage'}
  \settoheight{\headerboxsize}{\parbox[b][][c]{\textwidth}{#2}}
  \global\headerboxsize=\headerboxsize
  \fancyhead[#1]{#2}
  \DeactivateWarningFilters[temp]
}


% Large-header construction

% content of three columns in largeheader
\def\@dockeys{%
  \if\relax\@documentnumber\relax\else Doc.~no. \\ \fi
  \if\relax\@institutenumber\relax\else Inst.~no. \\ \fi
  \if\relax\@issue\relax\else Issue \\ \fi
  \if\relax\@level\relax\else Level \\ \fi
  \if\relax\@class\relax\else Class \\ \fi
  \if\relax\@category\relax\else Cat. \\ \fi
  Date \\
  Page%
}
\def\@docvals{%
  \if\relax\@documentnumber\relax\else \@documentnumber \\ \fi
  \if\relax\@institutenumber\relax\else \@institutenumber \\ \fi
  \if\relax\@issue\relax\else \@issue \\ \fi
  \if\relax\@level\relax\else \@level \\ \fi
  \if\relax\@class\relax\else \@class \\ \fi
  \if\relax\@category\relax\else \@category \\ \fi
  \@date \\
  \thepage\ of \pageref*{LastPage}%
}
\def\@doccolons{%
  \if\relax\@documentnumber\relax\else : \\ \fi
  \if\relax\@institutenumber\relax\else : \\ \fi
  \if\relax\@issue\relax\else : \\ \fi
  \if\relax\@level\relax\else : \\ \fi
  \if\relax\@class\relax\else : \\ \fi
  \if\relax\@category\relax\else : \\ \fi
  : \\
  :%
}

\newcounter{doclines}
\newcommand{\@headerstretchfactor}{1}
\fancypagestyle{largeheader}{%
  \renewcommand{\headrulewidth}{0pt}
  \setcounter{doclines}{2}
  \ifthenelse{\equal{\@documentnumber}{}}{}{\stepcounter{doclines}}
  \ifthenelse{\equal{\@institutenumber}{}}{}{\stepcounter{doclines}}
  \ifthenelse{\equal{\@issue}{}}{}{\stepcounter{doclines}}
  \ifthenelse{\equal{\@level}{}}{}{\stepcounter{doclines}}
  \ifthenelse{\equal{\@class}{}}{}{\stepcounter{doclines}}
  \ifthenelse{\equal{\@category}{}}{}{\stepcounter{doclines}}
  \ifnum \value{doclines}>6\relax
    \renewcommand{\@headerstretchfactor}{0.75}
  \else
    \ifnum \value{doclines}>4\relax
      \renewcommand{\@headerstretchfactor}{0.85}
    \fi
  \fi
  \fancyhf{}
  \@head[L]{%
    \begingroup
    \renewcommand{\baselinestretch}{\@headerstretchfactor}\selectfont
    \begin{tblr}[B]{%
        colspec={|X[c]|X[-1,rightsep=0pt]X[-1,colsep=0pt]X[-1]|},
        measure=vbox,
        abovesep=4pt
      }
      \hline
      \SetCell[r=2]{m} \Large\bf\texttt{\MakeUppercase{\@documenttype}} &
      \SetCell[r=2]{m} \bf\texttt{\@dockeys} &
      \SetCell[r=2]{m} \bf\texttt{\@doccolons} &
      \SetCell[r=2]{m} \texttt{\@docvals} \\
      \\
      \hline
    \end{tblr}%
    \endgroup
  }
  \setlength{\headheight}{\dimexpr\headerboxsize}
  \setlength{\textheight}{\dimexpr\paperheight-1in-\voffset-\topmargin-\headheight-\headsep-2cm}
}


% Small-header and compact-header construction

% header entry with arguments: {key}{value}[ending]
% ending is optional and is by default a large space
% value is required but can be empty to remove the whole entry
\NewDocumentCommand\@docinfo{m m O{\hskip1.7em}}{%
  \def\@docinfoval{#2}%
  \if\relax\@docinfoval\relax\else
    \fcolorbox{sapphire}{white}{%
      \textcolor{sapphire}{\frenchspacing\footnotesize\texttt{\MakeUppercase{#1}}}}
    {\ttfamily\small #2}#3\strut%
  \fi
}

\newlength{\mainwidth} % width of title in two-column format
\setlength{\mainwidth}{0.825\textwidth}

\fancypagestyle{smallheader}{%
  \renewcommand{\headrulewidth}{0.96pt} % default for \heavyrulewidth
  \renewcommand{\headrule}{\color{sapphire}\hrule height \headrulewidth}
  \setlength{\fboxrule}{0.5pt}
  \setlength{\fboxsep}{1.5pt}
  \fancyhf{}
  \@head[L]{
    \linespread{0.85}\small
    \begin{tabularx}{\textwidth}{@{} p{\dimexpr\textwidth-\mainwidth-5pt}
                                 @{\hspace{5pt}} >{\raggedright\arraybackslash}m{\mainwidth} @{}}%
      \iflogo
        \includegraphics[width=\linewidth, valign=m]{\@projectlogo}%
      \else
        \adjustbox{valign=m}{\ttfamily\Huge\fontseries{b}\selectfont\squeeze{\@project}}%
      \fi%
      &
      \if\relax\@documenttype\relax
        \@docinfo{Title}{\@shorttitle}[] \newline
      \else
        \@docinfo{\@documenttype}{\@shorttitle}[] \newline
      \fi%
      \if\relax\@documentnumber\@institutenumber\relax\else
        \@docinfo{Doc.~no.}{\@documentnumber}%
        \@docinfo{Inst.~no.}{\@institutenumber}[] \newline
      \fi
      \if\relax\@issue\@date\@level\@class\@category\relax\else
        \@docinfo{Issue}{\@issue}%
        \@docinfo{Date}{\@date}%
        \@docinfo{Level}{\@level}%
        \@docinfo{Class}{\@class}%
        \@docinfo{Cat.}{\@category}[] \newline
      \fi
      \@docinfo{Page}{\thepage\ of \pageref*{LastPage}} \\
    \noalign{\vspace{2pt}}
    \end{tabularx}%
  }
  \setlength{\headheight}{\dimexpr\headerboxsize + \headrulewidth}
  \setlength{\textheight}{\dimexpr\paperheight-1in-\voffset-\topmargin-\headheight-\headsep-2cm}
}

\fancypagestyle{logoheader}{%
  \renewcommand{\headrule}{}
  \fancyhf{}
  \@head[L]{
    \begin{tabularx}{\textwidth}{@{} >{\raggedright\arraybackslash}p{\textwidth} @{}}%
      \iflogo
        \includegraphics[width=\linewidth, max height=3cm, valign=m]{\@projectlogo}%
      \else
        \adjustbox{valign=m}{\ttfamily\Huge\fontseries{b}\selectfont\squeeze{\@project}}%
      \fi%
    \end{tabularx}%
  }
  \setlength{\headheight}{\dimexpr\headerboxsize + \headrulewidth}
  \setlength{\textheight}{\dimexpr\paperheight-1in-\voffset-\topmargin-\headheight-\headsep-2cm}
}

\fancypagestyle{compactheader}{%
  \renewcommand{\headrulewidth}{0.96pt} % default for \heavyrulewidth
  \renewcommand{\headrule}{\color{sapphire}\hrule height \headrulewidth}
  \setlength{\fboxrule}{0.5pt}
  \setlength{\fboxsep}{2pt}
  \fancyhf{}
  \@head[L]{
    \small
    \begin{tabularx}{\textwidth}{@{} >{\raggedright\arraybackslash}p{\textwidth} @{}}%
      \@docinfo{Doc.~no.}{\@documentnumber}%
      \@docinfo{Issue}{\@issue}%
      \@docinfo{Date}{\@date}%
      \hfill\@docinfo{Page}{\thepage\ of \pageref*{LastPage}}[] \newline
      \if\relax\@institutenumber\@project\@documenttype\@level\@class\@category\relax\else
        \@docinfo{Inst.~no.}{\@institutenumber}%
        \@docinfo{Project}{\@project}%
        \@docinfo{Doc.~type}{\@documenttype}%
        \@docinfo{Level}{\@level}%
        \@docinfo{Class}{\@class}%
        \@docinfo{Cat.}{\@category}[] \newline
      \fi
      \if\relax\@shorttitle\relax\else
        \@docinfo{Title}{\@shorttitle}[]%
      \fi \\
    \noalign{\vspace{2pt}}
    \end{tabularx}%
  }
  \setlength{\headheight}{\dimexpr\headerboxsize + \headrulewidth}
  \setlength{\textheight}{\dimexpr\paperheight-1in-\voffset-\topmargin-\headheight-\headsep-2cm}
}


% Title page

% \maketitle (without class option nosigs) produces a table with room for 
% signature fields. \maketitle[a,b,c,d] with a, b, c and d each either 0, 1
% or 2 also adds this number of signature fields to the prepared, checked,
% agreed and authorised table cells, respectively, but eforms from the
% acrotex bundle needs to be installed.

% wrapper around \IfFileExists using \graphicspath and dealing with empty argument
% \input@path is not necessarily defined, but if it is,
% we don't want to erase its contents
\providecommand*{\input@path}{}
\newcommand{\IfImageExists}[3]{%
  % enclosing the possible redefinition of \input@path
  % and the \IfFileExists test in this group will
  % make \input@path revert to its previous definition after the test
  \if\relax#1\relax
    #3%
  \else
    \begingroup
    \ifdefined\Ginput@path
      \edef\input@path{\input@path\Ginput@path}%
    \fi
    \IfFileExists{#1}{\endgroup #2}{\endgroup #3}%
  \fi
}

\newif\iflogo
\renewcommand\maketitle[1][]{%
  \IfImageExists{\@projectlogo}{%
    \logotrue
  }{%
    \logofalse
    \if\relax\@projectlogo\relax\else
      \ClassWarningNoLine{plain}{Project logo '\@projectlogo' not found, using project name}
    \fi
  }
  \pagestyle{\@headertype} % style for all pages
  \ifthenelse{\equal{\@firstheadertype}{\@headertype}}%
    {}%
    {\thispagestyle{\@firstheadertype}} % replace style for first page
  \ifthenelse{\equal{#1}{}}%
    {\expandafter\@fronttable0,0,0,0,\@nil}%
    {\IfFileExists{eforms.sty}{}{\ClassWarningNoLine{plain}%
      {Install eforms from the acrotex bundle to add signature fields}}
     \expandafter\@fronttable#1,,,,\@nil}
}

% Fields for digital signatures.
% Needs eforms.sty, insdljs.sty, taborder.sty and epdftex.def,
% or the whole acrotex bundle from CTAN.
\IfFileExists{eforms.sty}%
  {\RequirePackage{eforms}
   \kvsetkeys{Form}{NeedAppearances=false}
   \newcommand{\@signaturefield}[1]{\sigField{##1}{\linewidth}{23.45pt}}}%
  {\newcommand{\@signaturefield}[1]{}}
\newcommand{\@signatureset}[2]{%
  \raisebox{-8.1pt}[0pt]{%
    \hspace{1.5pt}%
    \begin{minipage}[t]{\dimexpr\linewidth-3.8pt}%
    \ifnum #1>0\@signaturefield{#2}\fi%
    \ifnum #1>1\vskip 1pt\@signaturefield{#22}\fi%
    \end{minipage}%
  }%
}
\newcommand{\@signaturerow}[3]{%
  \if\relax#2\relax\else
    \rule[-1.5cm]{0pt}{1.5cm}%
    \texttt{\textbf{#1}} & \raggedright #2\strut & #3 \\%
    \cline{3-3}%
  \fi
}

\newcommand{\@frontrow}[2]{%
  \if\relax#2\relax\else
    \texttt{\textbf{#1}} & \multicolumn{2}{@{}p{\mainwidth}@{}}{\raggedright #2\strut} \\%
  \fi
}

\def\@largeheadertext{largeheader}
\def\@fronttable#1,#2,#3,#4,#5\@nil{%
  \begingroup
  \setlength{\parindent}{0pt}
  \arrayrulecolor{black!8}
  \vspace*{\dimexpr1.5cm-\headsep}
  \begin{tabularx}{\textwidth}{@{} p{\dimexpr\textwidth-\mainwidth} @{} X | @{} p{0.5\textwidth} @{} |}
    \iflargetitle
      \multicolumn{3}{@{} p{\textwidth} @{}}{\raggedright \ttfamily\LARGE\bfseries\@title\strut} \\%
    \else
      \texttt{\textbf{Title}} & \multicolumn{2}{@{} p{\mainwidth} @{}}{%
        \raggedright \ttfamily\LARGE\bfseries\@title\strut} \\%
    \fi
    \noalign{\vspace{1.5cm}}%
    \ifx\@firstheadertype\@largeheadertext\else
      \@frontrow{Document type}{\@documenttype}%
      \@frontrow{Document number}{\@documentnumber}%
      \@frontrow{Inst. number}{\@institutenumber}%
      \@frontrow{Issue}{\@issue}%
      \@frontrow{Level}{\@level}%
      \@frontrow{Class}{\@class}%
      \@frontrow{Category}{\@category}%
      \@frontrow{Date}{\@date}%
      \if\relax\@documenttype\@documentnumber\@institutenumber\@issue\@level\@class\@category\@date\relax\else
        \noalign{\vspace{1.5cm}}%
      \fi
    \fi
    \ifsigs
      \if\relax\@author\@checkedby\@agreedby\@authorisedby\relax\else
        \cline{3-3}%
      \fi
      \@signaturerow{Prepared by}{\@author}{\@signatureset{#1}{prepared}}%
      \@signaturerow{Checked by}{\@checkedby}{\@signatureset{#2}{checked}}%
      \@signaturerow{PA agreed by}{\@agreedby}{\@signatureset{#3}{agreed}}%
      \@signaturerow{Authorised by}{\@authorisedby}{\@signatureset{#4}{authorised}}%
      \if\relax\@cinumber\@model\@baseline\@workpackage\relax\else
        \noalign{\vspace{4pt}}%
        \texttt{\textbf{CCB data}} & \multicolumn{1}{@{}l}{CI number} & \multicolumn{1}{l}{\@cinumber} \\%
        \if\relax\@model\relax\else
          & \multicolumn{1}{@{}l}{Model} & \multicolumn{1}{l}{\@model} \\%
        \fi
        \if\relax\@baseline\relax\else
          & \multicolumn{1}{@{}l}{Baseline} & \multicolumn{1}{l}{\@baseline} \\%
        \fi
        \if\relax\@workpackage\relax\else
          & \multicolumn{1}{@{}l}{WP} & \multicolumn{1}{l}{\@workpackage} \\%
        \fi
      \fi
    \else
      \@frontrow{Prepared by}{\@author}%
      \@frontrow{Checked by}{\@checkedby}%
      \@frontrow{PA agreed by}{\@agreedby}%
      \@frontrow{Authorised by}{\@authorisedby}%
    \fi
  \end{tabularx}%
  \arrayrulecolor{black}%
  \endgroup
}

% Suppress some log messages
% Make it possible to use something like \author{Sarah Lee\\Tom Smith}
\pdfsuppressptexinfo15 % suppress PTEX.Fullbanner and info of imported PDFs
\pdfstringdefDisableCommands{%
  \def\\{,\space}%
  \def\texttt#1{<#1>}%
}

% Metadata and better PDF/A-2b compliance
\AtBeginDocument{%
  \hypersetup{%
    pdftitle={\@title},
    pdfauthor={\@authorinproperties},
    pdfidentifier={\@documentnumber},
    pdfversionid={\@issue},
    pdfproducer={},
    pdfcreator={},
    pdfsource={},
    pdfapart=2,
    pdfaconformance=B
  }
  \ifpdf
    \immediate\pdfobj stream attr{/N 3} file{sRGB.icc}
    \pdfcatalog{%
      /OutputIntents [
      <<
        /Type /OutputIntent
        /S /GTS_PDFA1
        /DestOutputProfile \the\pdflastobj\space 0 R
        /OutputConditionIdentifier (sRGB)
        /Info (sRGB)
      >>
      ]
    }
  \fi
}


% Table of contents

\RequirePackage[nottoc]{tocbibind}
\RequirePackage[titles]{tocloft}
\setlocalecaption{UKenglish}{contents}{Table of contents}
\renewcommand{\cfttoctitlefont}{\ttfamily\Large\bfseries}
\renewcommand{\cftsecfont}{\normalfont}
\renewcommand{\cftsecleader}{\normalfont\cftdotfill{\cftsecdotsep}}
\renewcommand{\cftsecdotsep}{\cftdotsep}
\renewcommand{\cftsecpagefont}{\normalfont}


% Environments for first sections

\newenvironment{distributionlist}
{%
  \vspace{1.5cm}
  \noindent\texttt{\textbf{Distribution}}
  \begin{itemize}[label={},leftmargin=0cm]
}{%
  \end{itemize}
}

\newenvironment{changerecordtable}
{%
  \section*{Document change record}
  \begin{tabular}{llll}
  Issue & Date & Changed section & Description of change \\
  \midrule[\heavyrulewidth]\ignorespaces
}{%
  \end{tabular}\par
}

\newenvironment{abbreviationtable}
{%
  \section*{Abbreviations}
  \addcontentsline{toc}{section}{Abbreviations}
  \begin{tabular}{ll}
  Item & Meaning \\
  \midrule[\heavyrulewidth]\ignorespaces
}{%
  \end{tabular}\par
}

\NewDocumentEnvironment{documentstable}{+b}
{%
  \section*{Reference documents}
  \addcontentsline{toc}{section}{Reference documents}
  \begin{booktabs}{lllX[l]}
  {[RD\#]} & Document reference & Issue & Title \\
  \midrule[\heavyrulewidth]
  #1
  \end{booktabs}
}{%
  \par
}

\NewDocumentEnvironment{applicabledocumentstable}{+b}
{%
  \section*{Applicable documents}
  \addcontentsline{toc}{section}{Applicable documents}
  \begin{booktabs}{lllX[l]}
  {[AD\#]} & Document reference & Issue & Title \\
  \midrule[\heavyrulewidth]
  #1
  \end{booktabs}
}{%
  \par
}
