% quizmachine.sty
%
% This LaTeX package allows printing of homework problem set, from
% which alternatively a random selection of exactly 3 problems can be
% printed as a quiz.

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{quizmachine}[2013/02/27]

\RequirePackage{xifthen}
\RequirePackage{forloop}
\RequirePackage[first=1,last=6,seed=-1]{lcg}

\newif\if@Quiz@
\@Quiz@false
\DeclareOption{quiz}{\@Quiz@true}
\DeclareOption{homework}{\@Quiz@false}
\ProcessOptions

\newcount\@problemcount
\newcount\@problemnumber
\@problemcount=0

\long\def\defproblem#1{%
  \global\advance\@problemcount by 1
  \expandafter\long\expandafter%
    \def\csname problem\the\@problemcount\endcsname{#1}}

\newcounter{@q}
\newcounter{@ct}
\newcounter{@lastx}
\newcounter{@lasty}
\newcounter{@lastz}

\def\@quizleft{}
\def\@quizcenter{}
\def\@quizright{}
\def\@hwpreamble{}

\newcommand*{\quizleft}[1]{\def\@quizleft{#1}}
\newcommand*{\quizcenter}[1]{\def\@quizcenter{#1}}
\newcommand*{\quizright}[1]{\def\@quizright{#1}}
\newcommand*{\hwpreamble}[1]{\def\@hwpreamble{#1}}

\newcommand{\quizzes}[1]{%
  \if@Quiz@
    \setcounter{@lastx}{\the\@problemcount}
    \setcounter{@lasty}{\the\@problemcount}
    \addtocounter{@lasty}{-1}
    \setcounter{@lastz}{\the@lasty}
    \addtocounter{@lastz}{-1}
    \global\advance\@problemcount by 1
    \forloop{@ct}{0}{\value{@ct}<#1}{%
      \chgrand[last=\the@lastx, counter=x, quiet]\rand
      \chgrand[last=\the@lasty, counter=y, quiet]\rand
      \chgrand[last=\the@lastz, counter=z, quiet]\rand
      \ifthenelse{\they>\thez}{}{\addtocounter{z}{1}}
      \ifthenelse{\thex>\they}{}{\addtocounter{y}{1}}
      \ifthenelse{\thex>\thez}{}{\addtocounter{z}{1}}
      \noindent\textbf{\@quizleft} \hfill
      \textbf{\@quizcenter} \hfill
      \textbf{\@quizright}
      \begin{flushleft}
        {\baselineskip=20pt
         \begin{tabbing}
           Student ID Number: \= \kill
           Name: \> \rule[-2pt]{10cm}{0.3pt} \\
           Start Time:  \> \rule[-2pt]{10cm}{0.3pt} \\
           Finish Time: \> \rule[-2pt]{10cm}{0.3pt} \\
         \end{tabbing}}
      \end{flushleft}
      \forloop{@q}{1}{\value{@q}<\the\@problemcount}{%
        \@printproblem{\value{@q}}}
      \setcounter{page}{1}}
  \else
    \global\advance\@problemcount by 1
    \maketitle
    \@hwpreamble
    \begin{enumerate}
      \forloop{@q}{1}{\value{@q}<\the\@problemcount}{%
        \@problemnumber=\value{@q}
        \item \csname problem\the\@problemnumber \endcsname}
    \end{enumerate}
  \fi}
        
\newcommand{\@printproblem}[1]{%
  \@problemnumber=#1
  \ifthenelse{#1=\thex \OR #1=\they \OR #1=\thez}{%
    \noindent\emph{Question \the\@problemnumber:}
    \csname problem\the\@problemnumber \endcsname\newpage}{}}

