\ProvidesClass{TUedissertation}

%parameter: chapter. if set, the document will only contain that chapter (given that that chapter is included using the includeChapter command).
%(used for quick compilation)
%parameter: bleed. Prints a bleed line.
\RequirePackage{kvoptions}
\DeclareStringOption[0]{chapter}
\DeclareBoolOption{bleed}

%prevent leaking of these options to other packages
\DeclareLocalOptions{chapter,bleed}

\ProcessKeyvalOptions*

\LoadClass[twoside]{book}
\usepackage[paperwidth=172mm, paperheight=244mm, outer=22mm, inner=25mm, top=27mm, bottom=22mm]{geometry}

\newif\if@bleed
\ifTUedissertation@bleed
    \@bleedtrue
\else
    \@bleedfalse
\fi

\RequirePackage[british]{babel}
\RequirePackage{fancyhdr}
\RequirePackage{xcolor}
\RequirePackage{tikz}
\RequirePackage{titletoc}
\RequirePackage{makeidx}
\RequirePackage{tikzpagenodes}

\def\titlefont{\rmfamily}
\def\titleshape{\scshape}
\def\titlestyle{\titlefont\titleshape\bfseries}

\definecolor{anthracite}{cmyk}{0,0,0,0.8}
\definecolor{thumb}{RGB}{195,230,252}
\definecolor{thumbNumber}{RGB}{11,83,206}

%% Process options for partial compilation
    \newif\iffull
    \ifnum \TUedissertation@chapter=0
        \fulltrue
    \else
        \fullfalse
    \fi

%% keep track of the number of chapters
    \RequirePackage{totcount}
    \regtotcounter{chapter}
    \RequirePackage{pdftexcmds}
    % Notice: the macros \chapters (total number of chapters) and others are only defined after \begin{document}, as they rely on the .aux file, which is only read then.
    \AtBeginDocument{
        \ifnum \totvalue{chapter} > -1
            %this is the second compile run, so the total number of chapters is known
            \def\chapters{\totvalue{chapter}}
            \pgfmathtruncatemacro\chapterNameBelowUpToChapter{\chapters/2}
            \pgfmathtruncatemacro\chapterPlaces{\chapters+1}
        \else
            %this is the first compile run, so the total number of chapters is not known yet
            \def\chapters{2}
            \def\chapterNameBelowUpToChapter{1}
            \def\chapterPlaces{4}
        \fi
    }

%% Keep track of back matter
    \newif\ifbackmatter
    \backmatterfalse
    \makeatletter
    \g@addto@macro{\backmatter}{
        \backmattertrue
    }
    \makeatother

%% Include chapters and hide them if necessary
    \newsavebox\mybox
    \RequirePackage[explicit]{titlesec}
    \titleformat{\chapter}[display]{}{}{0pt}{\chapterPage{\thechapter}{#1}}
    \titleformat{name=\chapter,numberless}[display]{}{}{0pt}{\chapterPage{}{#1}}
    \titlespacing*{\chapter}{0pt}{0pt}{0pt}

    %% Remove the header and page number on empty pages.
    \def\cleardoublepage{%
        \clearpage%
        \if@twoside%
            \ifodd\c@page%
            \else%
                \thispagestyle{plain}%
                \vspace*{\fill}%
                \newpage%
            \fi%
        \fi%
    }

%set up the coordinates for a thumb
    \newcommand{\topRightThumb}{
        \coordinate (topRightThumbTop) at (current page text area.north -| current page.east) {};
        \coordinate (topRightThumbBottom) at ($(current page text area.south -| current page.east) + (0pt, \thumbheight)$) {};
        \ifbackmatter
            \coordinate (top right) at ($(topRightThumbBottom)$) {};
        \else
            \coordinate (top right) at ($(topRightThumbTop)!\value{chapter}/\chapterPlaces!(topRightThumbBottom)$) {};
        \fi
        \coordinate (bottom left a) at ($(top right)-(0,\thumbheight)$);
        \coordinate (bottom left b) at ($(current page text area.north east)+(\thumbhspace,0cm)$);
        \coordinate (bottom left) at (bottom left a -| bottom left b);
        %make sure that the thumb starts off the page such that the edge and its rounded corners are not visible
        \coordinate (top right 2) at ($(top right)+(\thumbedge,0pt)$);
    }

    \newcommand{\topLeftThumb}{
        \coordinate (topLeftThumbTop) at (current page text area.north -| current page.west) {};
        \coordinate (topLeftThumbBottom) at ($(current page text area.south -| current page.west) + (0pt, \thumbheight)$) {};
        \ifbackmatter
            \coordinate (top left) at ($(topLeftThumbBottom)$);
        \else
            \coordinate (top left) at ($(topLeftThumbTop)!\value{chapter}/\chapterPlaces!(topLeftThumbBottom)$) {};
        \fi
        \coordinate (bottom right a) at ($(top left)-(0,\thumbheight)$);
        \coordinate (bottom right b) at ($(current page text area.north west)-(\thumbhspace,0cm)$);
        \coordinate (bottom right) at (bottom right a -| bottom right b);
        %make sure that the thumb starts off the page such that the edge and its rounded corners are not visible
        \coordinate (top left 2) at ($(top left)-(\thumbedge,0pt)$);
    }

%arguments: name, number, image
\newcommand{\chapterFigure}{\empty}
\newcommand*{\chapterPage}[2]{%
    \ifx\chapterFigure\empty%
    \else
        \begin{lrbox}{\mybox}
            \chapterFigure
        \end{lrbox}
    \fi
    % fancy chapter header
    \begin{tikzpicture}[remember picture,overlay]
        %normal tab
            \topRightThumb

            %% Draw the thumb index.
            \fill[fill=thumb,rounded corners=\thumbedge, draw=thumbNumber](top right 2) rectangle (bottom left);
            %% Print the chapter number at the center right in the thumb index.
            \coordinate (center left) at ($(bottom left)+(0pt,0.5\thumbheight)$);
            \node at (center left)[anchor=west,inner sep=2\thumbedge, text height=\thumbheight, text depth=0.55\thumbheight]{%
                \titlefont\bfseries\color{thumbNumber}%
                \fontsize{0.75\thumbheight}{0.75\thumbheight}\selectfont%
                #1\strut%
            };

        %bar over page
            \coordinate (bar top left) at ($(top right -| current page.north west) - (1cm, 0)$) {};
            \coordinate (bar bottom right) at ($(bottom left) - (0.5\thumbheight,0pt)$) {};
            \fill[fill=thumb, draw=thumbNumber, rounded corners=\thumbedge] (bar top left) rectangle (bar bottom right);
        %name in bar
            \node [anchor=east, text height=\thumbheight, text depth=0.55\thumbheight] at (center left -| bar bottom right) {%
                \titlefont\bfseries\color{thumbNumber}%
                \fontsize{0.75\thumbheight}{0.75\thumbheight}\selectfont%
                #2\strut%
            };
        %outline image
            \if\chapterFigure\empty%
            \else
                \ifnum\thechapter>\chapterNameBelowUpToChapter%
                    \node [anchor=south, draw=thumbNumber, rounded corners=\thumbedge] at ($(top right -| current page text area.north) + (0,1cm)$) {\usebox\mybox};
                \else
                    \node [anchor=north, draw=thumbNumber, rounded corners=\thumbedge] at ($(bottom left -| current page text area.north) + (0,-1cm)$) {\usebox\mybox};
                \fi
            \fi
    \end{tikzpicture}%
    \thispagestyle{empty}
    \clearpage
    \noindent
    \global\def\chapterFigure{\empty}
}

\newcommand*{\inputChapter}[1]{%
    \ifnum \TUedissertation@chapter=0%
        \input{#1}%
    \else%
        \ifnum \TUedissertation@chapter=\thechapter%
            \input{#1}%
        \fi%
    \fi%
}

\if@bleed%
    \newcommand*\cropmarks{%
        \begin{tikzpicture}[remember picture, overlay]
            \draw [draw=green] (current page text area.north east) rectangle (current page text area.south west);
        \end{tikzpicture}
        \ifodd\c@page%
            \begin{tikzpicture}[remember picture,overlay]
                %\draw ($(current page.north east)+(0mm,-3mm)$) -- ($(current page.north east)+(-2mm,-3mm)$);
                %\draw ($(current page.north east)+(-3mm,0mm)$) -- ($(current page.north east)+(-3mm,-2mm)$);
                %\draw ($(current page.south east)+(0mm,3mm)$) -- ($(current page.south east)+(-2mm,3mm)$);
                %\draw ($(current page.south east)+(-3mm,0mm)$) -- ($(current page.south east)+(-3mm,2mm)$);
                \draw [red] ($(current page.north west)+(0,-2mm)$) to ($(current page.north east)+(-2mm,-2mm)$) to ($(current page.south east)+(-2mm,2mm)$) to ($(current page.south west)+(0mm,2mm)$);
            \end{tikzpicture}%
        \else%
            \begin{tikzpicture}[remember picture,overlay]
                %\draw ($(current page.north west)+(0mm,-3mm)$) -- ($(current page.north west)+(2mm,-3mm)$);
                %\draw ($(current page.north west)+(3mm,0mm)$) -- ($(current page.north west)+(3mm,-2mm)$);
                %\draw ($(current page.south west)+(0mm,3mm)$) -- ($(current page.south west)+(2mm,3mm)$);
                %\draw ($(current page.south west)+(3mm,0mm)$) -- ($(current page.south west)+(3mm,2mm)$);
                \draw [red] ($(current page.north east)+(0,-2mm)$) to ($(current page.north west)+(2mm,-2mm)$) to ($(current page.south west)+(2mm,2mm)$) to ($(current page.south east)+(0mm,2mm)$);
            \end{tikzpicture}%
        \fi%
    }
\else
    \newcommand*\cropmarks{}
\fi%

%%% Thumb indices consist of white text on a rectangular colored background. The
%%% font-size is 75% of the size of thumb height.
\newif\ifthumb
\newlength\thumbheight
\setlength\thumbheight{24pt} %height of the thumb. Thumbs will distributed evenly over vertical space.
\newlength\thumbedge
\setlength\thumbedge{1pt} %rounded corners and edge width
\newlength\thumbhspace
\setlength\thumbhspace{1cm} %distance between page margin and start of thumb. Determines the 'width' of the thumb.

\newlength\thumbspacing
\setlength\thumbspacing{2\thumbheight}

\newlength\thumbnamesize
\setlength\thumbnamesize{10pt}

%% We need the TikZ library calc to calculate the coordinates of the thumb
%% indices.
\usetikzlibrary{calc}
\usetikzlibrary{fit}

%% The lthumb command prints the current chapter number in a thumb index on the
%% left (even) page.
\usepackage{etoolbox}
\newcommand*\lthumb{%
    \ifthumb\iffull%
        \begin{tikzpicture}[remember picture,overlay]
            \topLeftThumb

            %thumb
            \fill[fill=thumb,rounded corners=\thumbedge](top left 2) rectangle (bottom right);

            %% Print the chapter number at the center right in the thumb index.
            \coordinate (center right) at ($(bottom right)+(0pt,0.5\thumbheight)$) {};
            \node at (center right)[anchor=east,inner sep=2\thumbedge,text height=\thumbheight, text depth=0.55\thumbheight]{%
                \titlefont\bfseries\color{thumbNumber}%
                \fontsize{0.75\thumbheight}{0.75\thumbheight}\selectfont%
                \thechapter\strut%
            };

            %chapter name below/above thumb
            \ifnum\thechapter>\chapterNameBelowUpToChapter%
                \coordinate (center left) at ($(top left -| bottom right)+(0pt,0.5\thumbheight)$);
                \node at (center left)[anchor=south west,inner sep=2\thumbedge,rotate=90,text height=\thumbnamesize, text depth=0.55\thumbnamesize]{
                    \titlefont\bfseries\color{black}
                    \fontsize{\thumbnamesize}{\thumbnamesize}\selectfont
                    \Chaptername\strut
                };
            \else
                \coordinate (center right) at ($(bottom right)-(0pt,0.5\thumbheight)$);
                \node at (center right)[anchor=south east,inner sep=2\thumbedge,rotate=90,text height=\thumbnamesize, text depth=0.55\thumbnamesize]{
                    \titlefont\bfseries\color{black}
                    \fontsize{\thumbnamesize}{\thumbnamesize}\selectfont
                    \Chaptername\strut
                };
            \fi
        \end{tikzpicture}%
    \fi\fi%
}

%% rthumb draws a thumb index on the right (odd) page.
\newcommand*\rthumb{%
    \ifthumb\iffull%
        \begin{tikzpicture}[remember picture,overlay]
            \topRightThumb

            %thumb
            \fill[fill=thumb,rounded corners=\thumbedge](top right 2) rectangle (bottom left);

            %% Print the chapter number at the center right in the thumb index.
            \coordinate (center left) at ($(bottom left)+(0pt,0.5\thumbheight)$);
            \node at (center left) [anchor=west,inner sep=2\thumbedge,text height=\thumbheight, text depth=0.55\thumbheight]{%
                \titlefont\bfseries\color{thumbNumber}%
                \fontsize{0.75\thumbheight}{0.75\thumbheight}\selectfont%
                \thechapter\strut%
            };

            \ifnum\thechapter>\chapterNameBelowUpToChapter%
                \coordinate (center right) at ($(top right -| bottom left)+(0pt,0.5\thumbheight)$);
                \node at (center right)[anchor=north west,inner sep=2\thumbedge,rotate=90,text height=\thumbnamesize, text depth=0.55\thumbnamesize]{
                    \titlefont\bfseries\color{black}
                    \fontsize{\thumbnamesize}{\thumbnamesize}\selectfont
                    \Chaptername\strut
                };
            \else
                \coordinate (center left) at ($(bottom left)-(0pt,0.5\thumbheight)$);
                \node at (center left)[anchor=north east,inner sep=2\thumbedge,rotate=90,text height=\thumbnamesize, text depth=0.55\thumbnamesize]{
                    \titlefont\bfseries\color{black}
                    \fontsize{\thumbnamesize}{\thumbnamesize}\selectfont
                    \Chaptername\strut
                };
            \fi
        \end{tikzpicture}%
    \fi\fi%
}

%% Page style for empty pages.
\fancypagestyle{empty}{%
    \fancyhf{}
    \renewcommand*\headrulewidth{0pt}
    \renewcommand*\footrulewidth{0pt}
    \fancyhead{\cropmarks}
}

%% Page style for title pages.
\fancypagestyle{plain}{%
    \fancyhf{}
    \renewcommand*\headrulewidth{0pt}
    \renewcommand*\footrulewidth{0pt}
    \fancyhead{\cropmarks}
    %% page number as footer
    \fancyfoot[RO]{\titlefont\thepage}
    \fancyfoot[LE]{\titlefont\thepage}
}

%% Fancy style for the main matter.
\fancypagestyle{mainmatter}{%
    \fancyhf{}
    %% no bars on top or bottom
    \renewcommand*\headrulewidth{0pt}
    \renewcommand*\footrulewidth{0pt}
    %% Section name on the left (even) / right (odd) page.
    \fancyhead[LE]{\cropmarks\lthumb\titlefont\titleshape\nouppercase{\rightmark}}
    \fancyhead[RO]{\cropmarks\rthumb\titlefont\titleshape\nouppercase{\rightmark}}
    %% page number as footer
    \fancyfoot[RO]{\titlefont\thepage}
    \fancyfoot[LE]{\titlefont\thepage}
}

%%Fancy style for the back matter
\fancypagestyle{backmatter}{%
    \fancyhf{}
    %% Section name on the left (even) / right (odd) page.
    \fancyhead[LE]{\cropmarks\lthumb\titlefont\titleshape\nouppercase{\Chaptername}}
    \fancyhead[RO]{\cropmarks\rthumb\titlefont\titleshape\nouppercase{\Chaptername}}
    %% page number as footer
    \fancyfoot[RO]{\titlefont\thepage}
    \fancyfoot[LE]{\titlefont\thepage}
}

%% The mainmatter style is default for normal pages.
\pagestyle{mainmatter}

%keep chapter names for thumbs
\let\Chaptermark\chaptermark
\renewcommand{\chaptermark}[1]{\def\Chaptername{#1}\Chaptermark{#1}}
\renewcommand{\sectionmark}[1]{\markright{\thesection\ #1}}

%remove title from table of contents
\usepackage{tocloft}
\tocloftpagestyle{mainmatter}
\makeatletter
\renewcommand{\@cftmaketoctitle}{}
\makeatother
\iffull
    \setcounter{tocdepth}{1} %only include sections
\else
    \setcounter{tocdepth}{4} %only include sections
\fi

%references/bibtex
\usepackage[numbers]{natbib}
\iffull %if full, open Adobe Reader in two-page layout
    \usepackage[backref=page,hyperindex,pdfpagelayout=TwoPageRight]{hyperref}
\else
    \usepackage[backref=page,hyperindex,pdfstartview=]{hyperref}
    %\usepackage[backref=page,hyperindex,pdfpagelayout=TwoPageRight]{hyperref}
\fi
\usepackage{etoolbox}
\makeatletter
\patchcmd{\BR@backref}{\newblock}{\newblock(page~}{}{}
\patchcmd{\BR@backref}{\par}{)\par}{}{}
\makeatother
%add a dedicated chapter header to the bibliography
\let\Bibliography\bibliography
\renewcommand{\bibliography}[1]{
    \chapter{\bibname}
    \begingroup
        \def\chapter*##1{}
        \Bibliography{#1}
    \endgroup
}
