\usepackage{etoolbox} % provides \protecting
\usepackage{tocloft}% Used for creating answer key
\usepackage{framed}% Used for formatting the exercises and solutions
\usepackage{xifthen}% Provides \ifthenelse
\usepackage{graphicx}% Provides \scalebox
% Different ways of enumerating exercises are provided as outlined below:
% 1) Inline Exercises: In this case each exercise is enumerated starting
% at 1 at the beginning of each chapter.  There is no logical
% connection between these numbers and the sections in the chapter.
% Suitable for a series of small exercises scattered throughout the chapter.
% The default case has exercises labeled
% Exercise 2-3  (i.e. Third exercise in chapter 2.)
% The initialization command
% \inlineexercises
% must be placed in the preamble of the document.  The \inlineexercises command
% takes an optional argument that changes the enumeration from counting
% within chapters to other sectioning levels.  Use 0 for chapter level (the
% default), 1 for section, 2 for subsection, and 3 for subsubsection.
% So for instance \inlineexercises[1] will cause exercises in section 1.2
% to be labelled 1.2-1, 1.2-2, 1.2-3, etc. regardless of their position
% within any potential subsection.
% Note: You will need to set the secnumdepth counter to 3 if you
% really wanted to use subsubsection level exercises as subsubsections are
% not enumerated by default.
%
% 2) Depth Fixed Exercises: This version assumes exercises follow
% directly at the end of a sectioning layer (defaults to the section
% level).  In this case the enumeration of the exercise directly
% follows the section level .  Here we assume that each exercise
% consists of a series of problems and the entry therefore is:
% 2.3 Exercises  (i.e. Exercises from section 3 in chapter 2.)
% Use the function 
% \depthfixedexercises
% in the preamble of the document if you want this version. An
% optional parameter may be passed to \depthfixedexercises to have the
% exercise numbering correspond to a different sectioning depth other
% than the section level.  Use 0 for chapter 1 for section (the
% default), 2 for subsection and 3 for subsubsection.
% For example
% \depthfixedexercises[0]
% would assume exercises come at the end of a chapter so that the exercise
% would be just labeled following the chapter:
% 1 Exercises
% for the exercise at the end of chapter 1.
% Note: You will need to set the secnumdepth counter to 3 if you
% really wanted to use subsubsection level exercises as subsubsections are
% not enumerated by default.

% 3) Depth Float Exercises: This version assumes that exercises occur
% at the end of an arbitrary (potentially changing) depth of
% sectioning (chapter, section, subsection, etc.) and that they should
% be numbered based on the greatest sectioning depth that one is in
% when the exercise is given.  So if you place the exercise at the end
% of subsection 2.1.2 then the exercise will be numbered 2.1.2 .
% Whereas if you are in section 3.1 (with no subsections) then the
% exercise will be 3.1 . Of course it may occur that section 3.1 HAS
% subsections 3.1.1 and 3.1.2 but you want the exercises to be
% labelled for the entire section rather than subsection 3.1.2 to
% which this numbering scheme would default.  To adjust this behaviour
% the commands
% \subsubsectionend
% \subsectionend
% \sectionend
% may be issued before the exercise.  (These are currently implemented
% by resetting the subsubsection, subsection or section counters to 0
% respectively which should have no effect as these exercises are at
% the end of the subsection, section, or chapter, section respectively
% and the counters get reset automatically as the
% next \chapter, \section, etc. begins.)
%%%%%%%%%%%%%%%%
% The following defines how we want the answer header entries to look
% in the answer key.  The first argument is the title of the exercise and
% the second is the page number. This function gets assigned to the
% \l@exercise function used below (see the tocloft documentation)
\newcommand{\answerheaderstyle}[2]{\textbf{#1 (page #2)}}
% Make a counter in case we want to test what exercisetype is being used. 
\newcounter{exercisetype}
% Define the following command so we can use renewcommand in the main defs.
\newcommand{\exercisetitle}{}%
% Note the \makeatletter needs to be outside the function definition for
% the redefinition of \l@exercise to work.
\makeatletter%
\newcommand{\inlineexercises}[1][0]{\setcounter{exercisetype}{1}%
\ifthenelse{#1=0}{%
\newlistof[chapter]{exercise}{ans}{Answers}%
% The following makes the references include the chapter too.
\renewcommand{\theexercise}{\thechapter-\arabic{exercise}}%
}{%
\ifthenelse{#1=1}{%
\newlistof[section]{exercise}{ans}{Answers}%
\renewcommand{\theexercise}{\thesection-\arabic{exercise}}%
}{%
\ifthenelse{#1=2}{%
\newlistof[subsection]{exercise}{ans}{Answers}%
\renewcommand{\theexercise}{\thesubsection-\arabic{exercise}}%
}{%
\ifthenelse{#1=3}{%
\newlistof[subsubsection]{exercise}{ans}{Answers}%
\renewcommand{\theexercise}{\thesubsubsection-\arabic{exercise}}%
}{%
}}}}
\renewcommand\l@exercise\answerheaderstyle
\renewcommand{\exercisetitle}{Exercise \theexercise}%
}
\newcommand{\depthfixedexercises}[1][1]{\setcounter{exercisetype}{2}%
\newlistof[chapter]{exercise}{ans}{Answers}
\renewcommand\l@exercise\answerheaderstyle
\ifthenelse{#1=0}{%
\renewcommand{\theexercise}{\thechapter}}{%
\ifthenelse{#1=1}{%
\renewcommand{\theexercise}{\thesection}}{%
\ifthenelse{#1=2}{%
\renewcommand{\theexercise}{\thesubsection}}{%
\ifthenelse{#1=3}{%
\renewcommand{\theexercise}{\thesubsubsection}}{%
}}}}
\renewcommand{\exercisetitle}{\theexercise\ Exercises}
}
\newcommand{\depthfloatexercises}{\setcounter{exercisetype}{3}
\newlistof[chapter]{exercise}{ans}{Answers}
\renewcommand\l@exercise\answerheaderstyle
\renewcommand{\theexercise}{%
\protecting{\ifthenelse{\value{section}=0}{%
\thechapter}{%
\ifthenelse{\value{subsection}=0}{%
\thesection}{%
\ifthenelse{\value{subsubsection}=0}{%
\thesubsection}{%
\thesubsubsection}}}}}%
% Define the section end commands for those using the last exercise style.
\newcommand{\subsubsectionend}{\setcounter{subsubsection}{0}}
\newcommand{\subsectionend}{\setcounter{subsection}{0}}
\newcommand{\sectionend}{\setcounter{section}{0}}
% Note you have to modify the exercise title entry and the following
% exercisetitletoanswerkey to have the exercise name appear consistently
% in the answer key as well.  This is due to a protection issue when
% using \exercisetitle in the \addcontentsline command for which no
% workaround was obvious.
\renewcommand{\exercisetitle}{\theexercise\ Exercises}
\newcommand{\exercisetitletoanswerkey}{%
  \ifthenelse{\value{section}=0}{%
    \addcontentsline{ans}{exercise}{\thechapter\ Exercises}}{%
    \ifthenelse{\value{subsection}=0}{%
      \addcontentsline{ans}{exercise}{\thesection\ Exercises}}{%
      \ifthenelse{\value{subsubsection}=0}{%
        \addcontentsline{ans}{exercise}{\thesubsection\ Exercises}}{%
        \addcontentsline{ans}{exercise}{\thesubsubsection\ Exercises}}}}}%
}
\makeatother
% The exerciselayout environment determines how the exercises are laid out
% (boxed, multicolumn, or whatever).  We default to a frame around the
% exercises but this environment can be renewed to however is desired.
% This environment is never used in the document proper.  See the exercise
% environment below.
% Note that newer versions of the framed package have an oframed environment
% which has the frame open at the top or bottom at page breaks which may
% be preferable.
\newenvironment{exerciselayout}%
{% begin code
\begin{framed}}%
{% end code
\end{framed}}
% The following command formats the title of the exercise.  It should
% depend on \exercisetitle which gives the label and a single optional
% argument, the name of the exercise.
\newcommand{\exercisetitlelayout}[1][]{%
\ifthenelse{\isempty{#1}}{% No optional title
\textbf{\exercisetitle}%
}{% Optional title given
\textbf{\exercisetitle:\ #1}%
}}%
% We make a counter to create labels for the exercises in the answer key
% This one gets incremented when the answer key file is processed
\newcounter{exerciseanswercounter}
% A parallel counter is kept which is incremented when the exercise itself
% is processed so that we can generate the name of the label.
\newcounter{exerciseanswercounterparallel}
% For now we will use marginal links to point to the answers.  Unfortunately
% in a two-sided document LaTeX will sometimes place these on the wrong side.
% The following package fixes that.
\usepackage{mparhack}
% We will alter the margin width and separation temporarily when we place
% our answer links.  These lengths store the original values temporarily
% and then return them to their defaults.
\newlength{\marginparwidthoriginal}
\newlength{\marginparseporiginal}
% Define two lengths to be the marginal width and separation for our answer
% reference along with some default values.
\newlength{\marginparwidthanswer}
\newlength{\marginparsepanswer}
\setlength{\marginparwidthanswer}{.75in}
\setlength{\marginparsepanswer}{.15in}
% Define a command to contain the margin answer page reference.  It should
% take the page number as its single argument.
\newcommand{\marginanswerpageref}[1]{\marginpar{\centering~\\~\\Answers:\\ Page {#1}}}
% The exercise environment is the main environment for exercises.  See
% The reviewexercise environment for exercises at the end of a chapter.
% The exercise environment takes an optional argument, the title of the
% exercise.  The starred version of both environments places no entry in
% the answer key.  They are used for an exercise with no answers at the back.
\newenvironment{exercise}[1][]%
{% begin code
% Create the link to the answer page.  Since currently this is done using
% a marginal note this has to be outside the exerciselayout environment which
% may contain boxes, etc.
\stepcounter{exerciseanswercounterparallel}
\setlength{\marginparwidthoriginal}{\marginparwidth}
\setlength{\marginparseporiginal}{\marginparsep}
\setlength{\marginparwidth}{\marginparwidthanswer}
\setlength{\marginparsep}{\marginparsepanswer}
\marginanswerpageref{\protect\pageref{exerciseanswer:\theexerciseanswercounterparallel}}
%\marginpar{\centering~\\~\\Answers:\\ Page \protect\pageref{exerciseanswer:\theexerciseanswercounterparallel}}
\setlength{\marginparwidth}{\marginparwidthoriginal}
\setlength{\marginparsep}{\marginparseporiginal}
\par\begin{exerciselayout}\noindent%
\refstepcounter{exercise}%
% The following command is what I would like to have for all three versions
% of exercise but it doesn't work for the floating depth exercise type 
% because of protection issues.  So I have added that exercise title by hand.
% with a separate command.
%\addcontentsline{ans}{exercise}{\exercisetitle}%
\ifthenelse{\value{exercisetype}=3}{\exercisetitletoanswerkey%
}{\addcontentsline{ans}{exercise}{\exercisetitle}}%
% Create a label for the exercise location in the answer key
\addtocontents{ans}{\protecting{\stepcounter{exerciseanswercounter}\edef\thelabel{\noexpand\label{exerciseanswer:\theexerciseanswercounter}}\thelabel}}%
% We start the enumeration environment and include an empty item so
% that answers for exercises involving no enumeration still work.
% The \rule in the entry is required for proper spacing if multicolumn
% is used to wrap an exercise. (See \addtoanswerkey below)
% I haven't figured out how to get the spacing quite right (i.e. how to
% backspace vertically exactly the size of an item.  In the end I've
% hardcoded something but this seems to vary across documents.)
%\addtocontents{ans}{\par\ignorespaces\protect\begin{enumerate}\protect\item[]\protect\rule{0ex}{1ex}\protect\vspace{-\itemsep}\protect\vspace{-\parsep}\protect\vspace{-1.35\baselineskip}\par}%
\addtocontents{ans}{\par\ignorespaces\protect\begin{enumerate}\protect\item[]\protect\rule{0ex}{1ex}\protect\vspace{-4ex}\par}%
\exercisetitlelayout[#1]%
    \par%
    \noindent\ignorespaces
}%
{% end code
  \par%
  \noindent\ignorespacesafterend\end{exerciselayout}%
  \addtocontents{ans}{\protect\end{enumerate}}%
} 

\newenvironment{exercise*}[1][]%
{% begin code
  \par\begin{exerciselayout}\noindent%
  \refstepcounter{exercise}%
  \exercisetitlelayout[#1]%
    \par%
    \noindent\ignorespaces
}%
{% end code
  \par%
  \noindent\ignorespacesafterend\end{exerciselayout}
} 
% The following makes a review exercise at the end of the chapter.  Note
% that it still uses the exercise counter so any inline exercise after a
% review exercise (which their shouldn't be) would be misnumbered.
\newcommand{\reviewexercisetitle}{\chaptername\ \thechapter\ Review Exercises}
% Define a reviewexerciselayout environment like exerciselayout as above.
% By default we'll set that environment to be the same as exerciselayout but
% For flexibility we allow them to be changed separately.
\newenvironment{reviewexerciselayout}%
{% begin code
\begin{exerciselayout}}%
{% end code
\end{exerciselayout}}
% The following command formats the title of the review exercise.  It should
% depend on \reviewxercisetitle
\newcommand{\reviewexercisetitlelayout}{%
\textbf{\reviewexercisetitle}}
\newenvironment{reviewexercise}
{% begin code
% Create the link to the answer page.  Since currently this is done using
% a marginal note this has to be outside the exerciselayout environment which
% may contain boxes, etc. (This is the same as in the exercise environment
% and uses the same counters.)
\stepcounter{exerciseanswercounterparallel}
\setlength{\marginparwidthoriginal}{\marginparwidth}
\setlength{\marginparseporiginal}{\marginparsep}
\setlength{\marginparwidth}{\marginparwidthanswer}
\setlength{\marginparsep}{\marginparsepanswer}
\marginanswerpageref{\protect\pageref{exerciseanswer:\theexerciseanswercounterparallel}}
%\marginpar{\centering~\\~\\Answers:\\ Page \protect\pageref{exerciseanswer:\theexerciseanswercounterparallel}}
\setlength{\marginparwidth}{\marginparwidthoriginal}
\setlength{\marginparsep}{\marginparseporiginal}
\par\begin{reviewexerciselayout}\noindent%
\refstepcounter{exercise}%
\addcontentsline{ans}{exercise}{\reviewexercisetitle}%
% Create a label for the exercise location in the answer key
\addtocontents{ans}{\protecting{\stepcounter{exerciseanswercounter}\edef\thelabel{\noexpand\label{exerciseanswer:\theexerciseanswercounter}}\thelabel}}%
\addtocontents{ans}{\par\ignorespaces\protect\begin{enumerate}\protect\item[]\protect\rule{0ex}{1ex}\protect\vspace{-4ex}\par}%
\reviewexercisetitlelayout%
    \par%
    \noindent\ignorespaces
}%
{% end code
  \par%
  \noindent\ignorespacesafterend\end{reviewexerciselayout}
  \addtocontents{ans}{\protect\end{enumerate}}%
} 
\newenvironment{reviewexercise*}
{% begin code
  \par\begin{reviewexerciselayout}\noindent%
  \refstepcounter{exercise}%
  \reviewexercisetitlelayout%
    \par%
    \noindent\ignorespaces
}%
{% end code
  \par%
  \noindent\ignorespacesafterend\end{reviewexerciselayout}
} 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The following problemblock environment is used to encapsulate a
% series of problems in an exercise's enumeration list of a common
% theme requiring a single set of instructions.  It takes one
% mandatory argument which is the set of instructions for the group of
% problems.  An optional argument may be provided specifying if one
% wants more than one column for subsequent problems.  This uses the
% multicol environment and so a \columnbreak may be placed manually if
% desired.
%
% As a technical note, the reason to have the multiple column optional
% argument is that if one just placed a \begin{multicols}{2} after the
% beginning of the problem block (which one wants as one needs the
% instructions to span the columns) then this necessitates that the
% multicolumn end occur before the end of the problem block.  Unfortunately
% ending a multicolumn triggers LaTeX to move out of the item level so
% that the label that is created when the end of the problemblock is called
% is now in error.  By making the number of columns optional this gets around
% this technical problem and also (ultimately) will allow the code to
% ignore the formatting command if desired.
%
% We need to use the \ref* command of hyperref below to stop putting a
% link if that package is used.  However since someone may NOT have
% been using hyperref we had to define \ref* to just be a regular \ref
% in that case.
% Note that hyperref must be loaded BEFORE textbooktools for hyperlinks
% in the answer key to work properly.  (hyperref redefines how certain
% aspects of counters behave when they are declared after the package is
% loaded.)
\makeatletter
\@ifpackageloaded{hyperref}{}{
\let\originalref\ref
\renewcommand{\ref}{\@ifstar\originalref\originalref}
}
\makeatother
\newcounter{problemblockcounter}
%The following is used to store the optional argument so it can be used
%in the end code for the environment which otherwise has no access to the
%parameter. 
\newcommand{\problemblockfirstarg}{}
\newenvironment{problemblock}[2][0]{%Begin code
\stepcounter{problemblockcounter}%
\renewcommand{\problemblockfirstarg}{#1}%
\renewcommand{\labelenumi}{\ref*{pgcstart:\theproblemblockcounter}-\ref*{pgcend:\theproblemblockcounter}:}
\item #2
\ifthenelse{\equal{#1}{0}}{% No multiple columns
}{% Multiple columns
\begin{multicols}{#1}%
}%
\edef\thelabel{\noexpand\label{pgcstart:\theproblemblockcounter}}%
\thelabel%
\addtocounter{enumi}{-1}
\renewcommand{\labelenumi}{\theenumi.}
}
{%End code
\edef\thelabel{\noexpand\label{pgcend:\theproblemblockcounter}}%
\thelabel%
\ifthenelse{\equal{\problemblockfirstarg}{0}}{% No multiple columns
}{% Multiple columns
\end{multicols}%
}%
\par\noindent\rule{.5\textwidth}{0.4pt}\par}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The specialitem is used to special symbols beside problems of various
% types.  The generic specialitem command takes as a single argument the
% symbol to put beside problem.  An optional second argument can be passed
% that is used for any enumeration level after the top level.  In those
% cases one typically wants a smaller symbol.  Several examples are given
% below.  One typically needs to \protect any commands in the optional
% argument as shown in the examples.
\makeatletter
\newcommand{\specialitem}[2][]{\refstepcounter{enum\romannumeral\@enumdepth}\item[\ifthenelse{\@enumdepth=1}{#2}{\ifthenelse{\equal{#1}{}}{#2}{#1}}\ifthenelse{\@enumdepth=1}{\labelenumi}{%
\ifthenelse{\@enumdepth=2}{\labelenumii}{%
\ifthenelse{\@enumdepth=3}{\labelenumiii}{%
\ifthenelse{\@enumdepth=4}{\labelenumiv}{}%
}}}]}
\makeatother
% The items below are all special items.  Many of them use symbols from
% various symbol packages.  The code currently checks to see the symbol
% package exists on the system before defining the command.  In this way
% the code will compile for someone who doesn't have the special symbol in
% question but isn't using that special item.  The code below could be
% modified to add a definition for the item in the event a symbol doesn't
% exist.  Instead it prints an error in log that the special item is
% disabled.  Ultimately however we may just want to create some custom pdf
% symbols so no symbol packages are ever required.  Some of the special
% items have no existing suitable symbols anyway.
%
% \optitem provides an optional item symbol (here an asterisk) for questions
% arising from an optional section of the text.
\newcommand{\optitem}{\specialitem{*}}
\IfFileExists{manfnt.sty}{\usepackage{manfnt}
% \toughitem provides an challenging problem symbol (here a bend in the road)
% from the manfnt package
\newcommand{\toughitem}{\specialitem[\protecting{\raisebox{.4em}{\scalebox{.6}{\dbend}}\hspace{.2ex}}]{\raisebox{.4em}{\scalebox{.85}{\dbend}}\hspace{.6ex}}}
}{\typeout{manfnt symbol package missing: toughitem disabled}}
\IfFileExists{marvosym.sty}{\usepackage{marvosym}%
% \codeitem provide a symbol for a problem requiring programming.  The
% symbol here is a keyboard from the marvosym package
\newcommand{\codeitem}{\specialitem[\protecting{\raisebox{0.1em}{\scalebox{.9}{\Keyboard}}\hspace{.2ex}}]{\raisebox{0em}{\scalebox{1.8}{\Keyboard}}\hspace{.4ex}}}
% \writeitem provides a symbol for a problem requiring a composition.
% The symbol is a writing hand (marvosym package).
\newcommand{\writeitem}{\specialitem[\protecting{\raisebox{0em}{\scalebox{1}{\Writinghand}}\hspace{.12ex}}]{\raisebox{-0.1em}{\scalebox{1.7}{\Writinghand}}\hspace{.4ex}}}
}{\typeout{marvosym symbol package missing: codeitem, writeitem disabled}}
% I undefine the \Cross command from marvosym as it prevents bbding package
% loading below.
\makeatletter
\@ifundefined{Cross}{}{%
\let\Cross\@undefined
\let\endCross\@undefined}
\makeatother
% \casitem provides a symbol for a problem requiring a computer algebra
% system.  The symbol is the letters CAS in a box.
\newcommand{\casitem}{\specialitem[\protecting{\raisebox{0.1em}{\scalebox{.3}{\fbox{CAS}}}\hspace{.12ex}}]{\raisebox{0.1em}{\scalebox{.65}{\fbox{\hspace{-.3em}CAS\hspace{-.2em}}}}\hspace{.3ex}}}
\IfFileExists{skak.sty}{\usepackage{skak}
% \calcitem provides a symbol for a problem requiring a calculator.
% The symbol is currently just a square with a cross from the skak package.
% Should be changed to a calculator graphic.
\newcommand{\calcitem}{\specialitem[\protecting{\raisebox{-.05em}{\scalebox{.8}{\centre}}\hspace{.12ex}}]{\raisebox{-.05em}{\scalebox{1}{\centre}}\hspace{.4ex}}}
}{\typeout{skak symbol package missing: calcitem disabled}}
% \beyonditem provides a symbol for a problem which takes you to concepts
% that are beyond the current scope of the material.  Currently the symbol
% is an arrow from bbding package, but a plane taking off might be better.
\IfFileExists{bbding.sty}{\usepackage{bbding}
\newcommand{\beyonditem}{\specialitem[\protecting{\raisebox{-.1em}{\scalebox{.75}{\ArrowBoldRightStrobe}}\hspace{.05ex}}]{\raisebox{-.3em}{\scalebox{1.2}{\ArrowBoldRightStrobe}}\hspace{.4ex}}}
}{\typeout{bbding symbol package missing: beyonditem disabled}}
% Maybe we should add a \spreaditem for a spreadsheet problem.  
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The \answer command is used within an exercise environment to put answers
% in the answer key at the back of the textbook.  In an enumerated list of
% questions the \answer command should be put within the given item.  It
% is only designed to work at the top level (depth 1) of an enumerated list.
% If the question has parts to it then the answer should includes answers
% for those parts such as
% \answer{\begin{itemize}\item Part (a) answer \item Part(b) answer\end{itemize}}
% The \answer command behaves properly if some questions in the list do
% not have answers, keeping the proper number of the question at the back.
% By keeping the answer embedded within the question one is able to easily
% omit questions as desired without having to adjust the answer key.
% If the \answer command is used outside of an enumerated list then the
% given answer will just be placed in the key without a number.
%
% One can choose to select that only odd or even answers in the top level
% enumeration environment be in the document with the commands
% \oddanswers
% \evenanswers
% Default is to have
% \allanswers
% The \noanswers command will make the \answer command put no answers whether
% found in enumeration lists or outside of them in the back.
% To omit an answer key entirely don't call the
% \listofexercise or \customlistofexercise commands from within the main
% document.
%
% Finally the \answer command admits an optional argument which is a long answer
% to the problem.  This is to be a complete solution to the problem suitable
% for a teacher's edition or a solutions manual.  The current behaviour is just
% to place the long solution at the point of the \answer command.  The
% \printlonganswers and \printnolonganswers command turns on and off the
% printing of long answers inline.  Default is to not print long answers.
% TODO: Make a solutions manual command which dumps the long answer (or short
% if none provided) to a separate solutions manual document along with the
% page header, exercise, etc.  I should also be able to control printing
% of even or odd as usual.
\newcounter{answertype}
\newcommand{\allanswers}{\setcounter{answertype}{0}}
\newcommand{\oddanswers}{\setcounter{answertype}{1}}
\newcommand{\evenanswers}{\setcounter{answertype}{2}}
\newcommand{\noanswers}{\setcounter{answertype}{3}}
% Set default to print all answers
\allanswers
\newboolean{printlonganswer}
\newcommand{\printlonganswers}{\setboolean{printlonganswer}{true}}
\newcommand{\printnolonganswers}{\setboolean{printlonganswer}{false}}
% Set default to print no long answers
\printnolonganswers
% The following environment determines how long answer solutions are
% printed inline.
% I'll used the shaded background from the framed package.  This needs the
% color package:
\usepackage{color}
% A grey backing:
\definecolor{shadecolor}{gray}{0.9}
\newenvironment{longanswerlayout}{%Begin
\begin{snugshade}\small}%
{%End
\end{snugshade}%
}
\makeatletter
% The following boolean is used internally below for determining whether
% to print an individual answer in the answer key.
\newboolean{printanswer}
% The \protecting command required in the following is supplied by
% the etoolbox package
% Without it one needs to \protect all the \item commands, etc. separately.
\newcommand{\answer}[2][]{\ifthenelse{\@enumdepth=0}%
{%Not in an enumeration list
%As long as we aren't in \noanswers mode print the answer
\ifthenelse{\value{answertype}=3}{}{%
\addtocontents{ans}{\protecting{#2}}}%
}{%In an enumeration list
\setboolean{printanswer}{false}%
\ifthenelse{\value{answertype}=0}{% All answer
\setboolean{printanswer}{true}}%
{%
\ifthenelse{\value{answertype}=1}{% Odd answers
\ifthenelse{\isodd{\theenumi}}{\setboolean{printanswer}{true}}{}}%
{%
\ifthenelse{\value{answertype}=2}{% Even answers
\ifthenelse{\isodd{\theenumi}}{}{\setboolean{printanswer}{true}}}%
}{% No answers (presumed)
}%
}%
\ifthenelse{\boolean{printanswer}}{%
\addtocontents{ans}{\protect\setcounter{enumi}{\theenumi}\protect\addtocounter{enumi}{-1}\protect\item\protecting{#2}}%
}{}%
\ifthenelse{\boolean{printlonganswer}}{%
\ifthenelse{\equal{#1}{}}{}{\begin{longanswerlayout}#1\end{longanswerlayout}}%
}{}%
}%
}%
\makeatother
% The following macro allows special local formatting to be placed in
% the answer key (such as multicolumn)
\newcommand{\addtoanswerkey}[1]{\addtocontents{ans}{\protecting{#1}}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Enumeration reference issues
% The following redefines the basic enumeration lists so that a reference
% to item 1 subitem (a) will appear as 1(a) rather than the default 1a.
\renewcommand{\theenumii}{(\alph{enumii})}
\renewcommand{\labelenumii}{\theenumii}
\makeatletter
\renewcommand{\p@enumiii}{\theenumi\theenumii}
\makeatother
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Textbooks often require references within lists.  So in part (b) of a problem
% one will want to say "Use your result from (a)".  The default behaviour
% is to generate the reference as 1(a) no matter where you are in the document.
% The novice author may choose to just hardcode the reference themselves but
% this is problematic for several reasons as it makes it difficult to change
% the style of the document universally later and it also makes it impossible
% for the document to support multiple versions some of which may have a
% different number of items, etc.  One can also use other enumeration package
% features but all of these hardcode the label style and this breaks if one
% wants to make references to the same label from different locations within
% the environment.  For now that is a preferable approach as at least
% it keeps the references working.  We need to make a package that is
% able to figure out the context on its own and use the correct label.
\usepackage{enumitem}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Define an example environment.  Numbering will be similar to
% \inlineexercises above.  In the default each example is enumerated starting
% at 1 at the beginning of each section such as
% Example 2.3-2  (i.e. Second example in section 2.3.)
% The command
% \initexamples
% must be placed in the preamble of the document.  The \initexamples command
% takes an optional argument that changes the enumeration from counting
% within sections to other sectioning levels.  Use 0 for chapter level, 
% 1 for section (the default), 2 for subsection, and 3 for subsubsection.
% So for instance \initexamples[0] will cause examples in chapter 2
% to be labelled 2-1, 2-2, 2-3, etc. regardless of their position
% within any further section.
% Note: You will need to set the secnumdepth counter to 3 if you
% really wanted to use subsubsection level examples as subsubsections are
% not enumerated by default.
% TODO: This environment could be implemented with the amsthm package.
\newcommand{\initexamples}[1][1]{%
\ifthenelse{#1=0}{%
\newcounter{example}[chapter]%
% The following makes the references include the chapter too.
\renewcommand{\theexample}{\thechapter-\arabic{example}}%
}{%
\ifthenelse{#1=1}{%
\newcounter{example}[section]%
\renewcommand{\theexample}{\thesection-\arabic{example}}%
}{%
\ifthenelse{#1=2}{%
\newcounter{example}[subsection]%
\renewcommand{\theexample}{\thesubsection-\arabic{example}}%
}{%
\ifthenelse{#1=3}{%
\newcounter{example}[subsubsection]%
\renewcommand{\theexample}{\thesubsubsection-\arabic{example}}%
}{%
}}}}
\newcommand{\exampletitle}{Example \theexample}%
}
% Note that newer versions of the framed package have an oframed environment
% which has the frame open at the top or bottom at page breaks which may
% be preferable.
\newenvironment{examplelayout}%
{% begin code
\begin{leftbar}}%
{% end code
\end{leftbar}}
% The following command formats the title of the example.  It should
% depend on \exampletitle which gives the label and a single optional
% argument, the name of the example.
\newcommand{\exampletitlelayout}[1][]{%
\ifthenelse{\isempty{#1}}{% No optional title
\textbf{\exampletitle}%
}{% Optional title given
\textbf{\exampletitle:\ #1}%
}}%
% The next counter counts all the examples from the beginning of the document
% and is used to automatically generate an internal label for every example
% which can then be referenced from an external document (a slides document)
% whose ordering matches the original document.
\newcounter{exinternal}%
% Finally we have the example environment.
\newenvironment{example}[1][]%
{% begin code
  \par\begin{examplelayout}\noindent%
  \refstepcounter{example}%
  \stepcounter{exinternal}%
  \edef\thelabel{\noexpand\label{exint:\theexinternal}}%
  \thelabel%
  \exampletitlelayout[#1]%
    \par%
    \noindent\ignorespaces
}%
{% end code
  \par%
  \noindent\ignorespacesafterend\end{examplelayout}
}
% Make a method/test environment.  This will be used for giving algorithmic
% steps, etc.  Currently we will just highlight it.
\newenvironment{method}{%Begin
\begin{framed}%
}{%End
\end{framed}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Asymptote code is used for drawing figures.  It will work within the
% exercise environments but will not work within macros like \answer.
% This code snippet creates the command \asycode{(the code)} which will
% work if one requires an asymptote object in the answer key.
% Note that the actual asymptote code will not get dumped into the asy file
% until the second latex pass.
% Also note that because newlines are not preserved in the answer key
% you cannot use comments (a line starting with //) in your asymptote code
% as it will make asymptote consider all subsequent lines in your code
% to be part of the comment.
% The original solution to the problem is found here:
% See http://tex.stackexchange.com/questions/127003/incorporate-asymptote-environment-into-macro
% As a final note the \asycode command is also useful if you want to
% resize your graph by putting the whole thing in a \resizebox command.
% Note that wildcard dimensions (!) in resizebox should line up with any
% zero dimension (if any) in the size command of your asymptote code or a
% division by zero error will result.  i.e. the following would work
%
%\resizebox{5.5in}{!}{%
%\asycode{%
%. .
%. .
%. .
%size(250,0);
% However if 0 had been first in the size command an error would be generated.
% If the size dimensions were completely specified in the asymptote code this
% is not an issue.  UPDATE: Actually this is not true, having the wildcard
% in the first space even with the size completely specified will NOT work.
% Since many will not use the asymptote package we check it is installed
% before loading it and defining the command.  If the package does not
% exist a warning is printed and the \asycode command disabled.
\IfFileExists{asymptote.sty}{\usepackage{asymptote}}{\typeout{asymptote package missing: asycode disabled}}
\makeatletter
\newcommand\asycode[2][]{%
  \stepcounter{asy}%
  \setkeys{ASYkeys}{#1}%
  \ifASYattach
    \ASYinlinefalse
  \fi
  \ifx\asydir\empty\else
    \def\ASYprefix{\asydir/}%
  \fi
  \immediate\write\AsyPreStream{%
    \noexpand\InputIfFileExists{%
      \ASYprefix\noexpand\jobname-\the\c@asy.pre}{}{}%
  }
  \asy@write@graphic@header
  \immediate\write\AsyStream{\detokenize{#2}}% here asy does the writing
  \asy@finalise@stream
  \asy@input@graphic
}
\makeatother
\IfFileExists{asymptote.sty}{}{\let\asycode\undefined}
%
% The following creates a default box called \asybox to use for putting
% asymptote code in a box.  This can be reused.
\newsavebox\asybox
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Make this so it works with each one.
\newlength{\tabcolseporiginal}
\setlength{\tabcolseporiginal}{\tabcolsep}
\usepackage{multicol}
\newcommand{\customlistofexercise}{%
\setlength{\columnseprule}{.6pt}
\setlength{\tabcolsep}{1mm}
{\raggedright\small{\begin{multicols}{2}
\listofexercise
\end{multicols}}}
\setlength{\columnseprule}{0pt}
\setlength{\tabcolsep}{\tabcolseporiginal}}
%
% TODO:
% Create an answer problem block so that a common set of comments could
% be placed at the top of a set of answers.  Also it should allow an
% optional multicolumn argument.
%
% Create a squeeze environment that can be used for squeezing material to
% fit onto a single page.  It could take a single argument that is the
% fraction by which any vertical space is temporarily reduced by (including
% \vspace).  i.e. \begin{squeeze}[.8] would change all vertical spaces to
% .8 of their value.  squeeze might also shorten bottom margins perhaps.
