%% Documentation for cntperchap.sty
%%
%% Version 0.3 (2015/06/01}
%%
%% 
%% -------------------------------------------------------------------------------------------
%% Copyright (c) 2015 by Dr. Christian Hupfer <christian dot hupfer at yahoo dot de>
%% -------------------------------------------------------------------------------------------
%%
%% This work may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License, either version 1.3
%% of this license or (at your option) any later version.
%% The latest version of this license is in
%%   http://www.latex-project.org/lppl.txt
%% and version 1.3 or later is part of all distributions of LaTeX
%% version 2005/12/01 or later.
%%
%% This work has the LPPL maintenance status `maintained'.
%%
%% This work consists of all files listed in README
%%


\documentclass[12pt,english]{ltxdoc}
\usepackage{scrlayer-scrpage}
\usepackage[tikz]{bclogo}
\usepackage[lmargin=3cm,rmargin=3cm,a4paper]{geometry}
\usepackage{savesym}%
\usepackage{bbding}%
\savesymbol{Cross}%

\usepackage{blindtext}%
\usepackage{enumitem}%
\usepackage{datetime}%
\usepackage{imakeidx}%


\usepackage[most]{tcolorbox}
\usepackage{cntperchap}

\RegisterCounters{section,subsection,subsubsection,table,figure}


\tcbuselibrary{documentation}

\tcbset{color command={blue}}




\newcommand{\tcolorboxdoclink}{http://mirrors.ctan.org/macros/latex/contrib/tcolorbox/tcolorbox.pdf}

\newcommand{\packagename}[1]{\fbox{\textcolor{blue}{\textbf{\ding{41}~#1}}}\index{Package!#1}}%
\newcommand{\classname}[1]{\fbox{\textcolor{brown}{\textbf{\Writinghand~#1}}}\index{Class!#1}}%


\newcommand{\handrightnote}{\tcbdocmarginnote{\ding{43}}}


\newtcolorbox{docCommandArgs}[1]{colbacktitle={blue},coltitle={white},title={Description of arguments of command \cs{#1}}}


\def\packageversion{0.3}%

\makeindex

\newcommand{\PackageDocName}{\cpspackagename.sty}%


\hypersetup{breaklinks=true}

\begin{document}
\mmddyyyydate


\setlength{\parindent}{0pt}

\thispagestyle{empty}%

\begin{center}
\begin{tcolorbox}[boxrule=1mm,arc=4mm,colback=yellow!30!white,width=0.8\textwidth]
\large \bfseries%
\begin{center}%
\begin{tabular}{c}%
\textsc{\PackageDocName} \tabularnewline
\tabularnewline
Store counter values per chapter \tabularnewline
(or other section levels) \tabularnewline 
\tabularnewline
Version \packageversion \tabularnewline
\tabularnewline
\today \tabularnewline
\tabularnewline
\addtocounter{footnote}{2}
Author: Christian Hupfer\(^\mathrm{\fnsymbol{footnote}}\)
\tabularnewline
\end{tabular}
\end{center}
\end{tcolorbox}
\makeatletter
\renewcommand{\thefootnote}{\fnsymbol{footnote}}%
\footnotetext{christian.hupfer@yahoo.de}%
\makeatother

\end{center}

\tableofcontents
\clearpage




\pagestyle{scrheadings}%
\setheadsepline{2pt}[\color{blue}]

\setcounter{footnote}{0}


\section{Disclaimer}
This package as of its version \packageversion\ is under constant development and as such subject to macro interface changes as well as renaming of macros. 

Although the example in this manual treats with the \docCounter{page} counter, it is not recommended to use this package in conjunction with the page counter for a serious document. The page counter is quite difficult to track. 

\section{Introduction}

The aim of this package is to provide support for a summary in advance how many sections, subsections, etc. or figures, tables, equations there will be in predefined section level, for example per chapters. The values are stored at the beginning of a new chapter and written to \cs{jobname.cpsfoo} files, where \docCounter{foo} is short for the relevant counter name. The section level can be one of standard levels 
\begin{itemize}
  \item \cs{part}
  \item \cs{chapter}
  \item \cs{section}
  \item \cs{subsection}
  \item \cs{subsubsection}
  \item \cs{paragraph}
  \item \cs{subparagraph}
\end{itemize}

The section level can be specified as an option (see \ref{section::package_options}), but is preconfigured on the underlying document class. For \classname{book}-like classes, the section level defaults to \cs{chapter}, for \classname{article}-like documentclasses it defaults to \cs{section}.

In fact, there is no need of having a section level at all. Basically any environment can serve as a track level, however, only one environment type per document so far only.  


This package is the consequence of the question \url{http://tex.stackexchange.com/questions/241559/how-to-count-the-total-number-of-sections-within-a-chapter} by the user \texttt{gsl}. 

\begin{tcolorbox}[title={Statistics of the local chapter},colbacktitle=yellow,coltitle=black]
\ShowStatistics[1]
\end{tcolorbox}

\subsection{Basic usage}

\tcbdocmarginnote{\ding{43}} If \refAuxcs{nofiles} is used, no package related files are generated or included, similar to the behaviour for \refAuxcs{tableofcontents} etc. 

\begin{tcblisting}{listing only}
\documentclass{book}
\usepackage{cntperchap}

\RegisterCounters{section,subsection,subsubsection,table,figure}

\begin{document}
\section{First section}
\ShowStatistics
\end{document}
\end{tcblisting}

\section{Package options}%
\label{section::package_options}

As of version \packageversion~ the package has only following options so far:


\begin{itemize}

\item   \begin{docKey}{autodefine}{}{}
    This option enables the automatic counter definition if some undefined counter is specified during the registration process. 
  \end{docKey}

\item   \begin{docKey}{draft}{}{default is draft}
    This option enables the explicit statistics
    \end{docKey}
\item   \begin{docKey}{final}{}{default is off}
    This option disables the explicit statistics
    \end{docKey}

  \item   \begin{docKey}{noendclose}{}{default is false}
      This option prevents the explicit closing of output files and provides the means to enter a hook into the \cs{AfterEndDocument} command. 
    \end{docKey}


\item   \begin{docKey}{tracklevel}{\meta{=chapter}}{chapter}
    This option sets the sectioning level or the environment under supervision (tracked). If not specified, the counters are stored on a per chapter base, if set to  \texttt{section}, the counter values are stored on a per section level etc. The section level has to be specified without the blackslash $\backslash$. 

Unknown section levels or environment (counters) will lead to a compilation error. As of version \packageversion~ this requires that the environment and the corresponding counter share the same name. 
\end{docKey}


\item   \begin{docKey}{verbose}{}{}
    This option enables verbose output during compilation. 
  \end{docKey}



\end{itemize}

\section{Requirements and incompatibilities}%

\subsection{Required packages}

\begin{itemize}
\item \packagename{assoccnt}%
\item \packagename{etoolbox}%
\item \packagename{ifthen}%
\item \packagename{morewrites}%
\item \packagename{xkeyval}%
\item \packagename{xparse}%
\end{itemize}

The packages \packagename{etoolbox} and \packagename{xkeyval} are already loaded by \packagename{assoccnt}. 

\subsection{Incompatibilities}

This package has been tested with the standard classes \classname{article}, \classname{book} and \classname{report} as well as with \classname{memoir} and the relevant \classname{KOMA} equivalents. As of version \packageversion\ for those classes there are no known incompatibilities with the general behaviour of the package, however, there is an issue with \packagename{assoccnt} and \packagename{xifthen} which is not solved so far. 

\marginnote{\bcbombe} It would be nice to adapt the package for usage on a per frame base with the \classname{beamer} class, but this seems both not really necessary as well as quite difficult, since \classname{beamer} follows different strategies about the usage of ``pages'' or ``sections'', see \ref{section::todo}


%This package will  so far if the document class does not provide the chapter command. It should work with the standard document classes of \classname{book} and \classname{report} as well as with \classname{memoir} and the relevant \classname{KOMA} equivalents. 


\section{Documentation of Macros}

\subsection{Preamble only commands}




\begin{docCommand}{RegisterCounter}{\oarg{options}\marg{counter}}

This provides the means to let the package know that a counter should be tracked for values per chapter

\begin{docCommandArgs}{RegisterCounter}%

  \begin{enumerate}[label={\textcolor{blue}{\#\arabic*}}]
  \item \oarg{options}: 

    \begin{docKey}{autodefine}{\meta{true,false}}{false}
      This will enable the automatic definition of a counter if the name specified as 2nd mandatory argument is not identified as \LaTeX\ counter. 
    \end{docKey}

 \item \marg{counter}
   This contains the counter name which should be tracked for counting itself.
\end{enumerate}
\end{docCommandArgs}

\end{docCommand}%

\begin{docCommand}{RegisterCounters}{\marg{counter1,counter2,...}}

This macro allows for specification of a CSV list of counter names -- internally this will call \refCom{RegisterCounter}

\begin{docCommandArgs}{RegisterCounters}%
\begin{itemize}
  \item \marg{counter1,counter2,...}
  \end{itemize}
  This contains a comma separated list of counter names which should be tracked for counting itself.
\end{docCommandArgs}

\end{docCommand}

\handrightnote Please note, that both \refCom{RegisterCounter} and \refCom{RegisterCounters} can be used only in the preamble of a document. 

\handrightnote It is safe to use \refCom{RegisterCounters} with just one counter name. 

\begin{docCommand}{PrepareTocCommand}{\marg{toc command}}
This command disables the usage of the automatic counter storage for ToC - like macros (\cs{tableofcontents},\cs{listoffigures},\cs{listoftables}, since those use \cs{chapter*} and confuse the tracking counter thereby. 

\begin{docCommandArgs}{PrepareTocCommand}
  \marg{toc command} This is intented to be a command such as \cs{tableofcontents} etc., but it could be any command actually. 
\end{docCommandArgs}
  
Please use this command with care!

By default, \cs{tableofcontents},\cs{listoffigures},\cs{listoftables} and \cs{printindex} are used with this feature. 
\tcbdocmarginnote{\tcbdocnew{2015-05-08}}
\end{docCommand}

\subsection{User macros}

\begin{docCommand}{GetStoredCounterValue}{\oarg{chapter number}\marg{counter}}
This macro gets the stored value of the counter (specified as 2nd argument) per chapter and stores this number to the counter \docCounter{cps@@tempcounterstorage}. If the counter could not be found, the result is -1.
This macro should be expandable. 
\begin{docCommandArgs}{GetStoredCounterValue}%
\begin{itemize}
  \item \oarg{chapter number}
    This optional argument contains the number of the chapter from which the counter value should be extracted. If this is not given, the current chapter is used. 
  \item \marg{counter}
    This is the name of of the counter whose per chapter value should be displayed.
  \end{itemize}
\end{docCommandArgs}
\end{docCommand}

\begin{docCommand}{FetchStoredCounterValue}{\oarg{chapter number}\marg{counter}}
\tcbdocmarginnote{\tcbdocnew{2015-06-01}}
This macro gets the stored value of the counter (specified as 2nd argument) per chapter and returns the value. This macro is expandable and is the convenience version of \cs{GetStoredCounterValue}. If the counter could not be found (i.e. the corresponding counter has not been used so far in the document) the result will be -1. 
\begin{docCommandArgs}{FetchStoredCounterValue}%
\begin{itemize}
  \item \oarg{chapter number}
    This optional argument contains the number of the chapter from which the counter value should be extracted. If this is not given, the current chapter is used. 
  \item \marg{counter}
    This is the name of of the counter whose per chapter value should be displayed.
  \end{itemize}
\end{docCommandArgs}

\end{docCommand}

\begin{docCommand}{IndividualCounterStatistics}{\oarg{chapter number}\marg{counter}}
This returns the total value of the counter (specified as 2nd argument) per chapter. 
\begin{docCommandArgs}{IndividualCounterStatistics}
\begin{itemize}
\item \oarg{chapter number}
    This optional argument contains the number of the chapter from which the counter value should be extracted. If this is not given, the current chapter is used. 
  \item \marg{counter}
    This is the name of of the counter whose per chapter value should be displayed together with the counter name. 
  \end{itemize}
\end{docCommandArgs}

\end{docCommand}


\begin{docCommand}{ShowStatistics}{\oarg{chapter number}}
This returns the all total values of the counters registered by \refCom{RegisterCounter} or \refCom{RegisterCounters} per chapter. 
\begin{docCommandArgs}{ShowStatistics}
\begin{itemize}
\item \oarg{chapter number}
    This optional argument contains the number of the chapter from which the counter value should be extracted. If this is not given, the current chapter is used. 
  \end{itemize}
\end{docCommandArgs}

Both \refCom{ShowStatistics} and \refCom{IndividualCounterStatistics} are defined to provide nothing if \refKey{final} is given as package option. 


\end{docCommand}


\begin{docCommand}{Fullstatistics}{}
\tcbdocmarginnote{\tcbdocnew{2015-05-07}}
  This will show an overview of all registered counters throughout the document (unless storage was locally disabled).
\end{docCommand}

\begin{tcblisting}{}
\Fullstatistics
\end{tcblisting}



\begin{docCommand}{StoreCounters}{}

This macro stores all registrated counter values to the file. 

%This command is automatically called before a new chapter starts and at the end of the document, but if there is only one chapter in file and some \cs{printindex} - like command pretty near the document end, the last counter values are not stored correctly. In this case, it's better to issue this command before \cs{printindex} manually, but not in other setups. 

\textit{Remark: This command was named \cs{StoreCountersPerChapter} in previous versions}
\end{docCommand}

\begin{docCommand}{StopCounting}{}

This macro stores all registrated counter values to the file. 

This command is automatically called at the end of the document, but can be used before too. It is useful, if there is some \cs{printindex} etc. at the end and only one chapter. In this case, the finalizing storage would not be done automatically. 

% new chapter starts and at the end of the document, but if there is only one chapter in file and some \cs{printindex} - like command pretty near the document end, the last counter values are not stored correctly. In this case, it's better to issue this command before \cs{printindex} manually, but not in other setups. 

\end{docCommand}

\begin{docCommand}{RestoreCounter}{\marg{counter}}
This macro restores the counter \marg{counter} to zero. 

\handrightnote It is not necessary to use this macro directly in almost any case. 
\end{docCommand}


\begin{docCommand}{RestoreCounters}{}
This macro restores all registrated counters to zero. This happens every time if a new driving section level is used.  
\end{docCommand}

\section{Informational macros}

\begin{docCommand}{numberofstoredcounters}{}
This macro just returns the number of registered counters. It will not return the internal counter name which holds the number. 
\end{docCommand}

\section{Conditionals}

The package knows some conditionals:

\begin{docCommand}{ifcpsstorage}{}
\tcbdocmarginnote{\tcbdocnew{2015-05-08}}
  This status variable enables or disables the storage of counters per chapter (section,$\ldots$). It is a classical \TeX\ \cs{newif} statement and can be set to true by saying \cs{cpsstoragetrue} or false \cs{cpsstorefalse}. However, there are two small macros to wrap this enabling or disabling into to more memorable names: \refCom{EnableCPSStorage} and \refCom{DisableCPSStorage}. 

\end{docCommand}

\begin{docCommand}{EnableCPSStorage}{}
Enables the storage of counters per chapter (etc.)
\tcbdocmarginnote{\tcbdocnew{2015-05-08}}
\end{docCommand}

\begin{docCommand}{DisableCPSStorage}{}
Enables the storage of counters per chapter (etc.)
\tcbdocmarginnote{\tcbdocnew{2015-05-08}}
\end{docCommand}

\begin{docCommand}{ifcpsdraftmode}{}
  This is a classical \TeX\ conditional defined by \cs{newif}. It can be used to enable draft mode locally by saying \cs{cpsdraftmodetrue} and disable in return using \cs{cpsdraftmodefalse}. 
\tcbdocmarginnote{\tcbdocnew{2015-05-03}}
\end{docCommand}



\clearpage

\section{Generated files}

The package uses the same approach as \LaTeX commands to write content to the table of content files. It creates \texttt{.cpsfoo} files, where \cs{foo} is the name of the relevant counter. Those files are constantly updated if the main document has been changed. It's safe to delete those files, however, the correct values appear only after the 2nd and consecutive runs. 

\section{Error messages}

If one of the tracked counters is deleted in the \refCom{RegisterCounters} - list between two compilation runs, there will be an error message. Just delete all relevant \texttt{*.cps*} files then and recompile twice.

\section{To-Do list}\label{section::todo}

\begin{itemize}
\item Better error handling (no checks for many features so far).
\item Squeeze the usage of multiple files for each counter value into a more sophisticated approach.
\item More options for fine control of the behaviour package and macros.
\item Easy - adaption for other documentclasses, especially for \classname{beamer}
\item Improve documentation

\end{itemize}

If you 

\begin{itemize}
  \item find bugs
  \item errors in the documentation
  \item have suggestions
  \item have feature requests
\end{itemize}

don't hesitate and contact me via \makeatletter christian.hupfer@yahoo.de\makeatother

\clearpage

\section{Acknowledgments}

I would like to express my gratitudes to the developpers of fine \LaTeX{} packages and of course
to the users at \url{tex.stackexchange.com}, especially to

\begin{itemize}
  \item Enrico Gregorio
  \item Joseph Wright
  \item David Carlisle
  \item Paulo Roberto Massa Cereda
  \item Werner Doe (;-))
  \item Johannes B\"ottcher (for some remarks/checking on KOMA related issues)
\end{itemize}

for their invaluable help on many questions on macros.

\vspace{2\baselineskip}
A special gratitude goes to Prof. Dr. Dr. Thomas Sturm for providing the wonderful \packagename{tcolorbox} package which was used to
write this documentation.

\clearpage

\section{Version history}
\begin{itemize}
\item 0.3:
\begin{itemize}
  \item Added some remarks about other tracklevels
  \item Added some remarks about \classname{beamer}
  \item Added \cs{FetchStoredCounterValue} for quicker access to the counter value, instead of using \docCounter{cps@@tempcounterstorage}. 
  \item Corrected the wrong name of the \cs{GetStoredCounterValue} in the documentation
\end{itemize}
\item 0.2:
 \begin{itemize}
 \item Introduced the possibility to disable the storage temporarily
 \item Fixed a severe bug concerning the file handle generation
 \item Added support for `tracklevel=option`, allowing for arbitray section levels as watch 
 \item Renamed some macros which had `Chapter` in name
 \item Added a check if the relevant section level sequence exists at all
 \item Added a total counter for the section level and limited the `\cs{GetTotalCounters}` max value
 \item Fixed typos in documentation
 \end{itemize}

\item 0.1: Initial version, fixed errors with \cs{dolistcsloop} for getting the counter values and replaced it with \cs{forlistcsloop}
\item 0.01: Bootstrap version


\end{itemize}

\clearpage
\StopCounting

%%%% Index of commands

\printindex

\end{document}