\ProvidesPackage{config/layout}

\RequirePackage[table]{xcolor}
\RequirePackage[copies]{contour}
\RequirePackage{imakeidx}% for spell summaries
\RequirePackage[
  acronyms,
  prefix,
  symbols,
  stylemods=mcols,
  style=mcoltree,
]{glossaries-extra}
  \setabbreviationstyle[acronym]{short-sc-long-desc}

\RequirePackage{gfsartemisia-euler} % fancy fonts
\RequirePackage[T1]{fontenc} % 
\RequirePackage{starfont} % for creature symbols
\RequirePackage{wasysym} % for sq checkboxes
\RequirePackage{appendix}
\RequirePackage{geometry} % changes page borders
  \geometry{margin=50pt}
\RequirePackage{svg}
\RequirePackage{alltt}
  \svgsetup{width=\textwidth}
\RequirePackage{tabularx}
\RequirePackage{wrapfig}
\RequirePackage{float}
\RequirePackage{epigraph} % part quotes
\RequirePackage{microtype} % more precise word-placement
\RequirePackage{makeidx}
\RequirePackage[english]{babel}
\RequirePackage{multicol}
  \raggedcolumns
\RequirePackage{graphicx}
\RequirePackage{etoolbox}
\RequirePackage{xparse}
\RequirePackage{titlesec,titletoc}
\RequirePackage{fancyhdr}
  \RequirePackage{fourier-orns}% for fancy headrules
\RequirePackage{needspace}
\RequirePackage{tikz}
  \usetikzlibrary{calc,mindmap,trees}% calc for fancy borders
  \usetikzlibrary{intersections}% for very fancy borders with intersecting lines
  \usetikzlibrary{decorations.text}% for text along circle paths in cs
  \usetikzlibrary{shapes.misc}% for very fancy \section
  \usetikzlibrary{shapes.callouts}% for labels on the cs
  \usetikzlibrary{patterns}% for the pattern 'gridspecks'
\RequirePackage{pifont}
\RequirePackage{colortbl}
\RequirePackage[poster]{tcolorbox}
\tcbuselibrary{breakable,raster,vignette}
\tcbuselibrary{skins} % used for wiggly-border boxes
  \pgfdeclarepatternformonly{gridspecks}{\pgfqpoint{-1pt}{-1pt}}{\pgfqpoint{1pt}{1pt}}{\pgfqpoint{26pt}{26pt}}
  {%
    \pgfpathcircle{\pgfqpoint{0pt}{0pt}}{.5pt}%
    \pgfusepath{fill}%
  }%

%%%%% Add fancy page chapter sides %%%%%

\newcounter{chapshift}
\addtocounter{chapshift}{-1}

%% Redefine plain page style, and use it for every page.

\renewcommand\headrule{%
  \iftoggle{verbose}{
  \vspace{-6pt}
  \hrulefill
  \raisebox{-2.1pt}
    {\textcolor{\pageSideColor}{\quad\decofourleft\decotwo\decofourright\quad}}%
  \hrulefill
  }{}
}

\fancypagestyle{plain}{
  \fancyhf{}% clear all header and footer fields
  \fancyfoot[LE]{--~\thepage}
  \fancyfoot[RO]{\thepage~--}
  \renewcommand{\headrulewidth}{0pt}%
} 

\pagestyle{plain}
%\fancyfoot{}

\newcounter{pageDarkness}
\setcounter{pageDarkness}{20}
\newcounter{pageAlt}
\setcounter{pageAlt}{100}

\newcommand\pageSideColor{black!\arabic{pageDarkness}!white}
\newcommand\pageOppositeColor{black!\arabic{pageAlt}}

\newif\ifsidetab
\sidetabtrue

\AddToHook{shipout/background}{%
  \if@mainmatter
    \pgfmathsetmacro{\BGvadjust}{ -2 * (\value{chapter} - 1)}
    \ifodd\value{page}
      \def\BGpageanchor{current page.north east}
      \def\BGanchor{north west}
      \def\BGmark{\textcolor{\pageOppositeColor}{\rightmark}}
      \def\BGrotate{-90}
    \else
      \def\BGpageanchor{current page.north west}
      \def\BGanchor{north east}
      \def\BGmark{\textcolor{\pageOppositeColor}{\leftmark}}
      \def\BGrotate{90}
    \fi
    \begin{tikzpicture}[overlay,remember picture]
      \path 
        ++(\BGpageanchor)
        +(0cm, \BGvadjust cm)
        node[
          text centered,
          inner sep=4pt,
          text width=4ex,
          text height=4ex,
          text depth=3ex,
          text width=14em,
          text=white,
          fill=\pageSideColor,
          anchor=\BGanchor,
          rotate=\BGrotate,
          font=\scshape\bfseries,
        ] {\BGmark};
    \end{tikzpicture}%
  \fi
}%

% redefinition of \chaptermark to contain only the number and title (no 'Chapter 1: Pogs', just '1: Pogs')
\renewcommand\chaptermark[1]{\markboth{\thechapter.~#1}{}}

\RequirePackage{xr-hyper}
\RequirePackage[
pdfstartpage=1,
hidelinks=true,
bookmarks=true]%
{hyperref}

%%%%%%%%%% Allow for external referencing

\newcommand*{\externalReferent}[1]{
  \newtoggle{#1}
  \iftoggle{verbose}{
    \IfFileExists{../#1/main.aux}{
      \@addtofilelist{../#1/main.tex}
      \@addtofilelist{../#1/main.aux}%
      \externaldocument{../#1/main}%
      \settoggle{#1}{true}
    }%
    {\typeout{No file #1.}
    \settoggle{#1}{false}
    }
  }{}
}

% Argument 1: The target git directory (e.g. 'core')
% Argument 2: What to call that directory (e.g. 'the core rules')
% Argument 3: Which label you're referring to
\newcommand\exRef[3]{%
\iftoggle{#1}{\footnote{\nameref{#3}: #2, \autopageref{#3}.}}%
{}%
}

%%%%%%%%%% Section Headers %%%%%%%%%%

%%% Allow quotes under part headers
\let\old@endpart\@endpart
\renewcommand\@endpart[1][]{%
\begin{quote}#1\end{quote}%
\old@endpart}

%%%%%%%%%% Give higher penalty to ~
% The ~ character usually functions as a space with a high penalty for line breaks.
% This stops the line breaks altogether, so we can write 'Athletics 3', without a line-break between the Skill and the number.

\DeclareRobustCommand{\nobreakspace}{%
   \leavevmode\nobreak\ }
\catcode `\~=13
\def~{\nobreakspace{}}

%%%%% Make table of contents two column

\renewcommand\tableofcontents{%
\begin{multicols}{2}

    \@starttoc{toc}%
\end{multicols}
}
% and make repeating function
\newcommand{\Repeat}[1]{%
  \expandafter\@Repeat\expandafter{\the\numexpr #1\relax}%
}

\def\@Repeat#1{%
    \ifnum#1>0
        \expandafter\@@Repeat\expandafter{\the\numexpr #1-1\expandafter\relax\expandafter}%
    \else
        \expandafter\@gobble
    \fi
}
\def\@@Repeat#1#2{%
    \@Repeat{#1}{#2}#2%
}

% This allows us to compare two strings. What other wonders will LaTeX bring in the future?  Perhaps subtraction syntax one day.
\ExplSyntaxOn
\NewExpandableDocumentCommand{\ifStrSame}{mmmm}
 {
  \str_if_eq:eeTF { #1 } { #2 } { #3 } { #4 }
 }
\ExplSyntaxOff

% This function divides a number by two, and rounds it up.
\newcommand\roundUp[1]{
  \ifodd\value{#1}
    \stepcounter{#1}
  \fi
  \divide\value{#1} by 2
  \addtocounter{#1}{0}% Think this line's pointless? Try removing it and seeing what happens - I dare you.
}

\newcommand{\chapnumfont}{
  \fontsize{50}{0}
  \selectfont
}

% change bullet points

\renewcommand{\labelitemi}{\ding{250}}
\renewcommand{\labelitemii}{\ding{254}}

%%%%%%%%%% Encounter Numbers

\newcounter{encnum}
\setcounter{encnum}{1}
\newcommand{\sqarea}{town}

\newcommand{\headingtype}{CHAPTER}

\newcommand\outline[2][7]{\contour[#1]{black}{\textcolor{white}{#2}}}
\contourlength{0.1em}

\newcommand{\pic}[1]{
  \noindent%
  \IfFileExists{images/#1.svg}{%
    \noindent\includesvg[width=\linewidth]{images/#1}
  }{%
    \includegraphics[width=\linewidth]{images/#1.jpg}
  }
  \label{#1}
}

\newcommand{\sidepic}[3][5]{
  \needspace{4cm}
  \begin{wrapfigure}{R}{.#1\linewidth}
  \noindent%
  \IfFileExists{images/#2.svg}{%
    \includesvg[width=\linewidth]{images/#2}
  }{
    \includegraphics[width=\linewidth]{images/#2.jpg}
  }
  #3
  \end{wrapfigure}
  \label{#2}
}

\newcommand{\widePic}[2][b]{
  \begin{figure*}[#1!]
    \IfFileExists{images/#2.svg}{
      \includesvg[width=\textwidth]{images/#2}
    }{
      \tcbincludegraphics[
      blankest,
      before upper={\parindent0pt},
      boxrule=0mm,
      finish fading vignette={size=0.02\textwidth},
      ]{images/#2.jpg}
    }
    \label{#2}
  \end{figure*}
}

\newcommand\mapLegend[4]{
  \node [black, font=\bfseries] at (0.#2,0.#3) {#4 #1};
}

\newcommand\mapPic[4][\Huge]{
  \begin{figure*}[#2!]
  \begin{tikzpicture}[every shadow/.style={
      shadow blur invert,
      shadow xshift=-1pt,
      shadow yshift=-3pt
  }]
      \node[anchor=south west,inner sep=0] (image) at (0,0) {\pic{#3}};
      \begin{scope}[
          x={(image.south east)},
          y={(image.north west)}
      ]
          \foreach \mNum/\mX/\mY in {#4}{
            \mapLegend{\outline{\mNum}}{\mX}{\mY}{#1}
          }
      \end{scope}
  \end{tikzpicture}
  \label{#3}
  \end{figure*}
}

\newcommand\smolMapPic[3][\Huge]{
  \noindent
  \begin{tikzpicture}
      \node[anchor=south west,inner sep=0] (image) at (0,0) {\pic{#2}};
      \begin{scope}[
          x={(image.south east)},
          y={(image.north west)}
      ]
          \foreach \mNum/\mX/\mY in {#3}{
            \mapLegend{\outline{\mNum}}{\mX}{\mY}{#1}
          }
      \end{scope}
  \end{tikzpicture}
  \label{#2}
}


\newcounter{blingNo}
\setcounter{blingNo}{0}


% Define the 'ornamentedbox' environment

% Wiggly Borders
\tikzset{
  use path for main/.code={%
    \tikz@addmode{%
      \expandafter\pgfsyssoftpath@setcurrentpath\csname tikz@intersect@path@name@#1\endcsname
    }%
  },
  use path for actions/.code={%
    \expandafter\def\expandafter\tikz@preactions\expandafter{\tikz@preactions\expandafter\let\expandafter\tikz@actions@path\csname tikz@intersect@path@name@#1\endcsname}%
  },
  use path/.style={%
    use path for main=#1,
    use path for actions=#1,
  }
}

\tikzset{ornamented frame inner/.style={color=\pageSideColor,
                                        line width=2pt},
         ornamented frame outer/.style={color=black,
                                        line width=3pt}}

\tcbsubskin{ornamented}{empty}{
  skin first=ornamented,  skin last=ornamented,
  title engine=standard,
  colbacktitle=white,
  frame code={
    % Account for the line widths in order not to draw beyond the bounding
    % box---except for a few very small details for which this is intentional.
    \coordinate (north west) at ([shift={(1.5pt,-1.5pt)}]frame.north west);
    \coordinate (north east) at ([shift={(-1.5pt,-1.5pt)}]frame.north east);
    \coordinate (south east) at ([shift={(-1.5pt,1.5pt)}]frame.south east);
    \coordinate (south west) at ([shift={(1.5pt,1.5pt)}]frame.south west);
    %
    \foreach \xoffset/\point in {34pt/north west, -34pt/north east,
                                  34pt/south west, -34pt/south east} {
      \fill[color=\pageOppositeColor]
        ([xshift=\xoffset]\point) circle[radius=2.5pt];
    }
    %
    \path[name path=ornament 1]
                                 ([yshift=-4pt]north west)
      [rounded corners=0.5pt] -- ++(23pt,0)
      [rounded corners=2pt]   -- ++(3pt,-4pt)
                              -- ([shift={(-26pt,-8pt)}]north east)
      [rounded corners=0.5pt] -- ++(3pt,4pt)
      [rounded corners=4pt]   -- ([yshift=-4pt]north east)
                              -- ([yshift=4pt]south east)
      [rounded corners=0.5pt] -- ++(-23pt,0)
      [rounded corners=2pt]   -- ++(-3pt,4pt)
                              -- ([shift={(26pt,8pt)}]south west)
      [rounded corners=0.5pt] -- ++(-3pt,-4pt)
      [rounded corners=4pt]   -- ([yshift=4pt]south west)
                              -- cycle;
    %
    \path[rounded corners=0.5pt, name path=ornament 2]
                                 ([yshift=-20pt]north west)
                              -- ++(-4pt,3pt)
                              -- ++(0,4pt)
               to[out=0, in=-90] ([shift={(8pt,0pt)}]north west)
                              -- ([shift={(34pt,0pt)}]north west)
                              -- ([shift={(-8pt,0pt)}]north east)
             to[out=-90, in=180] ([shift={(4pt,-13pt)}]north east)
                              -- ++(0,-4pt)
                              -- ++(-4pt,-3pt)
                              -- ([yshift=20pt]south east)
                              -- ++(4pt,-3pt)
                              -- ++(0,-4pt)
              to[out=180, in=90] ([shift={(-8pt,0pt)}]south east)
                              -- ([shift={(8pt,0pt)}]south west)
                to[out=90, in=0] ([shift={(-4pt,13pt)}]south west)
                              -- ++(0,4pt)
                              -- ++(4pt,3pt)
                              -- cycle;
    %
    \draw[ornamented frame outer, use path=ornament 1];
    \draw[ornamented frame outer, use path=ornament 2];
    \draw[ornamented frame inner, use path=ornament 1];
    \draw[ornamented frame inner, use path=ornament 2];
    %
    \iftoggle{creatureBox}{
      \node at ([xshift=-25pt,yshift=\thedr+5pt] south east)
        {\ifnum\value{dr}>2
          \addtocounter{dr}{7}\multiply\value{dr} by 2\includesvg[width=\thedr pt]{config/images/l1}
          \hspace{-30pt}
        \fi
     };
    \node at ([xshift=-20pt,yshift=-\themp] north east)
      {\ifnum\value{mp}>1
        \addtocounter{mp}{2}
        \multiply\value{mp} by 2
        \includesvg[angle=270,width=\themp pt]{config/images/b1}
        \hspace{-20pt}
      \fi
      };
    \node at ([xshift=-5pt,yshift=35pt] south west)
      {\ifnum\value{att}>7
        \addtocounter{att}{-4}
        \multiply\value{att} by 2
        \includesvg[angle=340,width=\theatt pt]{config/images/s1}
        \hspace{-30pt}
      \fi
    };
    }{}
  }
}

% These parameters---especially those related to geometry---are better located
% here in a style than in the subskin definition (see the Subskins section of
% the tcolorbox manual).
\tcbset{ornamented/.style={skin=ornamented,
  toptitle=14.5pt,
  top=15pt,
  bottom=9.5pt,
  fontupper={\iftoggle{verbose}{\normalsize}{\footnotesize}},
  coltitle=black,
  }
}

% Convenient style to use with a tcolorbox preceded by text (or anything),
% when one wants to prevent any page break before the tcolorbox.
\tcbset{skip and no break/.style={
  before={\par\nopagebreak\vspace{2ex}\noindent}}
}

% Style suitable for an “on line” (in the middle of a paragraph)
% 'ornamentedbox'.
\tcbset{my on line/.style={
  capture=hbox, tcbox raise base, top=14pt, bottom=14pt,
  before={\kern 5pt}, after={\kern 5pt}}
}

%%%%% TColorBox Basic Setup %%%%%

\tcbset{enhanced,
ornamented,
left=3pt,
right=3pt,
code={\rowcolors{2}{}{gray!10}},
before upper={\parindent15pt},
fonttitle=\bfseries,coltitle=black,attach boxed title to top center=
{yshift=-0.25mm-\tcboxedtitleheight/2,yshifttext=-2mm-\tcboxedtitleheight/2},
boxed title style={boxrule=-0.5mm,
frame code={ \path[tcb fill frame] ([xshift=-4mm]frame.west)
-- (frame.north west) -- (frame.north east) -- ([xshift=4mm]frame.east)
-- (frame.south east) -- (frame.south west) -- cycle; },
interior code={ \path[tcb fill interior] ([xshift=-2mm]interior.west)
-- (interior.north west) -- (interior.north east)
-- ([xshift=2mm]interior.east) -- (interior.south east) -- (interior.south west)
-- cycle;}
}
}


\newtcolorbox{boxtext}[1][]{
  ornamented,
  colback=white,
  fonttitle=\scshape, #1
  }

\newcommand{\sidebox}[2][23]{
  \iftoggle{verbose}{
    \needspace{4em}
    \begin{wrapfigure}{R}{.#1\textwidth} 
    #2
    \end{wrapfigure}%
  }{
    #2
    
  }%
}

% Chapter Heading Color
\colorlet{chapnumcol}{black!100}

%%%%% Section Formatting %%%%%

\newcommand{\frontpage}[3]{
  \iftoggle{verbose}{
  \begin{titlepage}
    \centering
    \vspace{2cm}
    {\scshape\Huge\bfseries #1\par}
    \vspace{1cm}
    \IfFileExists{images/#3.jpg}{
      \includegraphics[width=0.6\textwidth]{images/#3.jpg}\par\vspace{1cm}
    }{}
    {\Large #2\par}
    \vspace{1.5cm}
    {\large This edition bound on \today\par}
  
  \end{titlepage}
  \cleardoublepage
  }{}
}

\newcommand\shiftColours{
  \ifnum\value{pageDarkness}<80
    \addtocounter{pageDarkness}{7}
    \ifnum\value{pageDarkness}>30
      \setcounter{pageAlt}{0}
    \fi
  \else
    \addtocounter{pageDarkness}{-60}
    \setcounter{pageAlt}{100}
  \fi
}

\titleformat{\chapter}[display]
{\bfseries}
{%
  \shiftColours
  \hspace*{-1.5em}
\begin{tikzpicture}
  \node[minimum width=\linewidth+3em, text=\pageOppositeColor, fill=\pageSideColor, inner sep=1, outer sep=0, anchor=south] (rectinit) {\Huge \headingtype};
 \node[minimum width=.75\textwidth, text=white, inner sep=3, outer sep=0, anchor=south west, text width=.75\textwidth, align=right] at (rectinit.south west) (chapname) {};
  \node[minimum width=.25\textwidth, inner sep=-5, outer sep=0, anchor=south west, text width=.25\textwidth, align=left] at (chapname.south east) {\chapnumfont\textcolor{chapnumcol}{\Roman{chapter}}};
\end{tikzpicture}}
{0pt}
{\Huge}


\newcommand\titlebar{%
\tikz[baseline,trim left=1em,trim right=8em] {
    \fill [\pageSideColor] (6.6em,1.03em) rectangle (\linewidth+1.8em,-.38em);
    \node [
        fill=\pageSideColor,
  text= \pageOppositeColor,
        anchor= base east,
        rounded rectangle,
        minimum height=1.5em] at (7.3em,-0.05em) {
        \textbf{\arabic{section}}
    };
}%
}
\titleformat{\section}%
  {\large\needspace{12em}}%
  {\titlebar}%
  {0.1cm}%
  {\textcolor{\pageOppositeColor}}

\renewcommand*{\thesection}{\arabic{section}}

\titleformat{\subsection}
{\needspace{10em}\normalfont\center\large\bfseries}{\thesubsection}{1em}{}[\textcolor{\pageSideColor}{\titlerule}\vspace{1ex}\setcounter{list}{0}]

%
\titleformat{\subsubsection}
{\needspace{4em}\normalfont\normalsize\bfseries}{\thesubsubsection}{1em}{}

%%%%% Character Sheet Tracker

    \newcounter{track}
    \setcounter{track}{18}
    \newcommand{\tracker}{\center\noindent\iftoggle{examplecharacter}{\iftoggle{bestiarychapter}{}{\ifnum\value{track}=\value{spd}$\Rightarrow$ \fi}}{}\arabic{track}\addtocounter{track}{-1}\vspace{.54cm}

    }

%%%%% NPC Names

\newcommand{\name}{}
\newcommand{\NPCdescription}{}
\newcommand{\mannerism}{}
\newcommand{\archetype}{}
\newcommand{\npcsymbol}{}
\newcommand{\npc}[2]{\settoggle{personality}{false}\renewcommand{\name}{#1 #2}\renewcommand{\npcsymbol}{#1}}
\newcommand{\NPC}[5]{\renewcommand{\name}{#1 #2}
\renewcommand{\npcsymbol}{#1}
\settoggle{personality}{true}
\renewcommand{\NPCdescription}{#3}
\renewcommand{\mannerism}{#4}
\renewcommand{\archetype}{#5}
}

%%%%%%%%%%%%%%%%%%%% TOGGLES %%%%%%%%%%%%%%%%%%%%

\newtoggle{verbose}
\settoggle{verbose}{true}
\newtoggle{personality}
\settoggle{personality}{false}

% This toggle tells you if this is just one creature or a team.
\newtoggle{team}
\settoggle{team}{false}

\iftoggle{verbose}{
  \setcounter{tocdepth}{1}
  \setcounter{secnumdepth}{1}
}


%%%%%%%%%%%%%%%%%%%% RANDOM NUMBERS %%%%%%%%%%%%%%%%%%%%

\newcounter{r4}
\setcounter{r4}{\day}
\addtocounter{r4}{1}
  \whileboolexpr{
    test {\ifnumcomp{\value{r4}}{>}{4}}
  }
  {\addtocounter{r4}{-3}}

\newcounter{r2}
\setcounter{r2}{\value{r4}}
\newcounter{r2b}
  \setcounter{r2b}{\value{r2}}
  \addtocounter{r2b}{-1}
\newcounter{r2c}
\setcounter{r2c}{2}
\newcounter{r3}
\setcounter{r3}{\month}
  \divide\value{r3} by 4
\newcounter{r3b}
  \setcounter{r3b}{\value{r4}}
  \addtocounter{r3b}{-1}
\newcounter{r3c}
  \setcounter{r3c}{1}
\newcounter{r4b}
  \setcounter{r4b}{\day}
\newcounter{r12}
\setcounter{r12}{\month}
\newcounter{enc}
\newcounter{list}
\newcounter{spelllevel}
\setcounter{spelllevel}{0}

\newcounter{age}
\setcounter{age}{1}
\newcounter{gold}
\setcounter{gold}{\day}
\setcounter{enc}{0}

\newcommand{\randomtwo}{%
  \ifnum\value{r2}>1%
    \setcounter{r2}{1}%
  \else%
    \stepcounter{r2}%
  \fi%
  \setcounter{enc}{\value{r2}}%
}

\newcommand{\randomtwoB}{%
  \ifodd\value{r3}%
    \setcounter{r2b}{1}%
  \else%
    \setcounter{r2b}{2}%
  \fi%
}

\newcommand{\randomtwoC}{%
  \ifnum\value{r2c}>1%
  \setcounter{r2c}{1}\else%
  \stepcounter{r2c}%
  \fi%
}

\newcommand{\randomthree}{%
  \ifnum\value{r3}>2%
    \setcounter{r3}{1}%
  \fi%
  \ifnum\value{r3}<1%
    \setcounter{r3}{2}%
  \fi%
  \stepcounter{r3}%
  \setcounter{age}{\value{r3}}%
}

\newcommand{\randomthreeB}{%
  \ifnum\value{r3b}>2%
    \setcounter{r3b}{1}%
  \else%
    \stepcounter{r3b}%
  \fi%
  \ifnum\value{r3b}<1%
    \setcounter{r3b}{3}%
  \fi%
}

\newcommand{\randomthreeC}{%
  \ifnum\value{r3c}>2%
    \setcounter{r3c}{1}
  \else%
    \stepcounter{r3c}%
  \fi%
}

\newcommand{\randomfour}{%
  \ifnum\value{r4}>3%
    \setcounter{r4}{2}%
  \else%
    \ifnum\value{r4}<1%
      \setcounter{r4}{1}%
    \fi%
  \fi%
  \stepcounter{r4}%
  \setcounter{track}{\value{r4}}%
}

\newcommand{\randomfourB}{%
  \ifnum\value{r4b}>3%
    \setcounter{r4b}{1}%
  \else%
    \stepcounter{r4b}%
  \fi%
}

\newcommand{\randomdozen}{%
  \randomfourB%
  \setcounter{r12}{0}%
  \addtocounter{r12}{\value{r4b}}%
  \addtocounter{r12}{\value{r3c}}%
  \addtocounter{r12}{\value{r3}}%
  \addtocounter{r12}{\value{r4}}%
}

%%%%%%%%%%%%%%%%%%%% LAYOUT %%%%%%%%%%%%%%%%%%%%
\makeindex

\raggedbottom

 \newif\ifafterpar
 \newcommand\afterparnoindent{%
   \afterpartrue
   \everypar{%
     \ifafterpar
       \afterparfalse
       {\setbox\z@\lastbox}%
     \else
       \everypar{}%
     \fi}}

% Make floats hug the text.
\setlength\intextsep{0em}

\renewcommand\tabularxcolumn[1]{m{#1}}
\newcolumntype{Y}{>{\centering\arraybackslash}X}
\newcolumntype{L}{>{\raggedright\arraybackslash}X}

\newcommand{\currentsphere}{magic}

\newcommand{\sphere}[1]{%
  \setcounter{spelllevel}{0}%
  \renewcommand{\currentsphere}{#1}%
  \index{#1}%
  \section{\currentsphere}
}%

\newcommand{\spelllevel}{%
  \needspace{15em}
  \refstepcounter{spelllevel}%
  \subsection{\currentsphere~ Level \arabic{spelllevel}}%
}

\newcommand{\enhancement}[3]{%
  \paragraph[(#1) #2: #3]{(#1) Enhancement -- #2:}%
  \index{Enhancement!#2}%
}

\newcommand{\magicitem}[7]{%
  \vspace{1em}\needspace{1em}\noindent\textbf{#1}%
  \index{Magical Item!#1}

  \noindent
  \textit{Spells: #2, }%
  \textit{Path: #3, }%
  \textit{Duration: #4, }%
  \textit{Type: #5, }%
  \textit{Potency: +#6, }%
  \textit{MP: #7}%
  % Type can be 'Pocket Spell', 'Talisman', or 'Artefact'.
  \needspace{2em}%
}

\newcommand{\manalake}[8]{
  \subsection{#1 (Level #8)}

  \textit{Spells: #2, }\textit{Path: #3, }\textit{Duration: #4, }\textit{Type: #5, }\textit{Potence: #6, }\textit{#7 MP}% Type can be 'pocket spell', 'magical item', or 'artefact'.
  \index{Mana Lakes!#1}
  \vspace{.3em}
}

\newcommand{\spell}[4]{
  \subsubsection[\textbf{#1}: #4. (\textit{#3})]{#1}
  \index[spells]{\textbf{#1}: #4. (\currentsphere\ Level \arabic{spelllevel}, Type: #2, Skill: #3)}

  {\small\underline{\it Type: #2}, \iftoggle{verbose}{}{\\ }\underline{Skill: #3}}
  \vspace{.5em}\afterparnoindent
}

% Toggles for knacks

%%%%%%%%%%%%%%%%%%%% Environments %%%%%%%%%%%%%%%%%%%%

\newenvironment{speechtext}{
  \begin{boxtext}\it
\begin{quotation}\noindent}%
{\end{quotation}
\end{boxtext}%
}

\newenvironment{rolltable}%
{\vspace{.3cm}\begin{tabular}{|lp{.8\textwidth}}


Roll & Result \\
\hline

}%
{\end{tabular}}


\NewDocumentEnvironment{exampletext}%
  { O{\needspace{2em}\vspace{.3cm}\rule{.9\linewidth}{0.2pt}\vspace{.3em}} +b }%
  {\iftoggle{verbose}{#1

  \it
  #2}{}}
  {
    \iftoggle{verbose}{

    \rule{.9\linewidth}{0.2pt}

    }{}%
  }

\newcommand\sideBySide[2]{
  \end{multicols}
  \vspace{-1em}
  \begin{tcolorbox}[sidebyside,bicolor,colback=white,colbacklower=black!5!white]
  {#1}
  \tcblower
  {\it #2}
  \end{tcolorbox}
  \begin{multicols}{2}
}

\newcommand\boxPair[3][b]{
  \begin{figure*}[#1!]
    \begin{multicols}{2}
    #2
    \vfill\null
    \columnbreak
    #3
    \end{multicols}
  \end{figure*}
}

\newtcolorbox{xpchart}[1]{
  tabularx={l|X},
  fonttitle=\small,
  adjusted title=XP Rewards for #1,
  bottom=10pt,
  left=3pt,
  right=3pt,
  code={\rowcolors{3}{}{gray!10}}
  }

% this shows encounters, and the two counters below show the encounter number

\newtcolorbox[use counter=enc, use counter=list]{encounters}[1]{
  ornamented,
  adjusted title=Encounters in #1,
  tabularx={XXp{.6\textwidth}},
  bottom=10pt,
  left=3pt,
  right=3pt,
  code={\index{Encounter Tables}\rowcolors{2}{}{gray!10}\setcounter{enc}{19}\setcounter{list}{18}}}

\newcommand{\li}{\addtocounter{enc}{-1}\arabic{enc}&}
\newcommand{\lii}{\addtocounter{list}{-1}\arabic{list}&}

\newtcolorbox{boxtable}[1][cX]{
  tabularx={#1},
  top=10pt,
  bottom=10pt,
  left=3pt,
  right=3pt,
  code={\rowcolors{2}{}{gray!10}\needspace{2em}}
  }

\newtcolorbox{nametable}[2][cX]{
  tabularx=#1,
  adjusted title=#2,
  bottom=1em,
  left=3pt,
  right=6pt,
  code={\rowcolors{2}{}{gray!10}\needspace{1em}}
  }

\newtcolorbox{rollchart}{
  tabularx={cX},
  top=10pt,
  bottom=10pt,
  left=3pt,
  right=3pt,
  after={\afterparnoindent},
  code={\rowcolors{2}{}{gray!10}\needspace{2em}}
  }

\newtcolorbox{xpbox}[1]{
  tabularx={lX},
  bottom=10pt,
  left=3pt,
  right=3pt,
  top=10pt,
  code={\rowcolors{2}{}{gray!10}},
  equal height group=#1
  }

%%%%%%%%%%%%%%%%%%% COMMANDS %%%%%%%%%%%%%%%%%%%%

\newcommand{\story}[2]{%
  \subsubsection{#2}
  \textbf{Cost:} #1
  \\
  \afterparnoindent
}

\newcommand{\best}[2][\A]{
  \subsubsection[#2]{#1 #2}
  \index{Antagonists!#2}
}

\newcommand{\startingCondition}[1]{
  \ifnum\value{list}<95
    \item
    #1
  \fi
}

\newcommand{\mapentry}[2][]{
  \needspace{2em}
  \refstepcounter{list}
  \subsubsection[#2]{
    \arabic{list}: #2
  }
  \label{#1}
}

%%%%% Side Quests

% the first side quest gets a ticked box in the toc.
% the rest get an empty box, so the GM can tick it once it's ready.

\newtoggle{firstsq}
\settoggle{firstsq}{true}

\newcommand{\sqtoc}{\printcontents[\sqarea]{l}{2}{\section*{Summaries}\setcounter{tocdepth}{3}}}

% Change the tocdepth from 2 to 3 in order to output a miniature table of contents on all side quests
\newcommand{\sqminitoc}{

  \begin{figure*}[t]
  
  \begin{tcolorbox}[ornamented,adjusted title={Summary: \sqName}]
  \vspace{-1em}
  \printcontents[sq]{l}{2}{\setcounter{tocdepth}{3}}
  
  \end{tcolorbox}
  
  \end{figure*}
}

\newcounter{sqNo}
\newcommand{\sqName}{}

\newcommand{\sidequest}[1]{%
  \renewcommand{\sqName}{#1}
  \resumecontents[\sqarea]
  \subsection{\sqName}
  \stopcontents[\sqarea]
  \settoggle{firstsq}{true}
  \setcounter{sqNo}{0}
}

\newcommand{\sqpart}[3]{
  \refstepcounter{sqNo}
  \resumecontents[#1]
  \subsubsection[%
    \arabic{sqNo} -- %
    \iftoggle{firstsq}{\sqr}{\sqn}%
    #2 -- #3]%
    {(#1) #2}
  \stopcontents[#1]\settoggle{firstsq}{false}
}

%%%%% Character Sheet Commands

\newcounter{statCircles}
\newcounter{statDots}

\newcommand\statCircle{\textbf{\Circle}}
\newcommand\statDot{\textbf{\CIRCLE}}
\newcommand\currentCircle{}
\newcommand{\weeline}{\line(1,0){30} \hspace{.6cm}}

\newcommand\attributeDisplay[2]{
\setcounter{enc}{-5}
\setcounter{statDots}{\value{#2}}
#1 &
\raisebox{2pt}{--}
\Repeat{9}{&
\ifnum\value{enc}<\value{statDots}\renewcommand\currentCircle{\statDot}\else\renewcommand\currentCircle{\statCircle}\fi% This decides to use either a statDot (showing a stat value) or an empty statCircle (showing a potential dot)
\ifnum\value{enc}=-1\Large\currentCircle\else\raisebox{2pt}{\currentCircle}\fi% Most circles need a raisebox to appear nicely on a line. The dot representing '0' is large, and doesn't need raised.
\stepcounter{enc}
}%
&\raisebox{2pt}{+}
\\
}
\newcommand{\attributecircles}[1][-5]{\raisebox{0pt}{--}%
\setcounter{statDots}{#1}
\setcounter{statCircles}{0}%
\addtocounter{statCircles}{-#1}%
\ifnum#1>-1%
\Repeat{4}{\statDot}%
\else%
\Repeat{\value{statDots}}{\statDot}%
\Repeat{\value{statCircles}}{\statCircle}%
\fi%
\raisebox{-2pt}{\Large\ifnum#1>-1\statDot\else\statCircle\fi}%
\Repeat{4}{\statCircle}\raisebox{0pt}{ +}}
\newcommand{\skill}[1]{
  \setcounter{statCircles}{3}
  \addtocounter{statCircles}{-\value{#1}}
  #1 \dotfill & \Repeat{\value{#1}}{\statDot}\Repeat{\value{statCircles}}{\statCircle}\\
}

\newcommand{\sphereSkill}[2]{
  \setcounter{statCircles}{5}
  \addtocounter{statCircles}{-#2}
  #1 \dotfill \Repeat{#2}{\statDot}\Repeat{\value{statCircles}}{\statCircle}
}

\newcommand\hint[1]{%
  \iftoggle{examplecharacter}{}%
  {\small\textcolor{gray}{(#1)}}
}