%\iffalse
%<*package>
%% \CharacterTable
%%  {Upper-case\A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%%   Lower-case\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%%   Digits\0\1\2\3\4\5\6\7\8\9
%%   Exclamation   \! Double quote  \" Hash (number) \#
%%   Dollar\$ Percent   \% Ampersand \&
%%   Acute accent  \' Left paren\( Right paren   \)
%%   Asterisk  \* Plus  \+ Comma \,
%%   Minus \- Point \. Solidus   \/
%%   Colon \: Semicolon \; Less than \<
%%   Equals\= Greater than  \> Question mark \?
%%   Commercial at \@ Left bracket  \[ Backslash \\
%%   Right bracket \] Circumflex\^ Underscore\_
%%   Grave accent  \` Left brace\{ Vertical bar  \|
%%   Right brace   \} Tilde \~}
%</package>
%\fi
% \iffalse
% Doc-Source file to use with LaTeX2e
% Copyright (C) 2016 Cameron Gray <c.gray@bangor.ac.uk>, all rights reserved.
% \fi
% \iffalse
%<*driver>
\documentclass[a4paper]{ltxdoc}

\usepackage[top=2cm, bottom=2cm, right=2cm, left=2in, headsep=14pt]{geometry}
\usepackage{fancyhdr,courier}
\fancyhead[R]{\texttt{bangorexam} - Exam Document Class}
\renewcommand{\headrulewidth}{0.5pt}
\fancyfoot{}
\fancyfoot[R]{\thepage}
\setlength\parindent{0pt}
\hyphenpenalty=10000
\hbadness=10000
\sloppy
\begin{document}
\DocInput{bangorexam.dtx}
\end{document}
%</driver>
%\fi
%\CheckSum{553}
%\RecordChanges
%\changes{v1.0}{2016/09/26}{Initial version.}
%\changes{v1.1}{2016/10/17}{Added two from four exam mode.}
%\changes{v1.1.1}{2016/10/18}{Emergency bugfix for etoolkit interaction on
%new documents.}
%\changes{v1.1.2}{2016/10/29}{Add page numbers and multiple choice elements.}
%\changes{v1.1.3}{2016/11/15}{Fixed question totals when using sub/subsubparts.}
%\changes{v1.1.4}{2016/11/21}{Fixed turn-over prompts given page numbering change.}
%\pagestyle{fancy}
%\title{Bangor University Computer Science Department\\ Exam Document Class}
%\author{Cameron Gray \texttt{<c.gray@bangor.ac.uk>}}
%\date{November 15, 2016}
%\maketitle
%
%\begin{abstract}
%Starting with the 2016/17 academic year, the Computer Science department at
%Bangor University have moved to \LaTeX\ for preparation of examination papers
%for all taught courses.  This was done for multiple reasons, including the
%reduction of burden on support staff.
%
%This package is the embodiment of that effort.  It includes all of the
%elements needed to produce an examination paper, including examiner's copies
%with solutions included.
%\end{abstract}
%
%\section{Usage - Class Options}
%The document class is activated (or loaded) using the usual \LaTeX\ command
%|\documentclass{bangorexam}|.  The class requires one of the following options
%to control which `style' of exam paper is produced.
%
%\oarg{ab} - produces a compulsory Section A and a `two from three' Section B
%exam.
%\oarg{twofour} - produces a single part `two from four' exam.
%
%The `answers' option controls the inclusion of solutions as part of the
%output.
%
%|\documentclass[ab]{bangorexam}| - produces the student form of a Section A/B
%exam paper.
%
%|\documentclass[ab,answers]{bangorexam}| - produces the examiner form of the
%paper.
%
%\section{Usage - Preamble Macros}
%The class includes several macros that must be added to the document's
%preamble.  These set important aspects such as the module code and title.
%
%\ \\
%
%\DescribeMacro{\school\marg{English name}\marg{Welsh name}} The name of the
%school setting this exam, provided in both English and Welsh.
%
%\ \\
%
%\DescribeMacro{\module\marg{code}\marg{full name}} The code (including the
%3-letter prefix) and full name of the module.
%
%\ \\
%
%\DescribeMacro{\examperiod\marg{resit\textbar{}s1\textbar{}s2}} Specifies
%the period of the exam, s1 for January/End of Semester 1, s2 for May/End of
%Semester 2, or resit for Supplementary exams (August Resits).
%
%\ \\
%
%\DescribeMacro{\timeallowed\marg{hours}} The amount of time allowed in hours.
%This should be the numerical part only, e.g. |\timeallowed{1\half}| or
%|\timeallowed{3}|.
%
%\ \\
%
%\section{Usage - Body Macros}
%Various macros exist to typeset the questions within the exam paper.  The
%macros listed here are provided to comply with Bangor University's style and
%formatting requirements.  Users should not adjust any formatting, font,
%header, footer, margin other other display parameters.  Please use |\emph{}|
%for italic text and |\textbf{}| for boldface fonts only.  The document class
%has been designed to support amsmath and amssymb mathematics typesetting
%with the conventional font.
%
%\ \\
%
%\DescribeMacro{\sectiona} \[\emph{Only applies when class option ab is
%active.}\] Begins the compulsory Section A.
%
%\ \\
%
%\DescribeMacro{\sectionb} \[\emph{Only applies when class option ab is
%active.}\] Begins the student-choice Section B.
%
%\ \\
%
%\DescribeMacro{\pointsdesc\marg{description}} Sets the suffix/descriptive text
%following a points value.  This defaults to an empty string, so 5 points would
%be rendered as |[5]|.  Setting |\pointsdesc{%}| would result in |[5%]|.
%
%\ \\
%
%\DescribeMacro{\guidance\marg{guidance text}} Sets a 'guidance' paragraph at
%the beginning of all question sections (at the start for two of four or both
%of section A and B if ab).
%
%\ \\
%
%\DescribeMacro{\guidancea\marg{guidance text}} Sets a 'guidance' paragraph at
%the start of section A only.
%
%\ \\
%
%\DescribeMacro{\guidanceb\marg{guidance text}} Sets a 'guidance' paragraph at
%the start of section B only.
%
%\ \\
%
%\section{Usage - Environments}
%There are three key environments |questions|, |parts|, and |solution|.
%These represent a numbered sequence of questions, parts and sub-parts of one
%question, and a solution/answer for a question respectively.
%
%\subsection{Questions Environment}
%All questions must be set within a questions environment.  You may add other
%items, such as explanations, images, scenarios etc., in this environment
%too.  The most simple questions environment is as follows:\\
%\begin{verbatim}
%\begin{questions}
%\end{questions}
%\end{verbatim}
%However, this will not actually produce any output.
%
%Questions must be added with use of the |\question| macro.
%
%\ \\
%
%\DescribeMacro{\question\oarg{points} Question Text} This macro can only
%be used within the Questions environment and is used to typeset a question.
%The optional argument sets the number of points/marks/percentage awarded for
%correct answers. See the |\pointsdesc| macro for customisation options.
%
%Whenever a new block is started (with |\begin{questions}|), the numbering
%begins at 1.  (Questions, at present, can only be labelled with Arabic
%numerals.)
%
%\subsection{Parts Environment}
%Within a question, examiners may wish to have multiple sub-questions (a.k.a
%parts).  This is provided for by the |\begin{parts}...\end{parts}|
%environment.  Each sub-question or part is handled with the part macro.
%
%\ \\
%
%\DescribeMacro{\part\oarg{points} Part Text} This macro can only be used
%within the parts environment and is used to typeset a sub-question. The
%optional parameter sets the number of points/marks/percentage awarded for
%correct answers.  See the |\pointsdesc| macro for customisation options.
%
%\ \\
%
%The parts environment may only be used within the questions
%environment, as in the example below:
%
%\begin{verbatim}
%\begin{questions}
%  \question Use the graph in Figure 1 to answer the following:
%  \begin{parts}
%\part Sub-question 1
%\part[10] Sub-question 2
%  \end{parts}
%\end{questions}
%\end{verbatim}
%
%\ \\
%
%Whenever a new block is started (with |\begin{parts}|), the sub-question
%numbering begins with a).  (Sub-questions, at present, can only be labelled
%with English letters).
%
%\subsection{Solution Environment}
%Following either a |\question| or |\part|, the examiner should include a
%solution block.  This block/environment will only be included if the answers
%class option is in effect. (See Class Options for more details).  Any standard
%LaTeX content can be placed in a solution block. A minimal example is below:
%
%\begin{verbatim}
%\begin{questions}
%  \question A really hard question.
%  \begin{solution}
%The answer is placed here.
%  \end{solution}
%\end{questions}
%\end{verbatim}
%
%\ \\
%
%\section{Usage - Multiple Choice Questions}
%There are four environments that will allow typesetting of multiple choice
%selections depending on the desired layout.  All must be used within a
%Questions or Parts environment.
%
%The first pair present a list of possible responses labelled with letters.
%The |choices| environment presents one choice per line, whereas the
%|horizontalchoices| environment lays out choices in a single paragraph,
%wrapping lines wherever necessary.
%
%The second pair present tick or check boxes instead of labelled choices.
%A |checkboxes| environment will again typeset options one to a line, and the
%|horizontalcheckboxes| environment will present all options in one paragraph.
%
%Within any of the four environments each choice is typeset using the choice
%macro.  Please note; there is no points argument for individual choices, this
%should be handled at the question or part level.
%
%\ \\
%
%\DescribeMacro{\choice\ Choice Text} Typesets a single choice according to
%which environment it is placed in.
%
%Solutions to multiple choice questions are handled somewhat differently.
%Instead of a |solutions| environment, typeset the correct option using the
%|correctchoice| macro.
%
%\ \\
%
%\DescribeMacro{\correctchoice\ Choice Text} Typeset the correct choice based
%on where the macro is placed.  When |answers| is in effect, the output of
%this macro will either highlight the option in boldface, or replace the
%checkbox with a tick.
%
%
%
%
%\StopEventually{}
%\section{The Code}
%\iffalse
%\begin{macrocode}
%<*bangorexam.cls>
%\end{macrocode}
%\fi
%\begin{macrocode}
\def\version{1.1.4 }

\NeedsTeXFormat{LaTeX2e}

\ProvidesClass{bangorexam}[2016/10/29 \version C. Gray]

% Based on the Exam document class by Philip S. Hirschhorn
% Developed/Adapted for Bangor University by C. Gray

\RequirePackage[dvipsnames]{xcolor}
\RequirePackage[T1]{fontenc}
\RequirePackage[UKenglish]{babel}
\RequirePackage[UKenglish]{isodate}
\RequirePackage[utf8]{inputenc}

\RequirePackage{array}
\RequirePackage{color}
\RequirePackage{etoolbox}
\RequirePackage{graphicx}
\RequirePackage{letltxmacro}
\RequirePackage{newpxtext,newpxmath}
\RequirePackage{totcount}
\RequirePackage{xstring}

\RequirePackage{courier}

% *******************************************************************
% Strings
% *******************************************************************

\newcommand{\engATypeText}{Answer {\bf Section A} (compulsory) and {\bf any two} questions from {\bf Section B}.}%
\newcommand{\welATypeText}{Atebwch {\bf Adran A} (gorfodol) ac {\bf unrhyw ddau} gwestiwn o {\bf Adran B}.}%
\newcommand{\engBTypeText}{Answer \textbf{two} out of four questions.}%
\newcommand{\welBTypeText}{Atebwch \textbf{ddau} o'r pedwar cwestiwn.}%
\newcommand{\sectionAHeader}{\textbf{SECTION A} --- Answer \textbf{ALL} questions (Total marks \total{sectiona})}%
\newcommand{\sectionBHeader}{\textbf{SECTION B} --- Answer any \textbf{TWO} questions (\total{sectionb} marks each)}%

% *******************************************************************
% Class Level Options
% *******************************************************************

% Enable Welsh headings, etc.  Does not affect the cover sheet.
% -------------------------------------------------------------------
\DeclareOption{welsh}{%
	\newcommand{\welsh}{true}%
	\renewcommand{\sectionAHeader}{\textbf{ADRAN A} --- Atebwch BOB cwestiwn (Cyfanswm marciau \total{sectiona})}%
	\renewcommand{\sectionBHeader}{\textbf{ADRAN B} --- Atebwch unrhyw DDAU chwestiwn (\total{sectionb} marc yr un)}%
}%
% Exam Type
% -------------------------------------------------------------------
\newcommand{\engTypeText}{}
\newcommand{\welTypeText}{}
\DeclareOption{ab}{%
	\newcommand{\examtype}{ab}%
	\renewcommand{\engTypeText}{\engATypeText}
	\renewcommand{\welTypeText}{\welATypeText}
}%
\DeclareOption{twofour}{%
	\newcommand{\examtype}{twofour}%
	\renewcommand{\engTypeText}{\engBTypeText}
	\renewcommand{\welTypeText}{\welBTypeText}
}%
\DeclareOption{answers}{\PassOptionsToClass{\CurrentOption}{exam}}%
\DeclareOption{draft}{\PassOptionsToClass{\CurrentOption}{exam}}%
\ProcessOptions\relax%

\ifx\examtype\undefined%
	\ClassError{bangorexam}{An exam type option has not been defined; use ab or twofour in the class options}%
\fi%

\LoadClass[a4paper,twoside,11pt,addpoints]{exam}%

% *******************************************************************
% Layout
% *******************************************************************
% Page layout
\setlength{\parindent}{0mm}%
\setlength{\parskip}{1ex plus 0.5ex minus 0.2ex}%

% Footer
\pagestyle{headandfoot}%
\coverfooter{}{}{\iflastpage{}{/ troi drosodd\\/ turn over}{}}%
\footer{}{\thepage}{\oddeven{\iflastpage{}{/ troi drosodd\\/ turn over}}}{}%

% Cover Column Definition
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}

\SolutionEmphasis{\color{red}}
\CorrectChoiceEmphasis{\bfseries\color{red}}

% *******************************************************************
% Configuration Macros
% *******************************************************************
\newcounter{tmp}
\newtotcounter{all}
\newtotcounter{tf}
\newtotcounter{sectiona}
\newtotcounter{sectionb}
\newcounter{lq}
\newcounter{lqp}
\setcounter{lq}{-1}

\newcommand{\school}[2] {%
	\def \engSchool {\expandafter\MakeUppercase\expandafter{#1}}%
	\def \welSchool {\expandafter\MakeUppercase\expandafter{#2}}%
}%
\newcommand{\module}[2]{%
	\StrSubstitute{#1}{-}{}[\mTmp]%
	\def \moduleCode {\expandafter\MakeUppercase\expandafter{\mTmp}}%
	\def \moduleName {#2}%
}%
\newcommand{\examperiod}[1]{%
	\setcounter{tmp}{\the\year}%
	\ifnum \the\month>8%
		\stepcounter{tmp}%
		\newcommand{\examYear}{\arabic{tmp}}%
	\else%
		\newcommand{\examYear}{\arabic{tmp}}%
	\fi%
	\newcommand{\welSemesterText}{Arholiadau Diwedd Semester\ \welSemester}%
	\newcommand{\engSemesterText}{End of Semester \engSemester\ Examinations}%
	\ifthenelse{\equal{#1}{s1}}{%
		\def \welSemester {Un}%
		\def \engSemester {One}%
		\def \welExamMonth {IONAWR}%
		\def \engExamMonth {JANUARY}%
	}{}%
	\ifthenelse{\equal{#1}{s2}}{%
		\def \welSemester {Dau}%
		\def \engSemester {Two}%
		\def \welExamMonth {MAI}%
		\def \engExamMonth {MAY}%
	}{}%
	\ifthenelse{\equal{#1}{resit}}{%
		\renewcommand{\welSemesterText}{Arholiadau Atodol}%
		\renewcommand{\engSemesterText}{Supplementary Examination}%
		\def \welExamMonth {AWST}%
		\def \engExamMonth {AUGUST}%
	}{}%
}

\newcommand{\timeallowed}[1]{%
	\def \timeAllowed {#1}%
}

\newcommand{\guidance}[1]{%
	\def \guidance@a {#1}%
	\def \guidance@b {#1}%
}

\newcommand{\guidancea}[1]{%
	\def \guidance@a {#1}%
}

\newcommand{\guidanceb}[1]{%
	\def \guidance@b {#1}%
}

% *******************************************************************
% Cover Page
% *******************************************************************

\renewcommand{\maketitle}{%
	\ifx\timeAllowed\undefined%
		\ClassError{bangorexam}{The time allowed for this exam has not been defined (missing timealllowed?)}%
	\fi%
	\ifx\engExamMonth\undefined%
		\ClassError{bangorexam}{The exam period for this exam has not been set (missing examperiod?)}%
	\fi%
	\ifx\moduleCode\undefined%
		\ClassError{bangorexam}{The module details for this exam have not been specified (missing module?)}%
	\fi%
	\ifx\welSchool\undefined%
		\ClassError{bangorexam}{The academic school setting this exam has not been defined (missing school?)}%
	\fi%

	\begin{center}
		\bfseries
		\huge
		PRIFYSGOL\\
		\large\mbox{}\\
		\huge
		BANGOR\\
		\large\mbox{}\\
		\huge
		UNIVERSITY

		\vfill
		\Large
		\welSchool \\
		\engSchool
	\end{center}
	\medskip
	\large
	\begin{tabular}{C{0.5\textwidth}C{0.5\textwidth}}
		{\bf \welSemesterText\par\welExamMonth\ \examYear}\par\vspace*{\bigskipamount}
		Amser a ganiateir:~\timeAllowed~awr &%
		{\bf \engSemesterText\par\engExamMonth\ \examYear}\par\vspace*{\bigskipamount}
		Time allowed:~\timeAllowed~hours
	\end{tabular}

	\vspace*{20mm}
	\LARGE
	\begin{center}
		{\bf \moduleCode\\
		\mbox{}\\
		\moduleName}

		\vfill
		\large
		{\welTypeText} \\
		{\engTypeText} \\
		\ 

		\medskip
		{\bf Total marks \total{all}\\
		     Cyfanswm Marciau \total{all}}
		\vfill
	\end{center}
}
\AtBeginDocument{
	\begin{coverpages}
		\setlength{\hoffset}{0mm}
		\setlength{\marginparwidth}{0pt}
		\maketitle
	\end{coverpages}
	\setcounter{page}{2}
	\pointsinrightmargin
	\ifthenelse{\equal{\examtype}{twofour}}{
		\clearpage
		{%
			\LARGE
			\textbf{\moduleCode: \quad \moduleName}

			\vspace*{8mm}
			\large
			\ifcsdef{guidance@a}{\normalsize\par\guidance@a}{}%
		}
		\vspace*{8mm}
	}{}%
}

% *******************************************************************
% Section Commands
% *******************************************************************
\newcounter{seca}
\newcounter{secb}
\newcommand{\inDoc}{none}%
\newcommand{\sectiona} {%
	\ifthenelse{\equal{\examtype}{twofour}}{\ClassError{bangorexam}{Section A defined in a 'two from four' exam}\relax}{}%
	\ifnumcomp{\value{seca}}{>}{0}
		{
			\ClassError{bangorexam}{There is already a Section A in this exam}\relax%
		}
		{
			\stepcounter{seca}\relax%
		}
	\renewcommand{\inDoc}{secA}%
	\clearpage
	{%
	\LARGE
	\textbf{\moduleCode: \quad \moduleName}

	\vspace*{8mm}
	\large
	\sectionAHeader
	\ifcsdef{guidance@a}{\normalsize\par\guidance@a}{}%
	}
	\vspace*{8mm}
}

\newcommand{\sectionb}{%
\ifthenelse{\equal{\examtype}{twofour}}{\ClassError{bangorexam}{Section B defined in a 'two from four' exam}\relax}{}
	\ifnumcomp{\value{secb}}{>}{0}
		{
			\ClassError{bangorexam}{There is already a Section B in this exam}\relax%
		}
		{
			\stepcounter{secb}\relax%
		}
\renewcommand{\inDoc}{secB}
\clearpage
{%
\large
\sectionBHeader
\ifcsdef{guidance@b}{\normalsize\par\guidance@b}{}%
}
\vspace*{8mm}
}

% *******************************************************************
% Patch Questions to make it Section-aware
% *******************************************************************
\renewcommand{\questionshook}{%
	\setlength{\itemsep}{14pt}%
    \edef\mytemp{{\inDoc}}%
    \expandafter\ifstrequal\mytemp{secB}{\addtocounter{question}{100}}{}%
}

\renewcommand{\thequestion}{%
    \edef\mytemp{{\inDoc}}%
    \setcounter{tmp}{0}%
    \addtocounter{tmp}{\value{question}}%
    \expandafter\ifstrequal\mytemp{secB}{\addtocounter{tmp}{-100}\arabic{tmp}}{\arabic{question}}%
}

\newcommand{\be@adduppoints}[1]{% 
	\def\temp{#1}\ifx\temp\empty%
        \def\temp{0}%
    \fi%   
    \ifnumcomp{\value{question}}{=}{\value{lq}}
    	{% Same question
    		\addtocounter{lqp}{\temp}%
    	}
    	{% Moved onto next question
    		\be@addpoints{\value{lqp}}%
    		\setcounter{lq}{\value{question}}%
    		\setcounter{lqp}{0}%
    		\addtocounter{lqp}{\temp}%
    	}%
}

\let\oldendq\endquestions%
\renewcommand{\endquestions}{%
    \addtocounter{question}{-1}%
    \be@adduppoints{0}%
}

\newcommand{\be@addpoints}[1]{%
	\edef\mytemp{{\inDoc}}%
	\expandafter\ifstrequal\mytemp{secA}%
        {%
            \addtocounter{sectiona}{#1}%
            \addtocounter{all}{#1}%
        }%
        {}%
    \expandafter\ifstrequal\mytemp{secB}%
        {%
            \ifnumcomp{\value{sectionb}}{=}{0}%
                {%
                    \addtocounter{sectionb}{#1}%
                    \addtocounter{all}{#1}%
                    \addtocounter{all}{#1}}%
                {}%
            \ifnumcomp{\value{sectionb}}{=}{#1}%
                {}%
                {%
                	\setcounter{tmp}{0}%
    				\addtocounter{tmp}{\value{question}}%
    				\addtocounter{tmp}{-100}
                    \ClassError{bangorexam}{Section B question \arabic{tmp} does not have an equal number of points (Existing Section B question worth \arabic{sectionb})}\relax%
                }%
        }%
        {}%
   	 \edef\mytemp{{\examtype}}%
     \expandafter\ifstrequal\mytemp{twofour}%
		{%
            \ifnumcomp{\value{tf}}{=}{0}%
                {%
                    \addtocounter{tf}{#1}%
                    \addtocounter{all}{#1}%
                    \addtocounter{all}{#1}}%
                {}%
            \ifnumcomp{\value{tf}}{=}{#1}%
                {}%
                {%
                    \ClassError{bangorexam}{Question \arabic{question} does not have an equal number of points (Existing question(s) worth \arabic{tf})}\relax%
                }%
        }%
        {}%
}

\newcommand{\patchqnumaddpoints}{%
\be@adduppoints{\@points}%
}
\pointformat{[\thepoints]}
\pointname{\null\patchqnumaddpoints}
\newcommand{\pointsdec}[1]{%
\pointname{#1}\patchqnumaddpoints
}

% *******************************************************************
% Multiple Choice commands.
% *******************************************************************

\let\horizontalchoices\oneparchoices
\let\endhorizontalchoices\endoneparchoices
\let\horizontalcheckboxes\oneparcheckboxes
\let\endhorizontalcheckboxes\endoneparcheckboxes

% *******************************************************************
% End of document validation
% *******************************************************************

\AfterEndDocument{%
	\edef\mytemp{{\examtype}}%
    \expandafter\ifstrequal\mytemp{twofour}%
    {%
        \edef\mytmp{\numquestions}%
		\expandafter\ifstrequal\mytmp{4}%
			{\relax}%
			{%
				\ClassError{bangorexam}{There is/are only (\numquestions) question(s) defined, there should be four}\relax%
			}%
    }{%
        \ifnumcomp{\value{seca}}{=}{0}%
            {%
				\ClassError{bangorexam}{There is no Section A defined in this exam}\relax%
			}%
            {\relax}%
        \ifnumcomp{\value{secb}}{=}{0}%
            {%
				\ClassError{bangorexam}{There is no Section B defined in this exam}\relax%
			}%
            {\relax}%
    }%
}

%    \end{macrocode}%\iffalse
%    \begin{macrocode}
%</bangorexam.cls>
%    \end{macrocode}
%\fi
%\iffalse
%    \begin{macrocode}
%\fi
%\Finale
\endinput