% \iffalse meta-comment
%
% RWTH-CI -- Corporate Design for RWTH Aachen University
% ----------------------------------------------------------------------------
%
%  Copyright (C) 2025–2026 by Marei Peischl <rwth-ci@peitex.de> and Lukas C. Bossert
%
% ============================================================================
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3c
% of this license or (at your option) any later version.
% The latest version of this license is in
% http://www.latex-project.org/lppl.txt
% and version 1.3c or later is part of all distributions of LaTeX
% version 2008/05/04 or later.
%
% This work has the LPPL maintenance status `maintained'.
%
% The Current Maintainer of this work is
%   Marei Peischl rwth-ci@peitex.de
%
% The development repository can be found at
% https://gitlab.git.nrw/rwth-it-center/rwth-latex-templates/rwth-ci
% Please use the issue tracker for feedback!
%
% ============================================================================
%
% \fi
% \iffalse
%<*driver>
\ProvidesFile{rwth-letter.dtx}
  [2026-04-03 v1.2 Letters for RWTH-CI, Corporate Design of RWTH Aachen University]
%</driver>
%<@@=ptxcd>
%<*identification>
%<*package>
\NeedsTeXFormat{LaTeX2e}[2022-10-01]
\ProvidesExplPackage{rwth-letter}{2026-04-03}{1.2}{Letters for RWTH-CI, Corporate Design of RWTH Aachen University}
%</package>
%</identification>
%<*driver>
\providecommand*{\PtxcdDocDTXfiles}{rwth-letter.dtx}
\providecommand*{\PtxcdDocTitle}{\pkg{rwth-letter}~--~\LaTeX{}~Letter~setup~for~RWTH-CI}
\input{rwth-ci.dtx}
%</driver>
%<*initialization>
% \fi
% \begin{documentation}
% \section{Letters – \pkg{rwth-letter.sty}}
% The letter package is based on \pkg{scrletter} and supports all elements described in the KOMA-Script documentation.
% The corresponding demo file is called \file{DEMO-RWTHLetter.tex} and there also is a lco file to show a global configuration for address data.
%
% \subsection{Package specific options}
% \end{documentation}
% \begin{implementation}
% \begin{variable}{\g_@@_wide_letter_bool}
%    \begin{macrocode}
\bool_new:N \g_@@_wide_letter_bool
%    \end{macrocode}
% \end{variable}
%    \begin{macrocode}
\keys_define:nn {ptxcd/letter} {
%    \end{macrocode}
% \end{implementation}
% \begin{documentation}
% \DescribeKeyOption*{letterheadfile=\meta{file name/path}}{}
% There are logo files including the blue separation line for letters.
% These have to be scaled differently.
% This option allows to select those by passing it to the global \option{logofile} option and will adjust the scaling accordingly.
% The demo logo repository provides the file \file{rwth_briefkopf_cmyk.pdf} which could be enabled using the following setting:
% \begin{examplecode}
%   \usepackage[
%     letterheadfile=rwth_briefkopf
%   ]{rwth-letter}
% \end{examplecode}
% \end{documentation}
% \begin{implementation}
% \changes{v1.0}{2025-12-18}{Add support for letterheadfile}
% \begin{optionenv}{logo-is-letterhead,letterheadfile}
%    \begin{macrocode}
  logo-is-letterhead .bool_gset:N = \g_@@_logo_is_letterhead_bool,
  letterheadfile .code:n = \keys_set:nn {ptxcd/letter} {logofile=#1,logo-is-letterhead=true},
%    \end{macrocode}
% \end{optionenv}
% \end{implementation}
% \begin{documentation}
% \DescribeKeyOption{letterhooks=\meta{boolean}}{false}
% Add support for different document configuration which does not match the RWTH-CI settings outside of letters.
% \end{documentation}
% \begin{implementation}
% \begin{optionenv}{letterhooks}
%    \begin{macrocode}
  letterhooks .bool_gset:N = \g_@@_letterhooks_bool,
  letterhooks .initial:n = false,
  letterhooks .default:n = true,
  letterhooks .usage:n = load,
%    \end{macrocode}
% \end{optionenv}
% \end{implementation}
% \begin{documentation}
% \DescribeKeyOption{grayscale=\meta{boolean}}{false}
% Can be used to create the non-colored letter layout.
% This will use \pkg{xcolor}'s gray color model and convert all colores within the letter.
% If \option{letterhooks} is not enabled this would affect the whole document.
% \end{documentation}
% \begin{implementation}
% \begin{optionenv}{grayscale}
%    \begin{macrocode}
  grayscale .bool_gset:N = \g_@@_grayscale_bool,
  grayscale .initial:n = false,
  grayscale .default:n = true,
  grayscale .usage:n = load,
%    \end{macrocode}
% \end{optionenv}
% \end{implementation}
% \begin{documentation}
% \DescribeKeyOption{payment-data=\meta{boolean}}{false}
% \end{documentation}
% \begin{implementation}
% \begin{optionenv}{payment-data}
%    \begin{macrocode}
  payment-data .bool_gset:N = \g_@@_payment_data_bool,
  payment-data .initial:n = false,
  payment-data .default:n = true,
  payment-data .usage:n = load,
%    \end{macrocode}
% \end{optionenv}
% \end{implementation}
% \begin{documentation}
% \DescribeKeyOption{textwidth=narrow/wide}{narrow}
% Switch between the two available letter layouts.
%
% \end{documentation}
% \begin{implementation}
% \begin{optionenv}{textwidth}
%    \begin{macrocode}
  textwidth .choice:,
  textwidth / narrow .code:n = \bool_gset_false:N  \g_@@_wide_letter_bool,
  textwidth / wide .code:n = \bool_gset_true:N \g_@@_wide_letter_bool,
  textwidth .initial:n = narrow,
  textwidth .usage:n = load,
%    \end{macrocode}
% \end{optionenv}
% \iffalse
%</initialization>
%<*processoptions>
% \fi
%    \begin{macrocode}
%<gobble>}
\ProcessKeyOptions[ptxcd/letter]
%    \end{macrocode}
% \iffalse
%</processoptions>
%<*body>
% \fi
%    \begin{macrocode}
\bool_if:NF  \g_@@_wide_letter_bool {\PassOptionsToPackage{firstfoot=false}{scrletter}}
\PassOptionsToPackage{addrfield=topaligned,pagenumber=botright,refline=nodate,numericaldate=true}{scrletter}
\RequirePackage{scrletter}
%    \end{macrocode}
% Load the RWTH-colorscheme
%    \begin{macrocode}
\PassOptionsToPackage{cmyk}{rwth-colors}
\RequirePackage{rwth-colors}
%    \end{macrocode}
% Load the RWTH font configuration.
% This is not changing the documents main font, as this is not document class.
%    \begin{macrocode}
\PassOptionsToPackage{fontdefaults=false}{rwth-fonts}
\RequirePackage{rwth-fonts}
\bool_if:NTF \g_@@_letterhooks_bool {
  \AtBeginLetter
}{
  \AtBeginDocument
}{%
  \let\sfdefault\rwth@sffamily
  \renewcommand*{\familydefault}{\sfdefault}%
  \normalfont
  \makeatletter
  \input{rwth-lettersize11bp.clo}%
  \makeatother
  \bool_if:NT \g_@@_grayscale_bool {\selectcolormodel{gray}}
  \bool_if:NT \g_@@_raggedright_bool {\raggedright}
}
%    \end{macrocode}
% \end{implementation}
% \begin{documentation}
%
% \subsection{Additional KOMA variables defined for RWTH-CI}
% The letter template requires some additional variables:
% \begin{description}
%   \item[frominstitution] institute/department/group
%   \item[frominstitution-short] Abbreviated version of frominstitution to be used in the backaddress
%   \item[frominstitution-id] identifier to be placed right of the backaddress
%   \item[fromfunction] position or job title of the sender
%   \item[fromoffice] building and room number
%   \item[fromvat] VAT ID
%   \item[fromtax] Tax ID
% \end{description}
% The RWTH Letter layout also allows to add a second sender.
% Therefore this bundle provides also the KOMA variables |fromname2| and |fromfunction2|.
% Using more than 2 persons is not allowed.
%
% The same applies for |frombank| here |frombank2| and |frombank3| have been added.
% \end{documentation}
% \begin{implementation}
%    \begin{macrocode}
\newkomavar{frominstitution}
\newkomavar{frominstitution-short}
\newkomavar{frominstitution-id}
\newkomavar{fromfunction}
\newkomavar{fromname2}
\newkomavar{fromfunction2}
\newkomavar{fromoffice}
\newkomavar[\VatIdName]{fromvat}
\newkomavar[\TaxIdName]{fromtax}
\newkomavar{frombank2}
\newkomavar{frombank3}
%    \end{macrocode}
% \changes{1.1-dev}{2026-02-12}{Add captions for VAT and TAX IDs}
%    \begin{macrocode}
\providecaptionname{american,australian,british,canadian,english,newzealand,UKenglish,ukenglish,USenglish,usenglish}\VatIdName{VAT ID}
\providecaptionname{american,australian,british,canadian,english,newzealand,UKenglish,ukenglish,USenglish,usenglish}\TaxIdName{Tax ID}
\providecaptionname{german,ngerman,austrian,naustrian,swissgerman,nswissgerman}\VatIdName{USt-Identifikationsnummer}
\providecaptionname{german,ngerman,austrian,naustrian,swissgerman,nswissgerman}\TaxIdName{Steuernummer}
%    \end{macrocode}
% Letter Layout definitions:
%    \begin{macrocode}
\RequirePackage{geometry}
\geometry{left=2cm,top=3.6cm,bottom=1.3cm}

\bool_if:NTF  \g_@@_wide_letter_bool {
  \geometry{right=7.5mm}
}{
  \geometry{right=6cm}
}
%    \end{macrocode}
% TODO: ensure all logo files have the same dimensions.
% The 4mm offset is the 8mm offset mentioned in the guideline - the overlab of the secondary logo file.
%    \begin{macrocode}
\setplength{firstheadvpos}{4mm}% 8m zum RWTH logo
\setplength{firstheadhpos}{20mm}
\setplength{firstheadwidth}{187.5mm}% inkl 5mm  logo offset

\bool_if:NTF  \g_@@_wide_letter_bool {
  \setplength{locwidth}{60mm}
} {
  \setplength{locwidth}{44mm}
}

\setplength{lochpos}{7.5mm}
\setplength{locvpos}{36mm}
\setplength{locheight}{248mm}

\setplength{toaddrindent}{0pt}
\setplength{toaddrhpos}{2cm}
\setplength{toaddrwidth}{85mm}
\setplength{toaddrheight}{45mm}

\setplength{refvpos}{96mm}

\setplength{toaddrhpos}{20mm}
\setplength{tfoldmarkvpos}{105mm}
\setplength{bfoldmarkvpos}{210mm}

\bool_if:NT  \g_@@_wide_letter_bool {
  \setplength{firstfootvpos}{262mm}
  \setplength{firstfoothpos}{20mm}
  \setplength{firstfootwidth}{\textwidth}
  \setkomavar{firstfoot}{
    \bool_if:NT \g_@@_payment_data_bool {
      \parbox[t][22mm]{\useplength{firstfootwidth}}{
        \usekomafont{paymentdata}
        \parbox{45mm}{
          \setlength{\parskip}{\z@}
          \raggedright
          \clist_map_inline:nn {fromvat,fromtax} {
            \Ifkomavarempty{##1}{}{%
              \Ifkomavarempty*{##1}{}{\usekomavar*{##1}\par}
              \ignorespaces\usekomavar{##1}
              \par\addvspace{\baselineskip}
            }
          }
        }
        \clist_map_inline:nn {frombank,frombank2,frombank3} {
          \hskip1mm
          \parbox{44mm}{
            \setlength{\parskip}{\z@}
            \raggedright
            \Ifkomavarempty{##1}{}{%
              \Ifkomavarempty*{##1}{}{\usekomavar*{##1}:\space}
              \ignorespaces\usekomavar{##1}
              \par
            }
          }
        }
        \hfill
      }
    }
  }
}

\RequirePackage{graphicx}

%^^A Logo-Datei hat 5mm hmargin und 4mm mm vmargin
\setkomavar{firsthead}{\hskip 0pt plus 1 fill
  \_@@_insert_logo:n {
    \bool_if:NTF \g_@@_logo_is_letterhead_bool {80mm} {32mm}
  }
}

\newcommand{\ptxcd@location}{
%    \end{macrocode}
% If the payment_data is not displayed, the location field does not need a fixed height.
%    \begin{macrocode}
  \bool_if:NTF \g_@@_payment_data_bool
  {\use:nn} {\use_i:nn}
  {\parbox}{[t][\useplength{locheight}]}
  {\useplength{locwidth}}{
    \usekomafont{fromaddress}
    \raggedright
    \setlength{\parskip}{\z@}
    \setlength{\parindent}{\z@}
    \Ifkomavarempty{fromname}{}{
      {\usekomafont{fromname}%
          \ignorespaces\usekomavar{fromname}\par
        }
      \bool_if:NF \g_@@_wide_letter_bool {
        \Ifkomavarempty{fromfunction}{}{\ignorespaces\usekomavar{fromfunction}}
      }
			\par\addvspace{\baselineskip}
    }
    \Ifkomavarempty{fromname2}{}{
      {\usekomafont{fromname}%
          \ignorespaces\usekomavar{fromname2}\par
        }
      \bool_if:NF \g_@@_wide_letter_bool{
        \Ifkomavarempty{fromfunction2}{}{\ignorespaces\usekomavar{fromfunction2}}
      }
      \par\addvspace{\baselineskip}
    }
    \bool_if:NTF \g_@@_wide_letter_bool {
      \clist_set:Nn \l_tmpa_clist {fromaddress}
    } {
      \clist_set:Nn \l_tmpa_clist {fromaddress,fromoffice}
    }
    \clist_map_inline:Nn \l_tmpa_clist {
      \Ifkomavarempty{##1}{}{
        \ignorespaces\usekomavar{##1}
        \par\addvspace{\baselineskip}
      }
    }
    \clist_map_inline:nn {fromphone,fromfax,frommobilephone} {
      \Ifkomavarempty{##1}{}{
        \leavevmode
        \makebox[.22\linewidth][l]{\usekomavar*{##1}}\hspace{1em}
        \parbox[t]{\dimexpr.78\linewidth-1em}{
          \raggedright
          \strut\ignorespaces\usekomavar{##1}\strut\par
        }
        \par
      }
    }
    \par\addvspace{\baselineskip}

    \Ifkomavarempty{fromemail}{}{
      \ignorespaces\usekomavar{fromemail}
      \par\addvspace{\baselineskip}
    }
    \bool_if:NF \g_@@_wide_letter_bool {
      \Ifkomavarempty{fromurl}{}{
        \ignorespaces\usekomavar{fromurl}
        \par\addvspace{\baselineskip}
      }
    }
    \let\do@set@reffield\ptxcd@set@reffield
    \@set@reffields%
    \par
    \Ifkomavarempty{date}{}{%
      \begingroup
      \Ifkomavarempty*{date}{}{\usekomavar*{date}:\space}
      \usekomafont{letterdate}\ignorespaces\usekomavar{date}
      \endgroup
    }
    \par
    \bool_if:NF \g_@@_wide_letter_bool {
      \bool_if:NT \g_@@_payment_data_bool {
        \vfill
        \usekomafont{paymentdata}
        \clist_map_inline:nn {fromvat,fromtax,frombank,frombank2,frombank3} {
          \Ifkomavarempty{##1}{}{%
            \Ifkomavarempty*{##1}{}{\usekomavar*{##1}:\space}
            \ignorespaces\usekomavar{##1}
            \par\addvspace{\baselineskip}
          }
        }
      }
    }
  }
}

\newcommand*{\ptxcd@set@reffield}[1]{%
  \Ifkomavarempty{#1}{}{%
    \bool_if:NT \g_@@_wide_letter_bool {\par\addvspace{\baselineskip}}
    \Ifkomavarempty*{#1}{}{{\usekomafont{refname}\usekomavar*{#1}:\space}}
    {\usekomafont{refvalue}\strut\usekomavar{#1}}
    \par
  }
}%

\setkomavar{location}{
  \ptxcd@location
}

\setkomafont{backaddress}{\color{rwth-blue-100}\scriptsize}
\setkomafont{addressee}{}% normalsize?
\setkomafont{fromname}{\usekomafont{fromaddress}\bfseries}
\setkomafont{fromaddress}{\small}
\setkomafont{refname}{\small}
\setkomafont{pagenumber}{\small}
\setkomafont{refvalue}{\usekomafont{refname}}
\newkomafont{paymentdata}{\footnotesize}
\newkomafont{letterdate}{\bfseries}

%    \end{macrocode}
% pagestyle configuration
%    \begin{macrocode}

\DeclareNewLayer[
  background,
% remove rule if \g_@@_logo_is_letterhead_bool?
  contents={\color{rwth-blue-25}\rule{\layerwidth}{\layerheight}},
  hoffset=\dimexpr137.5mm+ 0.47952bp,% 21 cm - 6cm - 0.75cm - .5cm
  voffset=44mm,
  width=1bp,
  height=8cm,
  align=c,
]{letter.first.rule}

%    \end{macrocode}
% \changes{v1.0}{2025-12-18}{Configure letterpagemark}
%    \begin{macrocode}
\renewcommand*{\letterpagemark}{%
% get lastpage for this letter if not already done
  \int_if_exist:cF {c_@@_letter\thisletter _lastpage_int} {
    \cs_if_exist:cTF {r@\thisletter.lastpage} {
      \int_const:cn {c_@@_letter\thisletter _lastpage_int} {
        \exp_args:NNc \expandafter \@secondoffive { r@\thisletter.lastpage}
      }
    } {
% warning -> rerun latex
      \int_const:cn {c_@@_letter\thisletter _lastpage_int} {0}
    }
  }
  \int_compare:nT {
    \int_use:c {c_@@_letter\thisletter _lastpage_int}
    > 1
  } {
    \bool_if:NTF  \g_@@_wide_letter_bool {
%  \setplength{locwidth}{60mm}
    } {
      \makebox[\useplength{locwidth}][l]
    }
    {\usekomafont{pagenumber}\thepage/\int_to_arabic:n{\int_use:c {c_@@_letter\thisletter _lastpage_int}}}
  }
}

\renewpairofpagestyles{letter}{%
  \bool_if:NF	\g_@@_wide_letter_bool {\KOMAoptions{footwidth=18.25cm}}
  \clearpairofpagestyles
  \lehead{\usekomavar{nexthead}}
  \lohead{\usekomavar{nexthead}}
  \lefoot{\usekomavar{nextfoot}}
  \lofoot{\usekomavar{nextfoot}}
  \refoot[\pagemark]{}
  \rofoot[\pagemark]{}
}

\ModifyLayer[
  voffset=\dimexpr\paperheight-.8cm\relax,
  hoffset=2cm,
  width=18.25cm,
]{plain.letter.foot.oneside}

\ModifyLayer[
  voffset=\dimexpr\paperheight-.8cm\relax,
  hoffset=2cm,
  width=18.25cm,
]{letter.foot.oneside}

\DeclareNewPageStyleByLayers{letter.first}{plain.letter.foot.oneside,letter.first.rule}

\AddToHook{cmd/@datefield/before}{
  \removereffields
}

\AddToHook{cmd/@makelettertitle/after}{
  \thispagestyle{letter.first}
}

\renewcommand{\backaddr@format}[1]{
  \makebox[\useplength{toaddrwidth}]{
    #1
    \hfill\Ifkomavarempty{frominstitution-id}{}{\textcolor{black}{\usekomavar{frominstitution-id}}}
  }
}
\setkomavar{specialmail}{\null}
\setkomavar{backaddress}{%
	\Ifkomavarempty{frominstitution-short}{%
		\Ifkomavarempty{frominstitution}{}{\textbf{\usekomavar{frominstitution}}\\}%
	}{\textbf{\usekomavar{frominstitution-short}}\\}%
	\usekomavar{fromaddress}%
}
\setkomavar{backaddressseparator}{\space|\space}

\setkomavar*{date}{}

%    \end{macrocode}
% \iffalse
%</body>
% \fi
% \end{implementation}
% \Finale
\endinput
