% \iffalse meta-comment
% !TEX program  = pdfLaTeX
%<*internal>
\iffalse
%</internal>
%<*readme>
The diadia package allows you to keep a diabetes diary.
Usually, this means keeping record of certain medical values
like blood sugar, blood pressure, pulse or weight. It might
also include other medical, pharmaceutical or nutritional
data (HbA1c, insulin doses, carbohydrate units). The diadia
package supports all of this plus more - simply by adding
more columns to the data file!
It is able to evaluate the data file and typesets formatted
tables and derived plots. Furthermore, it supports medication
charts and info boxes.

Supported languages: english, german
Feel free to provide other translation files! ;-)

License: LPPL

Changes in v1.1:

- added diadia.lua
  It provides the cut, compose and average modes for data 
  management
  
- moved style definitions to diadia.cfg

%</readme>
%<*data>
date        bsl1  bsl2  bsl3  id1 id2 id3 bps bpd weight  cu  pul
2015-02-18  182   197   196   nan nan 10  120 80  102.3   12  64
2015-02-19  190   232   159   12  9   9   130 85  102.1   12  68
2015-02-20  181   217   153   14  9   9   130 85  103.5   12  72
2015-02-21  154   160   146   13  7   9   100 60  102.8   12  60
2015-02-22  186   204   152   14  9   9   120 80  102.4   12  64
2015-02-23  190   170   131   14  8   9   130 85  102.0   12  68
2015-02-24  165   128   97    14  7   6   110 75  101.7   12  64
2015-02-25  160   123   129   11  5   7   130 85  101.3   12  68
2015-02-26  151   115   128   11  nan 7   120 80  100.9   12  64
2015-02-27  141   119   130   11  4   nan 130 85  101.6   12  68
2015-02-28  142   137   143   nan nan nan 120 80  101.2   12  64
2015-03-01  134   151   128   nan nan nan nan nan nan     nan nan
2015-03-02  145   124   116   nan nan nan nan nan nan     nan nan
2015-03-03  133   130   125   nan nan nan nan nan nan     nan nan
2015-03-04  138   153   nan   nan nan nan nan nan nan     nan nan
2015-03-06  122   150   130   nan nan nan nan nan nan     nan nan
2015-03-07  nan   nan   135   nan nan nan nan nan nan     nan nan
2015-03-08  132   146   119   nan nan nan nan nan nan     nan nan
2015-03-11  144   nan   124   nan nan nan nan nan nan     nan nan
2015-03-13  131   116   nan   nan nan nan nan nan nan     nan nan
2015-03-16  119   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-19  109   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-20  107   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-21  103   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-22  97    nan   nan   nan nan nan nan nan nan     nan nan
2015-03-23  111   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-24  96    nan   nan   nan nan nan nan nan nan     nan nan
2015-03-25  109   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-26  115   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-28  96    nan   nan   nan nan nan nan nan nan     nan nan
2015-03-31  90    nan   nan   nan nan nan nan nan nan     nan nan
2015-04-02  101   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-03  105   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-04  116   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-05  118   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-06  124   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-07  97    nan   nan   nan nan nan nan nan nan     nan nan
2015-04-08  111   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-09  97    nan   nan   nan nan nan nan nan nan     nan nan
2015-04-10  102   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-11  96    nan   nan   nan nan nan nan nan nan     nan nan
2015-04-12  104   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-13  105   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-14  105   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-15  125   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-16  102   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-17  102   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-18  97    nan   nan   nan nan nan nan nan nan     nan nan
2015-04-19  96    nan   nan   nan nan nan nan nan nan     nan nan
2015-04-20  119   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-21  101   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-22  96    nan   nan   nan nan nan nan nan nan     nan nan
2015-04-23  93    nan   nan   nan nan nan nan nan nan     nan nan
2015-04-24  108   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-25  114   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-26  95    nan   nan   nan nan nan nan nan nan     nan nan
2015-04-27  110   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-28  114   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-29  104   nan   nan   nan nan nan nan nan nan     nan nan
2015-04-30  99    nan   nan   nan nan nan nan nan nan     nan nan
%</data>
%<*dataavg>
date        value avg07 avg14 avg30 avg60 avg90
2015-02-18  182   182   182   182   182   182
2015-02-19  190   186   186   186   186   186
2015-02-20  181   184   184   184   184   184
2015-02-21  154   177   177   177   177   177
2015-02-22  186   179   179   179   179   179
2015-02-23  190   181   181   181   181   181
2015-02-24  165   178   178   178   178   178
2015-02-25  160   175   176   176   176   176
2015-02-26  151   170   173   173   173   173
2015-02-27  141   164   170   170   170   170
2015-02-28  142   162   167   167   167   167
2015-03-01  134   155   165   165   165   165
2015-03-02  145   148   163   163   163   163
2015-03-03  133   144   161   161   161   161
2015-03-04  138   141   158   159   159   159
2015-03-06  122   136   151   157   157   157
2015-03-08  132   134   146   156   156   156
2015-03-11  144   133   138   155   155   155
2015-03-13  131   136   136   154   154   154
2015-03-16  119   131   131   152   152   152
2015-03-19  109   120   126   150   150   150
2015-03-20  107   112   124   146   148   148
2015-03-21  103   110   121   142   146   146
2015-03-22  97    107   116   138   144   144
2015-03-23  111   105   115   136   143   143
2015-03-24  96    104   113   132   141   141
2015-03-25  109   105   109   128   140   140
2015-03-26  115   105   110   126   139   139
2015-03-28  96    104   106   121   137   137
2015-03-31  90    103   103   117   136   136
2015-04-02  101   96    103   113   135   135
2015-04-03  105   98    102   111   134   134
2015-04-04  116   103   104   111   133   133
2015-04-05  118   106   106   111   133   133
2015-04-06  124   109   107   112   132   132
2015-04-07  97    110   107   110   132   132
2015-04-08  111   110   107   110   131   131
2015-04-09  97    110   106   109   130   130
2015-04-10  102   109   105   107   129   129
2015-04-11  96    106   105   107   129   129
2015-04-12  104   104   105   106   128   128
2015-04-13  105   102   105   106   127   127
2015-04-14  105   103   106   106   127   127
2015-04-15  125   105   108   106   127   127
2015-04-16  102   106   108   106   126   126
2015-04-17  102   106   107   106   126   126
2015-04-18  97    106   106   105   125   125
2015-04-19  96    105   105   105   123   125
2015-04-20  119   107   104   105   122   124
2015-04-21  101   106   104   105   120   124
2015-04-22  96    102   103   105   119   123
2015-04-23  93    101   103   105   117   123
2015-04-24  108   101   104   105   115   123
2015-04-25  114   104   105   105   114   122
2015-04-26  95    104   104   104   113   122
2015-04-27  110   102   105   105   112   122
2015-04-28  114   104   105   105   111   122
2015-04-29  104   105   104   105   110   121
2015-04-30  99    106   103   105   110   121
%</dataavg>
%<*feb15>
date        bsl1  bsl2  bsl3  id1 id2 id3 bps bpd weight  cu  pul
2015-02-18  182   197   196   nan nan 10  120 80  102.3   12  64
2015-02-19  190   232   159   12  9   9   130 85  102.1   12  68
2015-02-20  181   217   153   14  9   9   130 85  103.5   12  72
2015-02-21  154   160   146   13  7   9   100 60  102.8   12  60
2015-02-22  186   204   152   14  9   9   120 80  102.4   12  64
2015-02-23  190   170   131   14  8   9   130 85  102.0   12  68
2015-02-24  165   128   97    14  7   6   110 75  101.7   12  64
2015-02-25  160   123   129   11  5   7   130 85  101.3   12  68
2015-02-26  151   115   128   11  nan 7   120 80  100.9   12  64
2015-02-27  141   119   130   11  4   nan 130 85  101.6   12  68
2015-02-28  142   137   143   nan nan nan 120 80  101.2   12  64
%</feb15>
%<*mar15>
date        bsl1  bsl2  bsl3  id1 id2 id3 bps bpd weight  cu  pul
2015-03-01  134   151   128   nan nan nan nan nan nan     nan nan
2015-03-02  145   124   116   nan nan nan nan nan nan     nan nan
2015-03-03  133   130   125   nan nan nan nan nan nan     nan nan
2015-03-04  138   153   nan   nan nan nan nan nan nan     nan nan
2015-03-06  122   150   130   nan nan nan nan nan nan     nan nan
2015-03-07  nan   nan   135   nan nan nan nan nan nan     nan nan
2015-03-08  132   146   119   nan nan nan nan nan nan     nan nan
2015-03-11  144   nan   124   nan nan nan nan nan nan     nan nan
2015-03-13  131   116   nan   nan nan nan nan nan nan     nan nan
2015-03-16  119   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-19  109   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-20  107   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-21  103   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-22  97    nan   nan   nan nan nan nan nan nan     nan nan
2015-03-23  111   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-24  96    nan   nan   nan nan nan nan nan nan     nan nan
2015-03-25  109   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-26  115   nan   nan   nan nan nan nan nan nan     nan nan
2015-03-28  96    nan   nan   nan nan nan nan nan nan     nan nan
2015-03-31  90    nan   nan   nan nan nan nan nan nan     nan nan
%</mar15>
%<*apr15>
date        value avg07 avg14 avg30 avg60 avg90
2015-04-02  101   96    103   113   135   135
2015-04-03  105   98    102   111   134   134
2015-04-04  116   103   104   111   133   133
2015-04-05  118   106   106   111   133   133
2015-04-06  124   109   107   112   132   132
2015-04-07  97    110   107   110   132   132
2015-04-08  111   110   107   110   131   131
2015-04-09  97    110   106   109   130   130
2015-04-10  102   109   105   107   129   129
2015-04-11  96    106   105   107   129   129
2015-04-12  104   104   105   106   128   128
2015-04-13  105   102   105   106   127   127
2015-04-14  105   103   106   106   127   127
2015-04-15  125   105   108   106   127   127
2015-04-16  102   106   108   106   126   126
2015-04-17  102   106   107   106   126   126
2015-04-18  97    106   106   105   125   125
2015-04-19  96    105   105   105   123   125
2015-04-20  119   107   104   105   122   124
2015-04-21  101   106   104   105   120   124
2015-04-22  96    102   103   105   119   123
2015-04-23  93    101   103   105   117   123
2015-04-24  108   101   104   105   115   123
2015-04-25  114   104   105   105   114   122
2015-04-26  95    104   104   104   113   122
2015-04-27  110   102   105   105   112   122
2015-04-28  114   104   105   105   111   122
2015-04-29  104   105   104   105   110   121
2015-04-30  99    106   103   105   110   121
%</apr15>
%<*hba1c>
date        hba1c
2015-02-18  10
2015-04-23  6
%</hba1c>
%<*fallback>
\DeclareTranslationFallback{dd-BloodSugar}{Blood Sugar}%
\DeclareTranslationFallback{dd-Insulin}{Insulin}%
\DeclareTranslationFallback{dd-BloodPressure}{Blood Pressure}%
\DeclareTranslationFallback{dd-Weight}{Weight}%
\DeclareTranslationFallback{dd-MedicationChart}{Medication Chart}%
\DeclareTranslationFallback{dd-issued}{issued}%
\DeclareTranslationFallback{dd-Pharmaceutical}{Pharmaceutical}%
\DeclareTranslationFallback{dd-Morning}{Morning}%
\DeclareTranslationFallback{dd-Noon}{Noon}%
\DeclareTranslationFallback{dd-Evening}{Evening}%
\DeclareTranslationFallback{dd-Night}{Night}%
\DeclareTranslationFallback{dd-Note}{Note}%
\DeclareTranslationFallback{dd-Info}{Info}%
\DeclareTranslationFallback{dd-Date}{Date}%
\DeclareTranslationFallback{dd-BSi}{BS(1)}%
\DeclareTranslationFallback{dd-BSii}{BS(2)}%
\DeclareTranslationFallback{dd-BSiii}{BS(3)}%
\DeclareTranslationFallback{dd-IDi}{I(1)}%
\DeclareTranslationFallback{dd-IDii}{I(2)}%
\DeclareTranslationFallback{dd-IDiii}{I(3)}%
\DeclareTranslationFallback{dd-BPs}{BP(s)}%
\DeclareTranslationFallback{dd-BPd}{BP(d)}%
\DeclareTranslationFallback{dd-Weight}{Weight}%
\DeclareTranslationFallback{dd-CU}{CU}%
\DeclareTranslationFallback{dd-Pulse}{Pulse}%
\DeclareTranslationFallback{dd-Hbaonec}{$\text{HbA}_{\text{1c}}$}%
\DeclareTranslationFallback{dd-Value}{Value}%
%</fallback>
%<*english>
\DeclareTranslation{English}{dd-BloodSugar}{Blood Sugar}%
\DeclareTranslation{English}{dd-Insulin}{Insulin}%
\DeclareTranslation{English}{dd-BloodPressure}{Blood Pressure}%
\DeclareTranslation{English}{dd-Weight}{Weight}%
\DeclareTranslation{English}{dd-MedicationChart}{Medication Chart}%
\DeclareTranslation{English}{dd-issued}{issued}%
\DeclareTranslation{English}{dd-Pharmaceutical}{Pharmaceutical}%
\DeclareTranslation{English}{dd-Morning}{Morning}%
\DeclareTranslation{English}{dd-Noon}{Noon}%
\DeclareTranslation{English}{dd-Evening}{Evening}%
\DeclareTranslation{English}{dd-Night}{Night}%
\DeclareTranslation{English}{dd-Note}{Note}%
\DeclareTranslation{English}{dd-Info}{Info}%
\DeclareTranslation{English}{dd-Date}{Date}%
\DeclareTranslation{English}{dd-BSi}{BS(1)}%
\DeclareTranslation{English}{dd-BSii}{BS(2)}%
\DeclareTranslation{English}{dd-BSiii}{BS(3)}%
\DeclareTranslation{English}{dd-IDi}{I(1)}%
\DeclareTranslation{English}{dd-IDii}{I(2)}%
\DeclareTranslation{English}{dd-IDiii}{I(3)}%
\DeclareTranslation{English}{dd-BPs}{BP(s)}%
\DeclareTranslation{English}{dd-BPd}{BP(d)}%
\DeclareTranslation{English}{dd-Weight}{Weight}%
\DeclareTranslation{English}{dd-CU}{CU}%
\DeclareTranslation{English}{dd-Pulse}{Pulse}%
\DeclareTranslation{English}{dd-Hbaonec}{$\text{HbA}_{\text{1c}}$}%
\DeclareTranslation{English}{dd-Value}{Value}%
%</english>
%<*german>
\DeclareTranslation{German}{dd-BloodSugar}{Blutzucker}%
\DeclareTranslation{German}{dd-Insulin}{Insulin}%
\DeclareTranslation{German}{dd-BloodPressure}{Blutdruck}%
\DeclareTranslation{German}{dd-Weight}{Gewicht}%
\DeclareTranslation{German}{dd-MedicationChart}{Medikamentenplan}%
\DeclareTranslation{German}{dd-issued}{ausgestellt}%
\DeclareTranslation{German}{dd-Pharmaceutical}{Medikament}%
\DeclareTranslation{German}{dd-Morning}{morgens}%
\DeclareTranslation{German}{dd-Noon}{mittags}%
\DeclareTranslation{German}{dd-Evening}{abends}%
\DeclareTranslation{German}{dd-Night}{nachts}%
\DeclareTranslation{German}{dd-Note}{Bemerkung}%
\DeclareTranslation{German}{dd-Info}{Info}%
\DeclareTranslation{German}{dd-Date}{Datum}%
\DeclareTranslation{German}{dd-BSi}{BZ(1)}%
\DeclareTranslation{German}{dd-BSii}{BZ(2)}%
\DeclareTranslation{German}{dd-BSiii}{BZ(3)}%
\DeclareTranslation{German}{dd-IDi}{I(1)}%
\DeclareTranslation{German}{dd-IDii}{I(2)}%
\DeclareTranslation{German}{dd-IDiii}{I(3)}%
\DeclareTranslation{German}{dd-BPs}{BD(s)}%
\DeclareTranslation{German}{dd-BPd}{BD(d)}%
\DeclareTranslation{German}{dd-Weight}{Gewicht}%
\DeclareTranslation{German}{dd-CU}{BE}%
\DeclareTranslation{German}{dd-Pulse}{Puls}%
\DeclareTranslation{German}{dd-Hbaonec}{$\text{HbA}_{\text{1c}}$}%
\DeclareTranslation{German}{dd-Value}{Wert}%
%</german>
%<*bibfile>
@misc{bib:pgfplots,
 author               = {Dr. Christian Feuers��nger},
 note                 = {\href{http://mirrors.ctan.org/graphics/pgf/contrib/pgfplots/doc/pgfplots.pdf}{http://mirrors.ctan.org/graphics/pgf/contrib/pgfplots/doc/pgfplots.pdf}},
 title                = {{Manual for Package pgfplots}},
 year                 = {2015},
 }

@misc{bib:pgfplotstable,
 author               = {Dr. Christian Feuers��nger},
 note                 = {\href{http://mirrors.ctan.org/graphics/pgf/contrib/pgfplots/doc/pgfplotstable.pdf}{http://mirrors.ctan.org/graphics/pgf/contrib/pgfplots/doc/pgfplotstable.pdf}},
 title                = {{Manual for Package pgfplotstable}},
 year                 = {2015},
 }
 
@misc{bib:tcolorbox,
 author               = {Sturm, Thomas F.},
 note                 = {\href{http://mirrors.ctan.org/macros/latex/contrib/tcolorbox/tcolorbox.pdf}{http://mirrors.ctan.org/macros/latex/contrib/tcolorbox/tcolorbox.pdf}},
 title                = {{The tcolorbox package}},
 year                 = {2015},
 }
 
@misc{bib:multicol,
 author               = {Mittelbach, Frank},
 note                 = {\href{http://mirrors.ctan.org/macros/latex/required/tools/multicol.pdf}{http://mirrors.ctan.org/macros/latex/required/tools/multicol.pdf}},
 title                = {{An environment for multicolumn output}},
 year                 = {2014},
 }

 @misc{bib:longtable,
 author               = {Carlisle, David},
 note                 = {\href{http://mirrors.ctan.org/macros/latex/required/tools/longtable.pdf}{http://mirrors.ctan.org/macros/latex/required/tools/longtable.pdf}},
 title                = {{The \texttt{longtable} package}},
 year                 = {2014},
 }

%</bibfile>
%<*examplefile>
\documentclass[a4paper,DIV=13,parskip]{scrreprt}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage[tabcolor=gray!40,tabstyle=advanced]{diadia}
\usepackage{bera}
\usepackage{marvosym}
\usepackage{hyperref}
\begin{document}
\pgfplotstableset{columns/date/.append style={date type={\day.\month.\year}}}
\pgfplotsset{xlabel=2015,
             tick label style={font=\footnotesize}}
\title{My Diabetes Diary}
\author{John Doe}
\maketitle
\centering
\chapter{Long term values}

\begin{diadiasidebyside}
\diadiatab{}{hba1c.dat}

\begin{diadiaplot}[plotstyle=hbaonec]{xmin=2015-02-01,xmax=2015-04-30}
\diadiaaddplot{}{x=date,y=hba1c}{hba1c.dat}
\end{diadiaplot}
\end{diadiasidebyside}

\vfill
\begin{diadiaplot}[plotstyle=bloodsugar]
      {width=\textwidth,
      height=11cm,
      legend style={at={(0.5,-0.15)},font=\footnotesize,anchor=north,legend columns=-1},
      xtick={2015-03-01,2015-04-01,2015-05-01},
      xmin=2015-02-18,
      xmax=2015-04-30}
\diadiaaddplot{plot4,nomarks}{x=date,y=avg90}{ddbsl1avg.dat}
\diadiaaddplot{plot3,nomarks}{x=date,y=avg30}{ddbsl1avg.dat}
\diadiaaddplot{plot2,nomarks}{x=date,y=avg07}{ddbsl1avg.dat}
\diadiaaddplot{plot1}{x=date,y=value}{ddbsl1avg.dat}
\legend{$\varnothing_{90}$,$\varnothing_{30}$,$\varnothing_{7}$,morning}
\end{diadiaplot}
\chapter{February 2015}
\section{Data}
\diadiatab{font=\small}{201502.dat}

\vspace{1cm}
\begin{diadiasidebyside}
\begin{diadiaplot}[plotstyle=bloodsugar]{xmin=2015-02-18,xmax=2015-02-28}
\diadiaaddplot{}{x=date,y=bsl1}{diadia.dat}
\diadiaaddplot{}{x=date,y=bsl2}{diadia.dat}
\diadiaaddplot{}{x=date,y=bsl3}{diadia.dat}
\legend{morning,noon,evening}
\end{diadiaplot}

\begin{diadiaplot}[plotstyle=insulin]{xmin=2015-02-18,xmax=2015-02-27}
\diadiaaddplot{}{x=date,y=id1}{diadia.dat}
\diadiaaddplot{}{x=date,y=id2}{diadia.dat}
\diadiaaddplot{}{x=date,y=id3}{diadia.dat}
\legend{morning,noon,evening}
\end{diadiaplot}

\begin{diadiaplot}[plotstyle=bloodpressure]{xmin=2015-02-18,xmax=2015-02-27}
\diadiaaddplot{}{x=date,y=bps}{diadia.dat}
\diadiaaddplot{}{x=date,y=bpd}{diadia.dat}
\legend{systolic,diastolic}
\end{diadiaplot}

\begin{diadiaplot}[plotstyle=pulse]{xmin=2015-02-18,xmax=2015-02-27}
\diadiaaddplot{}{x=date,y=pul}{diadia.dat}
\end{diadiaplot}
\end{diadiasidebyside}

\vspace{1cm}
\begin{diadiasidebyside}
\begin{diadiaplot}[plotstyle=weight]{xmin=2015-02-18,xmax=2015-02-27}
\diadiaaddplot{ddpweightplot}{x=date,y=weight}{diadia.dat}
\end{diadiaplot}

\begin{diadiaplot}[plotstyle=cu]{xmin=2015-02-18,xmax=2015-02-27,enlargelimits=.08}
\diadiaaddplot{}{x=date,y=cu}{diadia.dat}
\end{diadiaplot}
\end{diadiasidebyside}
\section{Pharmaceuticals}
\begin{medicationchart}{}{16.02.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{1}{1}{1}{0}{}
\mcentry{Insulin}{1}{1}{1}{0}{see data}
\mcentry{Unacid 3g}{1}{0}{1}{1}{infusion 08:00, 16:00, 00:00}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe}{0}{0}{1}{0}{}
\end{medicationchart}
\begin{medicationchart}{}{24.02.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Insulin}{1}{1}{1}{0}{see data}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe}{0}{0}{1}{0}{}
\end{medicationchart}
\begin{medicationchart}{}{28.02.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Metformin}{2}{0}{2}{0}{}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe}{0}{0}{1}{0}{}
\end{medicationchart}
\chapter{March 2015}
\section{Data}
\begin{diadiasidebyside}
\diadiatab{columns={date,bsl1,bsl2,bsl3}}{201503.dat}

\begin{diadiaplot}[plotstyle=bloodsugar]{xmin=2015-03-01,xmax=2015-03-31}
\diadiaaddplot{}{x=date,y=bsl1}{diadia.dat}
\diadiaaddplot{}{x=date,y=bsl2}{diadia.dat}
\diadiaaddplot{}{x=date,y=bsl3}{diadia.dat}
\legend{morning,noon,evening}
\end{diadiaplot}
\end{diadiasidebyside}
\section{Pharmaceuticals}
\begin{medicationchart}{}{03.03.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Januvia 100mg}{1}{0}{0}{0}{replaces Metformin due to op}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe}{0}{0}{1}{0}{}
\end{medicationchart}
\begin{medicationchart}{}{10.03.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Novaminsulfon Lichtenstein 500 mg}{1}{1}{1}{1}{}
\mcentry{Januvia 100mg}{1}{0}{0}{0}{}
\mcentry{Unacid 3g}{1}{0}{1}{1}{infusion 08:00, 16:00, 00:00}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe}{0}{0}{1}{0}{}
\end{medicationchart}
\begin{medicationchart}{}{20.03.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Novaminsulfon Lichtenstein 500 mg}{1}{1}{1}{1}{}
\mcentry{Unacid 3g}{1}{0}{1}{1}{infusion 08:00, 16:00, 00:00}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe}{0}{0}{1}{0}{}
\end{medicationchart}
\begin{medicationchart}{}{30.03.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Novaminsulfon Lichtenstein 500 mg}{1}{1}{1}{1}{}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe}{0}{0}{1}{0}{}
\end{medicationchart}
\chapter{April 2015}
\section{Data}
\begin{diadiasidebyside}
\diadiatab{columns={date,value,avg07,avg30,avg90}}{201504.dat}

\begin{diadiaplot}[plotstyle=bloodsugar]{xmin=2015-04-02,xmax=2015-04-29}
\annotation[text width=1.4cm]{2015-04-10}{123}{rise after discharge}
\diadiaaddplot{plot4,nomarks}{x=date,y=avg90}{ddbsl1avg.dat}
\diadiaaddplot{plot3,nomarks}{x=date,y=avg30}{ddbsl1avg.dat}
\diadiaaddplot{plot2,nomarks}{x=date,y=avg07}{ddbsl1avg.dat}
\diadiaaddplot{plot1}{x=date,y=value}{ddbsl1avg.dat}
\legend{$\varnothing_{90}$,$\varnothing_{30}$,$\varnothing_{7}$,morning}
\end{diadiaplot}
\end{diadiasidebyside}

\section{Pharmaceuticals}
\begin{medicationchart}{}{02.04.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Novaminsulfon Lichtenstein 500 mg}{1}{1}{1}{1}{}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe}{0}{0}{1}{0}{}
\end{medicationchart}

\begin{medicationchart}{}{07.04.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Novaminsulfon Lichtenstein 500 mg}{1}{1}{1}{1}{}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe Novartis}{0}{0}{1}{0}{}
\mcentry{Sultamicillin-ratiopharm 375mg}{1}{0}{1}{0}{}
\end{medicationchart}

\begin{medicationchart}{}{16.04.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Novaminsulfon Lichtenstein 500 mg}{1}{1}{1}{1}{}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe Novartis}{0}{0}{1}{0}{}
\mcentry{Amoclav 875mg + 125mg (Amoxicillin, Clavulans��ure) Hexal}{1}{0}{1}{0}{}
\end{medicationchart}

\begin{medicationchart}{}{20.04.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Novaminsulfon Lichtenstein 500 mg}{1}{1}{1}{1}{}
\mcentry{ASS protect 100mg}{0}{1}{0}{0}{}
\mcentry{Amoclav 875mg + 125mg (Amoxicillin, Clavulans��ure) Hexal}{1}{0}{1}{0}{}
\end{medicationchart}

\section{Misc.}

\infobox{width=8cm}{22.04.2015}{
Podiatrist appointment:

\bigskip
22.04.2015 11:30

\medskip
\Telefon\ 089/65831933
}
\end{document}
%</examplefile>
%<*manifest>
This work consists of the following files:

diadia.pdf
diadia.dtx
diadia-example.pdf
README
makefile

Files packaged in diadia.dtx:

diadia.sty
diadia.cfg
diadia-fallback.trsl
diadia-english.trsl
diadia-german.trsl
diadia.dat
201502.dat
201503.dat
201504.dat
hba1c.dat
diadia-example.tex
manifest.txt
%</manifest>
%<*internal>
\fi
\def\nameofplainTeX{plain}
\ifx\fmtname\nameofplainTeX\else
  \expandafter\begingroup
\fi
%</internal>
%<*install>
\input docstrip.tex
\keepsilent
\askforoverwritefalse
\preamble

Copyright (C) 2015 by:
Josef Kleber
<josef.kleber@gmx.de>

This file 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
2003/12/01 or later.

This work has the LPPL maintenance status "maintained".

The Current Maintainer of this work is Josef Kleber.

This work consists of all files listed in manifest.txt.

\endpreamble

\usedir{tex/latex/diadia}
\generate{
  \file{\jobname.sty}{\from{\jobname.dtx}{package}}
}
\generate{
  \file{\jobname.cfg}{\from{\jobname.dtx}{cfg}}
}
\generate{
  \file{\jobname-fallback.trsl}{\from{\jobname.dtx}{fallback}}
}
\generate{
  \file{\jobname-english.trsl}{\from{\jobname.dtx}{english}}
}
\generate{
  \file{\jobname-german.trsl}{\from{\jobname.dtx}{german}}
}
\generate{
  \file{\jobname-example}{\from{\jobname.dtx}{examplefile}}
}
\nopreamble\nopostamble
\usedir{scripts/diadia}
\generate{
  \file{\jobname.lua}{\from{\jobname.dtx}{lua}}
}
\usedir{doc/latex/diadia}
\generate{
  \file{\jobname.dat}{\from{\jobname.dtx}{data}}
}
\generate{
  \file{ddbsl1avg.dat}{\from{\jobname.dtx}{dataavg}}
}
%</install>
%<install>\endbatchfile
%<*internal>
\generate{
  \file{\jobname.dat}{\from{\jobname.dtx}{data}}
}
\generate{
  \file{201502.dat}{\from{\jobname.dtx}{feb15}}
}
\generate{
  \file{201503.dat}{\from{\jobname.dtx}{mar15}}
}
\generate{
  \file{201504.dat}{\from{\jobname.dtx}{apr15}}
}
\generate{
  \file{hba1c.dat}{\from{\jobname.dtx}{hba1c}}
}
\generate{
  \file{README.txt}{\from{\jobname.dtx}{readme}}
}
\generate{
  \file{manifest.txt}{\from{\jobname.dtx}{manifest}}
}
\generate{
  \file{\jobname.bib}{\from{\jobname.dtx}{bibfile}}
}
\ifx\fmtname\nameofplainTeX
  \expandafter\endbatchfile
\else
  \expandafter\endgroup
\fi
%</internal>
%<*driver>
\documentclass[a4paper]{ltxdoc}%
\usepackage[english]{babel}%
\usepackage[utf8]{inputenc}%
\usepackage[T1]{fontenc}%
\usepackage{textcomp}%
\usepackage{lmodern}%
\usepackage{bera}%
\usepackage{microtype}%
\usepackage{marginnote}%
\usepackage[svgnames,rgb]{xcolor}%
\usepackage{listings}%
\usepackage{makeidx}
\usepackage[numbered]{hypdoc}
\usepackage{ragged2e}%
\usepackage{url}%
\usepackage{csquotes}%
\usepackage{diadia}%
\usepackage{alltt}%
\usepackage{marvosym}%
\usepackage[automark,nouppercase]{scrpage2}
\usepackage{tikz}
\usetikzlibrary{calc}%
% turn off idiotic tikz error in doc generation
\makeatletter
\global\let\tikz@ensure@dollar@catcode=\relax
\makeatother
\usepackage{hyperref}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
\makeatletter
\setlength{\headheight}{1.1\baselineskip}%
\renewcommand\paragraph{\@startsection{paragraph}{4}{\z@}%
            {-2.5ex\@plus -1ex \@minus -.25ex}%
            {1.25ex \@plus .25ex}%
            {\normalfont\normalsize\bfseries}}
\setcounter{secnumdepth}{5}
\setcounter{tocdepth}{5}
\hypersetup{colorlinks=true,urlcolor=NavyBlue,linkcolor=NavyBlue,citecolor=CornflowerBlue}%
\lstset{literate=%
    {��}{{\"O}}1
    {��}{{\"A}}1
    {��}{{\"U}}1
    {��}{{\ss}}1
    {��}{{\"u}}1
    {��}{{\"a}}1
    {��}{{\"o}}1
    {~}{{\textasciitilde}}1
}
\lstset{language=[LaTeX]TeX,numbers=left,numberstyle=\tiny, basicstyle=\ttfamily, aboveskip=\baselineskip, frame=single, backgroundcolor=\color{LightGoldenrodYellow}, keywordstyle=\color{Blue},
emph={}}
\renewcommand{\maketitle}%
{%
  \thispagestyle{empty}%
  \pagecolor{Ivory}%
  \begin{titlepage}%
    \begin{tikzpicture}[remember picture,overlay]%
      \node[yshift=-2cm] at (current page.north west)%
      {%
        \begin{tikzpicture}[remember picture, overlay]%
          \draw[fill=CornflowerBlue,color=CornflowerBlue] (0,0) rectangle%
            (\paperwidth,2cm);%
          \draw[anchor=west,yshift=-4cm,xshift=3cm,color=NavyBlue] (0,0) node%
            {\parbox{15cm}{\RaggedRight\Huge\sffamily\textbf{\@title}}};%
          \draw[anchor=west,yshift=-5.5cm,xshift=3cm,color=NavyBlue] (0,0) node%
            {\parbox{15cm}{\huge\sffamily\textbf{\@fileversion}}};%
          \draw[anchor=west,yshift=-7.5cm,xshift=3cm,color=NavyBlue] (0,0) node%
            {\parbox{15cm}{\RaggedRight\huge\sffamily\textbf{\@subtitle}}};%
          \draw[anchor=west,yshift=-13.2cm,xshift=3cm,color=NavyBlue] (0,0) node%
            {\usebox\logo};%
          \draw[anchor=west,yshift=-18.5cm,xshift=3cm,color=NavyBlue] (0,0) node%
            {\parbox{15cm}{\huge\sffamily\textbf{\@date}}};%
          \draw[anchor=west,yshift=-20.5cm,xshift=3cm,color=NavyBlue] (0,0) node%
            {\parbox{15cm}{\Large\sffamily{\@authorline\\\textbf{\@author}}}};%
        \end{tikzpicture}%
      };%
      \node[yshift=0cm] at (current page.south west)%
      {%
        \begin{tikzpicture}[remember picture, overlay]%
          \draw[fill=NavyBlue,color=NavyBlue,yshift=6cm,xshift=2cm] (0,0) rectangle (0.2cm,19cm);%
          \draw[fill=CornflowerBlue,color=CornflowerBlue] (0,0) rectangle (\paperwidth,2cm);%
          \draw[anchor=west,yshift=1cm,xshift=3cm,color=NavyBlue] (0,0) node%
            {\parbox{15cm}{\large\sffamily{\@refline}}};%
        \end{tikzpicture}%
      };%
    \end{tikzpicture}%
  \end{titlepage}%
  \pagecolor{white}%
}%
%
%
\newcommand*{\@tikzhead}[1]%
{%
  \begin{tikzpicture}[remember picture,overlay]%
    \node[yshift=-2cm] at (current page.north west)%
    {%
      \begin{tikzpicture}[remember picture, overlay]%
        \draw[fill=CornflowerBlue] (0,0) rectangle (\paperwidth,2cm);%
        \draw[anchor=west,yshift=1cm,xshift=1.5cm,color=NavyBlue] (0,0) node%
          {\parbox{15cm}{\LARGE\sffamily\textbf{\@title}}};%
        \node[anchor=east,xshift=.9\paperwidth,rectangle,%
              rounded corners=15pt,inner sep=11pt,fill=NavyBlue]%
              {\color{white}\textsc{#1}};%
      \end{tikzpicture}%
    };%
  \end{tikzpicture}%
}%
\clearscrheadings%
\ihead{\@tikzhead{\headmark}}%
\cfoot{\upshape\thepage}%
\pagestyle{scrheadings}%
%
\newcommand*{\Headline}[1]{\@mkboth{#1}{#1}}%
%
\renewcommand{\headfont}{\normalfont\mdseries\scshape}
%
\gdef\@subtitle{}%
\providecommand*{\Subtitle}[1]{\gdef\@subtitle{#1}}%
\gdef\@fileversion{}%
\providecommand*{\Fileversion}[1]{\gdef\@fileversion{#1}}%
\gdef\@author{}%
\providecommand*{\Author}[1]{\gdef\@author{#1}}%
\gdef\@authorline{Package author:}%
\providecommand*{\Authorline}[1]{\gdef\@authorline{#1}}%
\gdef\@refline{}%
\providecommand*{\Refline}[1]{\gdef\@refline{#1}}%
\gdef\and{\unskip{}, }%
\newcommand\doubledash{-\kern0.5pt-}
\def\enoteformat{\rightskip\z@ \leftskip\z@ \parindent=1em\leavevmode\llap{\makeenmark}}
\def\XeLaTeX{Xe\LaTeX}%
%
\newenvironment{optionlist}
{\begin{trivlist}\setlength\leftskip{2em}}
{\end{trivlist}}
\newcommand\optitem[3]{\item [\texttt{\textbf{\textcolor{DodgerBlue}{#1}} \lbrack\textcolor{Crimson}{#2}\rbrack}] #3}
\newcommand\optitemii[2]{\item [\texttt{\textbf{\textcolor{DodgerBlue}{#1}}}] \texttt{\lbrack\textcolor{Crimson}{#2}\rbrack}}
\newcommand\optitempgf[2]{\item [\texttt{\textbf{\textcolor{DodgerBlue}{#1}}}] #2}
\renewcommand\tableofcontents%
{%
  %\section*{\contentsname}%
  \@mkboth{%
  \MakeUppercase\contentsname}{\MakeUppercase\contentsname}%
  \@starttoc{toc}%
}%
%
\newcommand\env[1]{\texttt{#1}\SortIndex{#1}{\string{\string\ttfamily\space#1\string} (environment)}%
                   \SortIndex{environments:>#1}{\string{\string\ttfamily\space#1\string}}}%
\newcommand\stylename[1]{\texttt{#1}\SortIndex{#1}{{\ttfamily #1} (Style file)}%
                     \SortIndex{Style file>#1}{\texttt{#1}}}%
\newcommand\package[1]{\texttt{#1}\SortIndex{#1}{{\ttfamily #1} (Package)}%
                     \SortIndex{Package>#1}{\texttt{#1}}}%
\newcommand*\margcs[1]{\marginnote{\hbadness=10000\RaggedLeft\scriptsize #1}}%
\def\PrintIndex{\clearpage\Headline{Index}\@input@{\jobname.ind}%
                \global\let\PrintIndex\@empty}
                \renewenvironment{theindex}
               {\if@twocolumn
                  \@restonecolfalse
                \else
                  \@restonecoltrue
                \fi
                \columnseprule \z@
                \columnsep 35\p@
\def\see##1##2{\textit{See} ##1}%
\def\seealso##1##2{\textit{See also} ##1}%
\long\def\cmd##1{\cs{\expandafter\cmd@to@cs\string##1}}%
\def\@url##1{\url@break\ttt{##1}\endgroup}%
\def\ttt{\begingroup\@sanitize\ttfamily\@ttt}%
\def\@ttt##1{##1\endgroup}%
\mathchardef\save@secnumdepth\c@secnumdepth
\c@secnumdepth\m@ne
                \phantomsection%
                \twocolumn%[\section{\indexname}]%
                \refstepcounter{section}
                \addcontentsline{toc}{section}{\protect\numberline{\thesection}Index}%
\c@secnumdepth\save@secnumdepth
                %\thispagestyle{plain}
                \parindent\z@
                \parskip\z@ \@plus .3\p@\relax
                \let\item\@idxitem}
               {\if@restonecol\onecolumn\else\clearpage\fi}
\setlength\parindent{0pt}%
\newcommand*\myref[1]{[see: \ref{#1} on page \pageref{#1}]}
\makeatother
\begin{document}
  \DocInput{\jobname.dtx}
\end{document}
%</driver>
% \fi
%
% \GetFileInfo{\jobname.sty}
%
% \hypersetup{pdfauthor={Josef Kleber},pdftitle={A LaTeX package for keeping a diabetes diary},pdfsubject={Documentation for LaTeX package \filename}}%
% \lstset{language=[LaTeX]TeX,numbers=left,numberstyle=\tiny, basicstyle=\ttfamily, aboveskip=\baselineskip, frame=single, backgroundcolor=\color{LightGoldenrodYellow}, keywordstyle=\color{Blue},
% emph={medicationchart,diadiasidebyside,diadiaplot},emphstyle=\color{Tomato}, 
% emph={[2]columns,column,chol,string,replace,name,ddpuser,font,tabstyle,tabcolor,date,type,bsl1,bsl2,bsl3,plotstyle,xlabel,tick,label,style,xmin,xmax,x,y,
% text,width,very,thick,fill,draw,mark,options,anchor},
% emphstyle={[2]\color{OliveDrab}},
% morekeywords={pgfplotsset,pgfplotstableset,diadiatab,diadiaaddplot,legend,annotation,setlimit,mcentry,infobox,Telefon,varnothing,lastdate}}
% \DoNotIndex{\,,\\,\begin,\end,\begingroup,\endgroup,\csname,\def,\else,\endcsname,\equal,\expandafter,
% \fi,\gdef,\ifnum,\ifthenelse,\immediate,\MessageBreak,\NeedsTeXFormat,\newcommand,\renewcommand,\NewEnviron,\newenvironment,\newif,
% \PackageInfo,\PackageError,\ProcessOptionsX,\ProvidesPackage,\relax,\RequirePackage,
% \space,\errmessage,\ExecuteOptionsX,\n}
%
% \setlength\parskip{6pt}%
% \bibliographystyle{plain}
% \title{\filename}%
% \Subtitle{A \LaTeX{} package for keeping a diabetes diary}%
% \author{Josef Kleber}
% \Fileversion{\fileversion}
% \date{\filedate}
% \Refline{\href{mailto:josef.kleber@gmx.de}{\texttt{josef.kleber@gmx.de}}\\\href{https://bitbucket.org/kleberj/diadia/}{\texttt{https://bitbucket.org/kleberj/diadia/}}}
% \newsavebox\logo
% \savebox\logo{%
% \begin{diadiaplot}[plotstyle=bloodsugar]
%                   {
%                     xlabel=2015,
%                     tick label style={font=\footnotesize},
%                     legend style={draw=NavyBlue},
%                     ytick={90,120,150,210,240},
%                     xmin=2015-02-18,
%                     xmax=2015-02-28,
%                     width=9cm,
%                     color=NavyBlue
%                   }
%   \diadiaaddplot{}{x=date,y=bsl1}{diadia.dat}
%   \diadiaaddplot{}{x=date,y=bsl2}{diadia.dat}
%   \diadiaaddplot{}{x=date,y=bsl3}{diadia.dat}
%   \annotation[text width=0.9cm]{2015-02-22}{215}{My first annoation}
%   \setlimit[very thick]{140,180}
%   \legend{morning,noon,evening}
% \end{diadiaplot}
%}
% \maketitle
% \stepcounter{page}
% \tableofcontents
% \clearpage
%
%
%\StopEventually{^^A
% {
% \clearpage
% \raggedright
% \nocite{*}
% \bibliography{\jobname}
% }
% \clearpage
%  \PrintChanges
%  \PrintIndex
%}
%
% \Headline{Abstract}
% \begin{abstract}
% The \package{diadia} package allows you to keep a diabetes diary.
% Usually, this means keeping record of certain medical values
% like blood sugar, blood pressure, pulse or weight. It might
% also include other medical, pharmaceutical or nutritional
% data ($\text{HbA}_{\text{1c}}$, insulin doses, carbohydrate units). The \package{diadia}
% package supports all of this plus more - simply by adding
% more columns to the data file!
%
% It is able to evaluate the data file and typesets formatted
% tables and derived plots. Furthermore, it supports medication
% charts and info boxes.
% \end{abstract}
% \clearpage
%
% \section{Options}
% The following options can be set as package options with global scope,
% as well as command options with local scope:
%
% \begin{optionlist}
%   \optitem{tabstyle}{simple}{sets the style of the tables}
%   \optitem{tabcolor}{none}{sets the color of the table}
%   \optitem{plotstyle}{none}{sets the predefined style of your plot}
%   \optitem{plotclosedcycle}{false}{sets an implicit \cmd\closedcycle\ command inside a filled plot (weight). This is usually controlled by \texttt{plotstyle.}}
%   \optitem{mcnotewidth}{3cm}{sets the width of the note column in medication charts}
%   \optitem{columnsep}{18pt}{sets the distance of columns inside \env{diadiasidebyside} environments}
%   \optitem{columnseprule}{0pt}{sets the width of the separation rule between columns}
%   \optitem{columnseprulecolor}{\cmd\normalcolor}{sets the color of the separation rule. The \package{diadia} package follows the usage of options in the \package{multicol}\cite{bib:multicol} package. Thus, this option must be a color command like \cmd\color\{blue\} -- not just a color name!}
% \end{optionlist}
%
% Furthermore, the design of this package is defined by several Ti\textit{k}z-like styles.
% These can be (re)defined with \cmd\tikzstyle, \cmd\tcbset, \cmd\pgfplotsset\ or \cmd\pgfplotstableset\ with the usual syntax:
%
% \verb|key/.style={}| or\\
% \verb|key/.append style={}|, e.g.:
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\pgfplotsset{ddpuser/.style={thin}}
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
% These definitions are out-sourced into \texttt{diadia.cfg}. You can copy this file to your local \TeX\ tree
% to alter definitions or to add new ones.
%
% Among other things, it defines the general plot styles \texttt{ddpuser} and \texttt{ddpdefault}, as well as the special
% plot styles \texttt{ddpweight}, \texttt{ddpbloodpressure}, \texttt{ddpinsulin}, \texttt{ddpbloodsugar}, \texttt{ddppulse},
% \texttt{ddpcu} and \texttt{ddphbaonec}. Additionally, it defines the special styles \texttt{ddpweightplot} for
% filled weight plots and \texttt{nomarks} for \enquote{deleting} the data marks.
%
% Furthermore, it defines the appearance of tables in general and header elements. It defines the usually used color cycle list
% \texttt{diadiacyclelist} and make the color styles also available as \texttt{plot1} to \texttt{plot4}.
%
% Moreover, it defines the \texttt{ddpannotation}, \texttt{setlimit} and \texttt{ddaddplotfill} for filled plots (\texttt{teal!50}).
% Finally, it defines the box styles \texttt{medicationchart} and \texttt{infobox} based on \texttt{ddboxdefault}.
% See section \ref{sec:config} on page \pageref{sec:config} for a more or less detailed description of the config file.
%
% The \package{pgfplots}\cite{bib:pgfplots}, \package{pgfplotstable}\cite{bib:pgfplotstable} and \package{tcolorbox}\cite{bib:tcolorbox} packages offer
% zillions of options to influence the design!
% \Headline{2 Storing data}
% \section{Storing data}
% The very simple basic structure of the data file is as follows:
%
% \begin{center}
%   \begin{alltt}\input{201502.dat}\end{alltt}
% \end{center}
%
% It is a simple text file with columns seperated by <space> or <tab>.
% Thus, empty cells must be marked either with an empty group (\texttt{\{\}}) or the special marker \texttt{nan} (not a number).
% In plots, empty groups will simply be ignored, where as \texttt{nan} will result in jumps in the plots.
% The data file starts with a header row. Its keys will be used to plot the data or to typeset tables.
%
% \begin{center}
% \begin{tabular}{>{\bfseries}rl}
% \toprule
% \multicolumn{2}{c}{standard keys} \\\midrule
% date & entry date \\
% bsl1-3 & three blood sugar levels (morning, noon, evening) \\
% id1-3 & three insulin doses \\
% bps & blood pressure (systolic) \\
% bpd & blood pressure (diastolic) \\
% weight & weight \\
% cu & carbohydrate units \\
% pul & pulse\\
% hba1c\footnotemark & $\text{HbA}_{\text{1c}}$ \\
% \bottomrule
% \end{tabular}
% \footnotetext{long term values can be stored in a seperate data file}
% \end{center}
%
% You can easily add other columns or delete existing ones. You can even rename these columns, but you would have to redefine a lot of internal commands.
% You must not neither rename the \texttt{date} key nor change its format (YYYY-MM-DD)!
%
% Lets say you want to add a cholesterol column, then you should at least define the following key:
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\pgfplotstableset
{
  columns/chol/.style=
  {
    string replace={nan}{},
    column name={Chol.}
  }
}
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
% This sets the column name in tables and prevents that \texttt{nan} values are printed. For plots you only need the \texttt{chol} key!
%
% \section{Editing data}
% \label{sec:diadialua}
%
% The \texttt{diadia.lua} script offers several ways to edit your data file. At the moment it supports the following modes:
% \begin{itemize}
% \item[\texttt{cut}] This mode allows you to cut chunks of data out of your data file, e.g. for preparing data files for monthly reports.
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
$ diadia -m cut -i diadia.dat -o 201504.dat -s 2015-04-01
-e 2015-04-30
set mode to cut
reading data file diadia.dat
writing data file 201504.dat
\end{lstlisting}
% \iffalse
%</example>
% \fi
% \item[\texttt{compose}] This mode allows you to rearrange the columns of your data file, e.g. as preperation for the \texttt{average} mode
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
$ diadia -m compose -i diadia.dat -o ddbsl1.dat -c 1,2
set mode to compose
reading data file diadia.dat
writing data file ddbs1.dat
\end{lstlisting}
% \iffalse
%</example>
% \fi
% \item[\texttt{average}] This mode allows you to create a new data file. By definition, it takes the first
% two columns (\texttt{date} and \texttt{value}) of the input file and adds columns for the 7, 14, 30,
% 60 and 90 days average.\footnote {Your data files should be big enough, as a correct 90 day average can
% of course only be calculated with data starting at least 90 days \textbf{before} the date period you
% want to visualize.}
%
% \clearpage
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
$ diadia -m average -i ddbsl1.dat -o bsl1.dat
set mode to average
reading data file ddbs1.dat
writing data file bsl1.dat
\end{lstlisting}
% \iffalse
%</example>
% \fi
% \end{itemize} 
%
% As shown in the examples, the script supports the following command line options:
% 
% \begin{optionlist}
%   \optitempgf{-m}{specify the mode (cut\textbar{}compose\textbar{}average)}
%   \optitempgf{-i}{specify the input file}
%   \optitempgf{-o}{specify the output file}
%   \optitempgf{-c}{specify a list of columns for \texttt{compose} mode, e.g. \texttt{-c 1,2}\footnote{even crazy things like \texttt{-c 1,2,2,2} work}}
%   \optitempgf{-s}{specify the start date (\texttt{YYYY-MM-DD}) in \texttt{cut} and \texttt{average} mode}
%   \optitempgf{-e}{specify the end date}
%   \optitempgf{-v}{prints version information}
%   \optitempgf{-h}{prints help information}
% \end{optionlist}
%
% Furthermore, the script provides the following error codes:
% 
% \begin{optionlist}
%   \optitempgf{\space0}{as usual, everythings fine!}
%   \optitempgf{\space1}{general error}
%   \optitempgf{11}{no \texttt{mode} specified}
%   \optitempgf{12}{invalid \texttt{mode}}
%   \optitempgf{21}{wrong date format (\texttt{YYYY-MM-DD})}
% \end{optionlist}
%
%
% \section{Managing data}
%
% In principal, it's enough to have just one data file, but it might be worth considering to use a seperate data
% file for long term values like $\text{HbA}_{\text{1c}}$. You might also want to have monthly data files for the
% \cmd\diadiatab\ command. These can easily be created with the \texttt{cut} mode of \texttt{diadia.lua}! You can simplify
% your data management for example with a \texttt{makefile}\footnote{This works also on a Windows system with an environment like Cygwin.}:
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
NAME  = mydiadia
TODAY = $(shell date +'%Y-%m-%d')
RM    = rm -f

all: doc

today:
	echo "\def\lastdate{$(TODAY)}" >today.dat

doc: today
	pdflatex $(NAME)
	pdflatex $(NAME)
	openar ./$(NAME).pdf &

dat: 
	diadia -m cut -i diadia.data -o diadia.dat -s 2015-02-18 
-e $(TODAY)
	diadia -m cut -i longterm.data -o longterm.dat -s 2015-02
-18 -e $(TODAY)
	diadia -m average -i diadia.dat -o ddbsl1avg.dat
	diadia -m cut -i diadia.dat -o 201502.dat -s 2015-02-18 -
e 2015-02-28
	diadia -m cut -i diadia.dat -o 201503.dat -s 2015-03-01 -
e 2015-03-31
	diadia -m average -i diadia.dat -o 201504.dat -s 2015-04-
01 -e 2015-04-30
	diadia -m average -i diadia.dat -o 201505.dat -s 2015-05-
01 -e $(TODAY)

clean:
	$(RM) *.aux *.log *.out *.toc

cleanall: clean
	$(RM) $(NAME).pdf *.dat

.PHONY: all today doc dat clean cleanall
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
% It provides the two major targets \texttt{dat} for data management and \texttt{doc} for
% creating your diary.\footnote{\texttt{openar} is a simple shell script, which opens the resulting \texttt{PDF} file with Adobe Reader.}
% Furthermore, it provides \texttt{today.dat},\footnote{simply \texttt{\cmd\input\{today.dat\}}}
% which provides the \cmd\lastdate\ macro with current date in \texttt{YYYY-MM-DD} format.
% Finally, it provides the cleanup targets \texttt{clean} and \texttt{cleanall}.
%
% \section{Presenting data}
% \subsection{Tables}
%
% The \cmd\diadiatab\margcs{\cmd\diadiatab\oarg{options}\\\marg{pgfplotstable options}\marg{file}} command typesets the data file specified
% by \marg{file} in a table. Now, you can typeset the example data in a formatted table:
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\diadiatab{font=\scriptsize}{201502.dat}
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
%\diadiatab{font=\scriptsize}{201502.dat}
%
% \bigskip
% You can influence the design with the following options:
%
% \begin{optionlist}
%   \optitem{tabstyle}{\underline{simple}, advanced}{}
%   \optitem{tabcolor}{\underline{none}, color name}{}
% \end{optionlist}
% 
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\diadiatab[tabstyle=advanced,tabcolor=gray!30]
          {font=\scriptsize}{201502.dat}
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
% \diadiatab[tabstyle=advanced,tabcolor=gray!30]{font=\scriptsize}{201502.dat}
%
% \bigskip
% Here's a list of interesting keys for \marg{pgfplotstable options}, but there are of course
% much more in the \package{pgfplotstable}\cite{bib:pgfplotstable} package documentation!
%
% \begin{optionlist}
%   \optitempgf{font}{accepts usual font commads}
%   \optitempgf{columns}{takes a list of columns, which should be typeset}
%   \optitempgf{column name}{sets the column heading (replacement of \texttt{key})}
%   \optitempgf{date type}{sets the date format}
% \end{optionlist}
%  
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\diadiatab[tabstyle=advanced,tabcolor=gray!30]
          {
            font=\small,
            columns={date,bsl1,bsl2,bsl3},
            columns/bsl1/.append style={column name={B1}},
            columns/bsl2/.append style={column name={B2}},
            columns/bsl3/.append style={column name={B3}},
            columns/date/.append style={
              date type={\day.\month.\year}}
          }
          {201502.dat}
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
% \diadiatab[tabstyle=advanced,tabcolor=gray!30]
%           {
%             font=\small,
%             columns={date,bsl1,bsl2,bsl3},
%             columns/bsl1/.append style={column name={B1}},
%             columns/bsl2/.append style={column name={B2}},
%             columns/bsl3/.append style={column name={B3}},
%             columns/date/.append style={
%               date type={\day.\month.\year}}
%           }
%           {201502.dat}
%
% \bigskip
% Note, that the data file was never changed!
%
% Unfortunately, the \package{pgfplotstable} package does not offer a simple method to limit the output
% of the table to certain dates, as the \package{pgfplots} package offers with the \texttt{xmin} and \texttt{xmax} keys.
% Thus, you have to prepare piecewise data files for monthly reports or so. See section \ref{sec:diadialua} on  page
% \pageref{sec:diadialua} for a simple solution!
%
% Furthermore, \package{diadia} does not support page breaks for tables. The documentation of the \package{pgfplotstable}\cite[p. 21]{bib:pgfplotstable}
% package describes a way out by using a \package{longtable}\cite{bib:longtable} if you need to typeset long tables!
%
% \subsection{Plots}
% The \env{diadiaplot}\margcs{\cmd\begin\{diadiaplot\}\oarg{options}\\\marg{pgfplots options}\\...\\\cmd\end\{diadiaplot\}}
% environment provides a typical plot structure, where you can add elements like plots, annotations or a legend.
% It will typeset the basic frame of the data plot.
%
% \begin{samepage}
% Possible options:
%
% \begin{optionlist}
%   \optitemii{plotstyle}{\underline{none}, bloodsugar, bloodpressure, insulin, weight, cu, pulse, hbaonec}
%   \optitem{plotclosedcycle}{\underline{false}, true}{}
% \end{optionlist}
% \end{samepage}
%
% The \cmd\diadiaaddplot\margcs{\cmd\diadiaaddplot\marg{addplot options}\\\marg{key mappings}\marg{file}} command adds a data plot to the basic frame.
% The keys specified in \marg{addplot options} are added to the predefined plot options.
% By contrast, with the starred version \cmd\diadiaaddplot*\margcs{\cmd\diadiaaddplot*\marg{addplot options}\\\marg{key mappings}\marg{file}},
% the keys specified in \marg{addplot options} will completely replace the predefined plot options.
%
% The \cmd\legend\margcs{\cmd\legend\marg{label list}} command will typeset a legend under the plot.
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\begin{diadiaplot}[plotstyle=bloodsugar]
                  {
                    xlabel=2015,
                    tick label style={font=\footnotesize},
                    xmin=2015-02-18,
                    xmax=2015-02-28
                  }
  \diadiaaddplot{}{x=date,y=bsl1}{diadia.dat}
  \diadiaaddplot{}{x=date,y=bsl2}{diadia.dat}
  \diadiaaddplot{}{x=date,y=bsl3}{diadia.dat}
  \legend{morning,noon,evening}
\end{diadiaplot}
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
% \begin{diadiaplot}[plotstyle=bloodsugar]
%                   {
%                     xlabel=2015,
%                     tick label style={font=\footnotesize},
%                     xmin=2015-02-18,
%                     xmax=2015-02-28
%                   }
%   \diadiaaddplot{}{x=date,y=bsl1}{diadia.dat}
%   \diadiaaddplot{}{x=date,y=bsl2}{diadia.dat}
%   \diadiaaddplot{}{x=date,y=bsl3}{diadia.dat}
%   \legend{morning,noon,evening}
% \end{diadiaplot}
%
% \bigskip
% The \cmd\annotation\margcs{\cmd\annotation\oarg{Ti\textit{k}z options}\\\marg{x}\marg{y}\marg{annotation}} command allows you to annotate
% your plot values. The x and y coordinates must be declared in the context of the plot. That is usually a date and a plot value.
%
% With the \cmd\setlimit\margcs{\cmd\setlimit\oarg{Ti\textit{k}z options}\\\marg{limit list}} command, you can set general and/or individual
% limits agreed with your doctor.
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\begin{diadiaplot}[plotstyle=bloodsugar]
                  {
                    xlabel=2015,
                    tick label style={font=\footnotesize},
                    xmin=2015-02-18,
                    xmax=2015-02-28
                  }
  \diadiaaddplot{}{x=date,y=bsl1}{diadia.dat}
  \diadiaaddplot{}{x=date,y=bsl2}{diadia.dat}
  \diadiaaddplot{}{x=date,y=bsl3}{diadia.dat}
  \annotation[text width=0.9cm]{2015-02-22}{215}
             {My first annoation}
  \setlimit[very thick]{140,180}
  \legend{morning,noon,evening}
\end{diadiaplot}
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
% \begin{diadiaplot}[plotstyle=bloodsugar]
%                   {
%                     xlabel=2015,
%                     tick label style={font=\footnotesize},
%                     legend style={at={(0.5,-0.18)},
%                        font=\footnotesize,anchor=north,
%                        legend columns=-1},
%                     xmin=2015-02-18,
%                     xmax=2015-02-28
%                   }
%   \diadiaaddplot{}{x=date,y=bsl1}{diadia.dat}
%   \diadiaaddplot{}{x=date,y=bsl2}{diadia.dat}
%   \diadiaaddplot{}{x=date,y=bsl3}{diadia.dat}
%   \annotation[text width=0.9cm]{2015-02-22}{215}{My first annoation}
%   \setlimit[very thick]{140,180}
%   \legend{morning,noon,evening}
% \end{diadiaplot}
%
% \bigskip
% If you have calculated average values with the \texttt{diadia.lua} script, you can also plot them like this:
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\begin{diadiaplot}[plotstyle=bloodsugar]
                  {
                    width=\textwidth,
                    xlabel=2015,
                    tick label style={font=\footnotesize},
                    legend style={at={(0.5,-0.15)},
                      font=\footnotesize,anchor=north,
                      legend columns=-1},
                    xmin=2015-02-18,
                    xmax=2015-04-30
                  }
  \diadiaaddplot{plot4,nomarks}{x=date,y=avg90}{ddbsl1avg.dat}
  \diadiaaddplot{plot3,nomarks}{x=date,y=avg30}{ddbsl1avg.dat}
  \diadiaaddplot{plot2,nomarks}{x=date,y=avg07}{ddbsl1avg.dat}
  \diadiaaddplot{plot1}{x=date,y=value}{ddbsl1avg.dat}
  \legend{$\varnothing_{90}$,$\varnothing_{30}$,$\varnothing_{7}$,
          morning}
\end{diadiaplot}
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
% \begin{diadiaplot}[plotstyle=bloodsugar]
%                   {
%                     width=\textwidth,
%                     xlabel=2015,
%                     tick label style={font=\footnotesize},
%                     legend style={at={(0.5,-0.15)},
%                       font=\footnotesize,anchor=north,
%                       legend columns=-1},
%                     xmin=2015-02-18,
%                     xmax=2015-04-30
%                   }
%   \diadiaaddplot{plot4,nomarks}{x=date,y=avg90}{ddbsl1avg.dat}
%   \diadiaaddplot{plot3,nomarks}{x=date,y=avg30}{ddbsl1avg.dat}
%   \diadiaaddplot{plot2,nomarks}{x=date,y=avg07}{ddbsl1avg.dat}
%   \diadiaaddplot{plot1}{x=date,y=value}{ddbsl1avg.dat}
%   \legend{$\varnothing_{90}$,$\varnothing_{30}$,$\varnothing_{7}$,morning}
% \end{diadiaplot}
%
% \bigskip
% Here's a list of interesting keys for \marg{pgfplots options}, but there are of course
% much more in the \package{pgfplots}\cite{bib:pgfplots} package documentation!
%
% \begin{optionlist}
%   \optitempgf{width}{sets the width of the data plot. Furthermore, there are the special \texttt{normalsize}, \texttt{small}, \texttt{footnotesize} and \texttt{tiny} keys}
%   \optitempgf{height}{usually, a 1:1 aspect ratio is used}
%   \optitempgf{xlabel}{sets a label under the plot, usually the year}
%   \optitempgf{ylabel}{sets a label left to the plot, usually controlled by \texttt{plotstyle}}
%   \optitempgf{xmin}{sets the start date of the plot}
%   \optitempgf{xmax}{sets the end date of the plot}
%   \optitempgf{tick label style}{sets the style of tick labels, usually the font size (see examples)}
%   \optitempgf{ytick}{takes a list of values for y ticks, if you are not happy with the standard choice}
% \end{optionlist}
%  
% \subsection{Medication charts}
%
% The \env{medicationchart}\margcs{\cmd\begin\{medicationchart\}\oarg{options}\\\marg{tcolorbox options}\marg{date}\\...\\\cmd\end\{medicationchart\}} 
% environment allows you to typeset a medication chart. That is, a list of your pharmaceuticals and how to take them. 	Internally, you must use
% the standard systax of a 6 column tabular. Or you simply use the \cmd\mcentry\margcs{\cmd\mcentry\marg{pharmaceutical}\marg{morning}\\\marg{noon}\marg{evening}\marg{night}\marg{note}} command.
%
% \begin{samepage}
% Possible options:
%
% \begin{optionlist}
%   \optitem{mcnotewidth}{\underline{3cm}}{}
% \end{optionlist}
% \end{samepage}
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\begin{medicationchart}{}{07.04.2015}
\mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
\mcentry{Novaminsulfon Lichtenstein 500 mg}{1}{1}{1}{1}{}
\mcentry{Mono-Embolex 3000 I.E. Prophylaxe Novartis}{0}{0}{1}{0}{}
\mcentry{Sultamicillin-ratiopharm 375mg}{1}{0}{1}{0}{}
\end{medicationchart}
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
% \begin{medicationchart}{}{07.04.2015}
%   \mcentry{Oxycodon-HCI STADA 10mg Retardtabletten}{0}{0}{1}{0}{}
%   \mcentry{Novaminsulfon Lichtenstein 500 mg}{1}{1}{1}{1}{}
%   \mcentry{Mono-Embolex 3000 I.E. Prophylaxe Novartis}{0}{0}{1}{0}{}
%   \mcentry{Sultamicillin-ratiopharm 375mg}{1}{0}{1}{0}{}
% \end{medicationchart}
%
% \subsection{Info boxes}
%
% The \cmd\infobox\margcs{\cmd\infobox\marg{tcolorbox options}\\\marg{date}\marg{information}} 
% environment allows you to typeset info boxes.
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\infobox{width=8cm}{22.04.2015}{%
Podiatrist appointment:

\bigskip
22.04.2015 11:30

\medskip
\Telefon\ 089/65831933
}%
\end{lstlisting}
% \iffalse
%</example>
% \fi
%
% \infobox{width=8cm}{22.04.2015}{%
% Podiatrist appointment:
%
% \bigskip
% 22.04.2015 11:30
%
% \medskip
% \Telefon\ 089/65831933
% }%
%
% \subsection{Misc.}
%
% The \env{diadiasidebyside}\margcs{\cmd\begin\{diadiasidebyside\}\oarg{options}\\...\\\cmd\end\{diadiasidebyside\}} 
% environment is a wrappper for the \env{multicol}\cite{bib:multicol} environment with a two column layout and offers the following options:
%
% \begin{optionlist}
%   \optitem{columnsep}{\underline{18pt}}{}
%   \optitem{columnseprule}{\underline{0pt}}{}
%   \optitem{columnseprulecolor}{\underline{\cmd\normalcolor}}{}
% \end{optionlist}
%
% For plots it sets the width to \cmd\columnwidth, so there's no need to adjust the width!
%
% \iffalse
%<*example>
% \fi
\begin{lstlisting}
\begin{diadiasidebyside}
\pgfplotsset{xlabel=2015,tick label style={font=\footnotesize}}
\begin{diadiaplot}[plotstyle=bloodpressure]
                  {
                    xmin=2015-02-18,
                    xmax=2015-02-27
                  }
\diadiaaddplot{}{x=date,y=bps}{diadia.dat}
\diadiaaddplot{}{x=date,y=bpd}{diadia.dat}
\legend{systolic,diastolic}
\end{diadiaplot}

\begin{diadiaplot}[plotstyle=weight]
                  {
                    xmin=2015-02-18,
                    xmax=2015-02-27
                  }
\diadiaaddplot{lime,mark options={fill=lime!50!black},
               mark=otimes*,draw=lime!75!black}
              {x=date,y=weight}{diadia.dat}
\end{diadiaplot}
\end{diadiasidebyside}
\end{lstlisting}
% \iffalse
%</example>
% \fi
% \vspace{1cm}
% \begin{diadiasidebyside}
% \pgfplotsset{xlabel=2015,tick label style={font=\footnotesize}}
% \begin{diadiaplot}[plotstyle=bloodpressure]
%                   {
%                     xmin=2015-02-18,
%                     xmax=2015-02-27
%                   }
% \diadiaaddplot{}{x=date,y=bps}{diadia.dat}
% \diadiaaddplot{}{x=date,y=bpd}{diadia.dat}
% \legend{systolic,diastolic}
% \end{diadiaplot}
%
% \begin{diadiaplot}[plotstyle=weight]
%                   {
%                     xmin=2015-02-18,
%                     xmax=2015-02-27
%                   }
% \diadiaaddplot{lime,mark options={fill=lime!50!black},
%                mark=otimes*,draw=lime!75!black}
%               {x=date,y=weight}{diadia.dat}
% \end{diadiaplot}
% \end{diadiasidebyside}
%
% \clearpage
% \section{Implementation}
% \subsection{diadia.sty}
% \changes{v1.0}{2015/05/11}{CTAN upload}
%    \begin{macrocode}
%<*package>
%    \end{macrocode}
% First, we provide the \LaTeX\ package \package{diadia}.
%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}%
\ProvidesPackage{diadia}[2015/05/20 v1.1 diadia.sty - Josef Kleber (C) 2015]%
%    \end{macrocode}
% We load the \texttt{xkeyval} package and define a helper macro to define the (global) options.
%    \begin{macrocode}
\RequirePackage{xkeyval}%
%
\newcommand*\DD@JK@define@key[4]%
{%
  \expandafter\gdef\csname#1@#3\endcsname{#4}%
  \define@key{#2.sty}{#3}[#4]%
  {%
    \expandafter\gdef\csname#1@#3\endcsname{##1}%
  }%
  \define@key{#2}{#3}%
  {%
    \expandafter\def\csname#1@#3\endcsname{##1}%
  }%
}%
%    \end{macrocode}
% Now, we can define the options and execute them with defaults. 
%    \begin{macrocode}
\DD@JK@define@key{DD@JK}{diadia}{tabstyle}{simple}%
\DD@JK@define@key{DD@JK}{diadia}{tabcolor}{none}%
\DD@JK@define@key{DD@JK}{diadia}{plotstyle}{none}%
\DD@JK@define@key{DD@JK}{diadia}{plotclosedcycle}{false}%
\DD@JK@define@key{DD@JK}{diadia}{mcnotewidth}{3cm}%
\DD@JK@define@key{DD@JK}{diadia}{columnsep}{18pt}%
\DD@JK@define@key{DD@JK}{diadia}{columnseprule}{0pt}%
\DD@JK@define@key{DD@JK}{diadia}{columnseprulecolor}{\normalcolor}%
%
\ExecuteOptionsX{tabstyle,tabcolor,plotstyle,plotclosedcycle,mcnotewidth,%
                 columnsep,columnseprule,columnseprulecolor}%
\ProcessOptionsX*\relax%
%    \end{macrocode}
% We load the needed packages and libraries!
%    \begin{macrocode}
\RequirePackage{pgfplots}%
\RequirePackage{pgfplotstable}%
\RequirePackage{pgfcalendar}%
\RequirePackage{tabularx}%
\RequirePackage{booktabs}%
\RequirePackage{colortbl}%
\RequirePackage{ifthen}%
\RequirePackage{calc}%
\RequirePackage{translations}%
\RequirePackage{amsmath}%
\RequirePackage[many]{tcolorbox}%
\RequirePackage{environ}%
\RequirePackage{multicol}%
\RequirePackage{amssymb}%
%
\usepgfplotslibrary{dateplot}%
%
\def\DD@JK@closedcycle{}%
\def\DD@JK@addplotdefault{}%
%    \end{macrocode}
% We load the translation files for supported languages and map the translations of the active language to macros!
%    \begin{macrocode}
\input{diadia-fallback.trsl}%
\input{diadia-english.trsl}%
\input{diadia-german.trsl}%
%
\def\DD@JK@trans@BloodSugar{\GetTranslation{dd-BloodSugar}}%
\def\DD@JK@trans@Insulin{\GetTranslation{dd-Insulin}}%
\def\DD@JK@trans@BloodPressure{\GetTranslation{dd-BloodPressure}}%
\def\DD@JK@trans@Weight{\GetTranslation{dd-Weight}}%
\def\DD@JK@trans@MedicationChart{\GetTranslation{dd-MedicationChart}}%
\def\DD@JK@trans@issued{\GetTranslation{dd-issued}}%
\def\DD@JK@trans@Pharmaceutical{\GetTranslation{dd-Pharmaceutical}}%
\def\DD@JK@trans@Morning{\GetTranslation{dd-Morning}}%
\def\DD@JK@trans@Noon{\GetTranslation{dd-Noon}}%
\def\DD@JK@trans@Evening{\GetTranslation{dd-Evening}}%
\def\DD@JK@trans@Night{\GetTranslation{dd-Night}}%
\def\DD@JK@trans@Note{\GetTranslation{dd-Note}}%
\def\DD@JK@trans@Info{\GetTranslation{dd-Info}}%
\def\DD@JK@trans@Date{\GetTranslation{dd-Date}}%
\def\DD@JK@trans@BSi{\GetTranslation{dd-BSi}}%
\def\DD@JK@trans@BSii{\GetTranslation{dd-BSii}}%
\def\DD@JK@trans@BSiii{\GetTranslation{dd-BSiii}}%
\def\DD@JK@trans@IDi{\GetTranslation{dd-IDi}}%
\def\DD@JK@trans@IDii{\GetTranslation{dd-IDii}}%
\def\DD@JK@trans@IDiii{\GetTranslation{dd-IDiii}}%
\def\DD@JK@trans@BPs{\GetTranslation{dd-BPs}}%
\def\DD@JK@trans@BPd{\GetTranslation{dd-BPd}}%
\def\DD@JK@trans@Weight{\GetTranslation{dd-Weight}}%
\def\DD@JK@trans@CU{\GetTranslation{dd-CU}}%
\def\DD@JK@trans@Pulse{\GetTranslation{dd-Pulse}}%
\def\DD@JK@trans@Hbaonec{\GetTranslation{dd-Hbaonec}}%
\def\DD@JK@trans@Value{\GetTranslation{dd-Value}}%
%    \end{macrocode}
% We define two new tabular types Z (ragged right X type) and Y (ragged right p with \texttt{mcnotewidth} width).
%    \begin{macrocode}
\newcolumntype{Z}{>{\raggedright\let\newline\\\arraybackslash}X}%
\newcolumntype{Y}{>{\raggedright\let\newline\\\arraybackslash}p{\DD@JK@mcnotewidth}}%
%    \end{macrocode}
% We load the \texttt{diadia.cfg} config file. It holds all kind of style definitions. You can copy this
% file to your local \TeX\ tree and alter the definitions or add new ones! 
%    \begin{macrocode}
\IfFileExists{diadia.cfg}%
{%
  \input{diadia.cfg}%
}%
{%
  \PackageError{diadia}{diadia.cfg not found}%
  {Please install diadia.cfg! The style definitions are missing!}%
}%
%    \end{macrocode}
% \begin{macro}{\annotation}
% With this command you can annotate your plots. You must use x/y coordinates in the context of your plot. Thus the x coordinate is usually a date.
%
% \cs{annotation}\oarg{Ti\textit{k}z options}\marg{x}\marg{y}\marg{annotation}
%    \begin{macrocode}
\newcommand*{\annotation}[4][]%
{%
  \node[ddpannotation,#1] at (#2,#3) {#4};%
}%
%    \end{macrocode}
%  \end{macro}
% \begin{macro}{\diadiatab}
% The \cmd\diadiatab\ command allows you to typeset your data in a formatted table.
%
% \cs{diadiatab}\oarg{options}\marg{pgfplotstable options}\marg{file}
%    \begin{macrocode}
\newcommand*{\diadiatab}[3][]%
{%
  \begingroup%
  %    \end{macrocode}
% Initially, we evaluate the options and set \texttt{pgfplotstable} options accordingly.
%    \begin{macrocode}
    \setkeys{diadia}{#1}%
    \ifthenelse{\equal{\DD@JK@tabstyle}{simple}}%
    {}%
    {%
      \ifthenelse{\equal{\DD@JK@tabstyle}{advanced}}%
      {%
        \pgfplotstableset%
        {%
          every head row/.style={before row=\toprule,after row=\midrule},%
          every last row/.style={after row=\bottomrule}%
        }%
      }%
      {}%
    }%
    \ifthenelse{\equal{\DD@JK@tabcolor}{none}}%
    {}%
    {%
      \pgfplotstableset%
      {%
        every even row/.style={before row={\rowcolor{\DD@JK@tabcolor}}}%
      }%
    }%
%    \end{macrocode}
% Finally, we typeset the table.
%    \begin{macrocode}
    \pgfplotstabletypeset[#2]{#3}%
  \endgroup%
}%
%    \end{macrocode}
%  \end{macro}
% \begin{macro}{\diadiaaddplot}
% The \cmd\diadiaddplot\ command adds a data plot. First of all, it checks for a * and calls
% \cmd\@@diadiaaddplot or \cmd\@@diadiaaddplot!
%
% \cs{diadiaaddplot}\marg{pgfplots options}\marg{key mapping}\marg{file}
%    \begin{macrocode}
\newcommand*\diadiaaddplot{\@ifstar\@@diadiaaddplot\@diadiaaddplot}%
%    \end{macrocode}
%  \end{macro}
%    \begin{macrocode}
\newcommand*\@diadiaaddplot[4][]%
{%
  \addplot+[\DD@JK@addplotdefault,#2] table[#3] {#4}\DD@JK@closedcycle;%
}%
%
\newcommand*\@@diadiaaddplot[4][]%
{%
  \addplot[#2] table[#3] {#4}\DD@JK@closedcycle;%
}%
%    \end{macrocode}
% \begin{environment}{diadiaplot}
% The \env{diadiaplot} environment is a wrapper for the \env{tikzpicture} and \env{axis} environments!
%
%    \begin{macrocode}
\newenvironment{diadiaplot}[2][]%
{%
%    \end{macrocode}
% We use the \texttt{baseline} option to have all plots on the same baseline. Important for sidebyside
% plots with different legends!
%    \begin{macrocode}
  \begin{tikzpicture}[baseline]%
%    \end{macrocode}
% We evalute the options and set the \cmd\DD@JK@closedcycle\ and \cmd\DD@JK@ddpmode\ macros accordingly.
%    \begin{macrocode}
    \setkeys{diadia}{#1}%
    \ifthenelse{\equal{\DD@JK@plotclosedcycle}{true}}%
    {\def\DD@JK@closedcycle{\closedcycle}}%
    {\def\DD@JK@closedcycle{}}%
    \def\DD@JK@ddpmode{}%
    \ifthenelse{\equal{\DD@JK@plotstyle}{none}}%
    {%
      \def\DD@JK@ddpmode{}%
    }%
    {%
      \ifthenelse{\equal{\DD@JK@plotstyle}{weight}}%
      {%
        \def\DD@JK@ddpmode{ddpweight}%
        \def\DD@JK@closedcycle{\closedcycle}%
      }%
      {%
        \ifthenelse{\equal{\DD@JK@plotstyle}{bloodpressure}}%
        {%
          \def\DD@JK@ddpmode{ddpbloodpressure}%
        }%
        {%
          \ifthenelse{\equal{\DD@JK@plotstyle}{insulin}}%
          {%
            \def\DD@JK@ddpmode{ddpinsulin}%
          }%
          {%
            \ifthenelse{\equal{\DD@JK@plotstyle}{bloodsugar}}%
            {%
              \def\DD@JK@ddpmode{ddpbloodsugar}%
            }%
            {%
              \ifthenelse{\equal{\DD@JK@plotstyle}{pulse}}%
              {%
                \def\DD@JK@ddpmode{ddppulse}%
              }%
              {%
                \ifthenelse{\equal{\DD@JK@plotstyle}{cu}}%
                {%
                  \def\DD@JK@ddpmode{ddpcu}%
                  \def\DD@JK@addplotdefault{ddaddplotfill}%
                }%
                {%
                  \ifthenelse{\equal{\DD@JK@plotstyle}{hbaonec}}%
                  {%
                    \def\DD@JK@ddpmode{ddphbaonec}%
                    \def\DD@JK@addplotdefault{ddaddplotfill}%
                  }%
                  {}%
                }%
              }%
            }%
          }%
        }%
      }%
    }%
%    \end{macrocode}
% We start the \texttt{axis} environment with the right plot style.
%    \begin{macrocode}
    \begin{axis}[ddpdefault,%
                 \DD@JK@ddpmode,%
                 #2%
                ]%
}%
{%
    \end{axis}%
  \end{tikzpicture}%
}%
%    \end{macrocode}
% \end{environment}
% \begin{macro}{\mcentry}
% The \cmd\mcentry\ command provides a simple interface for a six column tabular entry needed inside a \env{medicationchart} environment.
%
% \cs{mcentry}\marg{pharmaceutical}\marg{morning}\marg{noon}\marg{evening}\marg{night}\marg{note}
%    \begin{macrocode}
\newcommand*{\mcentry}[6]%
{%
  #1 & #2 & #3 & #4 & #5 & #6 \\%
}%
%    \end{macrocode}
%  \end{macro}
% \begin{environment}{medicationchart}
% The \env{medicationchart} environment allows you to typeset a medication chart. It uses the \package{environ} package to collect
% the environment body in the \cmd\Body\ macro. It is later used in a \texttt{medicationchart} style \texttt{tcolorbox} box.
%
%    \begin{macrocode}
\NewEnviron{medicationchart}[3][]%
{%
  \begingroup%
    \setkeys{diadia}{#1}%
    \tcbox[medicationchart,%
           title={\DD@JK@trans@MedicationChart\space (\DD@JK@trans@issued: #3)},#2]%
    {%
      \renewcommand{\arraystretch}{1.2}%
      \begin{tabularx}{\textwidth-13.64pt}{Z||r|r|r|r||Y}%
        \DD@JK@trans@Pharmaceutical & \DD@JK@trans@Morning & \DD@JK@trans@Noon &%
        \DD@JK@trans@Evening & \DD@JK@trans@Night & \DD@JK@trans@Note\\\hline\hline%
        \BODY%
      \end{tabularx}%
    }%
  \endgroup%
}%
%    \end{macrocode}
% \end{environment}
% \begin{macro}{\infobox}
% The \cmd\infobox\ allows you to typeset arbitrary material into a \texttt{infobox} style \texttt{tcolorbox} box.
%
% \cs{infobox}\marg{tcolorbox options}\marg{date}\marg{info}
%    \begin{macrocode}
\newcommand{\infobox}[3]%
{%
  \begin{tcolorbox}[infobox,title={\DD@JK@trans@Info\space (#2)},#1]%
    #3%
  \end{tcolorbox}%
}%
%    \end{macrocode}
% \end{macro}
% \begin{environment}{diadiasidebyside}
% The \env{diadiasidebyside} environment allows you to typeset (narrow) tables and plots sidebyside.
% It supports the \texttt{columnsep}, \texttt{columnseprule} and \texttt{columnseprulecolor} options of the \package{multicol} package.
%
%    \begin{macrocode}
\newenvironment{diadiasidebyside}[1][]%
{%
  \setkeys{diadia}{#1}%
  \setlength{\columnsep}{\DD@JK@columnsep}%
  \setlength{\columnseprule}{\DD@JK@columnseprule}%
  \def\columnseprulecolor{\DD@JK@columnseprulecolor}%
  \pgfplotsset{width=\columnwidth}%
  \begin{multicols}{2}%
}%
{%
  \end{multicols}%
}%
%    \end{macrocode}
% \end{environment}
% \begin{macro}{\setlimit}
% The \cmd\setlimit\ command allows you to add limits to your plot!
%
% \cs{setlimit}\oarg{Tikz options}\marg{limit list}
%    \begin{macrocode}
\newcommand*{\setlimit}[2][]%
{%
  \pgfplotsset{%
                extra y ticks={#2},%
                extra tick style={grid=major, major grid style={setlimit, #1}}%
              }%
}%
%    \end{macrocode}
%  \end{macro}
%    \begin{macrocode}
%</package>
%    \end{macrocode}
% \subsection{diadia.cfg}
% \label{sec:config}
% \changes{v1.1}{2015/05/17}{added diadia.cfg}
%    \begin{macrocode}
%<*cfg>
%    \end{macrocode}
% We set \texttt{pgfplot} compat mode to 1.12 and the \texttt{date ZERO} key to \texttt{2015-01-01}.
% Sometimes, values are plotted at the wrong date. Then you should adjust the \texttt{date ZERO} key
% to the start date of your data to avoid rounding errors in date calculation.
%    \begin{macrocode}
\pgfplotsset{%
  compat=1.12,%
  date ZERO=2015-01-01%
}%
%    \end{macrocode}
% We define some \texttt{pgfplots} styles with priority order: \texttt{ddpdefault} $\rightarrow$ \texttt{ddpuser} $\rightarrow$
% \{\texttt{ddpbloodsugar}\textbar\texttt{ddpinsulin}\textbar\texttt{ddpbloodpressure}\textbar\texttt{ddpweight}\textbar\texttt{ddpcu}\textbar\texttt{ddppulse}\textbar\newline\texttt{ddphbaonec}\}
%
% Thus, you can redefine \texttt{ddpuser} to adjust the general design set by \texttt{ddpdefault}. Furthermore, we define
% a \texttt{ddpweightplot} to use our standard design also in weight plots, as area style plots use their own color cycle list.
%    \begin{macrocode}
\pgfplotsset{%
  ddpuser/.style=%
  {},%
  ddpdefault/.style=%
  {%
    thick,%
    date coordinates in=x,%
    cycle list name=diadiacyclelist,%
    tick align=inside,%
    unbounded coords=jump,%
    xticklabel={\day.\month.},%
    legend style={at={(0.5,-0.25)},%
      font=\footnotesize,%
      anchor=north,%
      legend columns=-1},%
    ddpuser%
  },%
  ddpweight/.style=%
  {%
    smooth,%
    area style,%
    ylabel=\DD@JK@trans@Weight%
  },%
  ddpweightplot/.style=%
  {%
    teal,%
    fill=teal!50,%
    mark=halfcircle*,%
    every mark/.append style={solid,fill=.!80!black}%
  },%
  ddpbloodpressure/.style=%
  {%
    ylabel=\DD@JK@trans@BloodPressure%
  },%
  ddpinsulin/.style=%
  {%
    ylabel=\DD@JK@trans@Insulin%
  },%
  ddpbloodsugar/.style=%
  {%
    smooth,%
    ylabel=\DD@JK@trans@BloodSugar%
  },%
  ddppulse/.style=%
  {%
    smooth,%
    ylabel=\DD@JK@trans@Pulse%
  },%
  ddpcu/.style=%
  {%
    ybar,%
    ylabel=\DD@JK@trans@CU%
  },%
  ddphbaonec/.style=%
  {%
    ybar,%
    ylabel=\DD@JK@trans@Hbaonec%
  },
  nomarks/.style=%
  {%
    mark={},
    every mark/.style={}%
  }%
}%
%    \end{macrocode}
% We set some sensible defaults for \cmd\diadiatab
%
% \begin{itemize}
% \item replace \texttt{nan} with empty string
% \item replace empty cells with --
% \item define \texttt{date} column as \texttt{date type}
% \item define \texttt{weight} and \texttt{hba1c} columns as \texttt{fixed,fixed zerofill,precision=1}
% \end{itemize}
%
%    \begin{macrocode}
\pgfplotstableset%
{%
  empty cells with={--},%
  columns/date/.style={date type},%
  columns/bsl1/.style={string replace={nan}{}},%
  columns/bsl2/.style={string replace={nan}{}},%
  columns/bsl3/.style={string replace={nan}{}},%
  columns/id1/.style={string replace={nan}{}},%
  columns/id2/.style={string replace={nan}{}},%
  columns/id3/.style={string replace={nan}{}},%
  columns/bps/.style={string replace={nan}{}},%
  columns/bpd/.style={string replace={nan}{}},%
  columns/weight/.style={fixed,fixed zerofill,precision=1,string replace={nan}{}},%
  columns/cu/.style={string replace={nan}{}},%
  columns/pul/.style={string replace={nan}{}},%
  columns/hba1c/.style={fixed,fixed zerofill,precision=1,string replace={nan}{}},%
  columns/value/.style={string replace={nan}{}},%
  columns/avg07/.style={string replace={nan}{}},%
  columns/avg14/.style={string replace={nan}{}},%
  columns/avg30/.style={string replace={nan}{}},%
  columns/avg60/.style={string replace={nan}{}},%
  columns/avg90/.style={string replace={nan}{}}%
}%
%    \end{macrocode}
% Now, we append the language dependent column headers to the column style!
%    \begin{macrocode}
\pgfplotstableset%
{%
  columns/date/.append style={column name={\DD@JK@trans@Date}},%
  columns/bsl1/.append style={column name={\DD@JK@trans@BSi}},%
  columns/bsl2/.append style={column name={\DD@JK@trans@BSii}},%
  columns/bsl3/.append style={column name={\DD@JK@trans@BSiii}},%
  columns/id1/.append style={column name={\DD@JK@trans@IDi}},%
  columns/id2/.append style={column name={\DD@JK@trans@IDii}},%
  columns/id3/.append style={column name={\DD@JK@trans@IDiii}},%
  columns/bps/.append style={column name={\DD@JK@trans@BPs}},%
  columns/bpd/.append style={column name={\DD@JK@trans@BPd}},%
  columns/weight/.append style={column name={\DD@JK@trans@Weight}},%
  columns/cu/.append style={column name={\DD@JK@trans@CU}},%
  columns/pul/.append style={column name={\DD@JK@trans@Pulse}},%
  columns/hba1c/.append style={column name={\DD@JK@trans@Hbaonec}},%
  columns/value/.append style={column name={\DD@JK@trans@Value}},%
  columns/avg07/.append style={column name={$\varnothing_{7}$}},%
  columns/avg14/.append style={column name={$\varnothing_{14}$}},%
  columns/avg30/.append style={column name={$\varnothing_{30}$}},%
  columns/avg60/.append style={column name={$\varnothing_{60}$}},%
  columns/avg90/.append style={column name={$\varnothing_{90}$}},%
}%
%    \end{macrocode}
% We define the \texttt{diadiacyclelist} color cycle list used in plots. You may adjust it to your needs.
% Furthermore, we make these styles available as \texttt{plot1}, ..., \texttt{plot4}.
%    \begin{macrocode}
\pgfplotscreateplotcyclelist{diadiacyclelist}%
{%
  {teal,mark=halfcircle*,every mark/.append style={solid,fill=.!80!black}},%
  {orange,mark=halfcircle*,every mark/.append style={solid,fill=.!80!black,rotate=180}},%
  {cyan,mark=o,every mark/.append style={solid,fill=.!80!black}},%
  {yellow,mark=star,every mark/.append style={solid,fill=.!80!black}}%
}%
\tikzset%
{%
  plot1/.style=%
  {%
    teal,%
    mark=halfcircle*,%
    every mark/.append style={solid,fill=.!80!black}%
  },%
  plot2/.style=%
  {%
    orange,%
    mark=halfcircle*,%
    every mark/.append style={solid,fill=.!80!black,rotate=180}%
  },%
  plot3/.style=%
  {%
    cyan,%
    mark=o,%
    every mark/.append style={solid,fill=.!80!black}%
  },%
  plot4/.style=%
  {%
    yellow,%
    mark=star,%
    every mark/.append style={solid,fill=.!80!black}%
  }%  
}%
%    \end{macrocode}
% We define the Ti\textit{k}z styles for annotations and limits.
%    \begin{macrocode}
\tikzset%
{%
  ddpannotation/.style=%
  {%
    fill=yellow!50!white,%
    rectangle,%
    rounded corners=3pt,%
    font=\tiny%
  },%
  setlimit/.style=%
  {%
    red,%
    thick%
  },%
  ddaddplotfill/.style=%
  {%
    fill=teal!50,%
  },%
}%
%    \end{macrocode}
% Finally, we define the \texttt{medicationchart} and \texttt{infobox} \texttt{tcolorbox} styles based on \texttt{ddboxdefault}!
%    \begin{macrocode}
\tcbset%
{%
  ddboxdefault/.style=%
  {%
    enhanced,%
    fonttitle=\bfseries\large,%
    coltitle=black,%
    center title,%
    titlerule=.75mm,%
    toprule=1mm,%
    bottomrule=1mm,%
    toptitle=2mm,%
    bottomtitle=2mm%
  },%
  medicationchart/.style=%
  {%
    ddboxdefault,%
    fontupper=\footnotesize,%
    colback=yellow!10!white,%
    colframe=yellow!60!black,%
    colbacktitle=yellow!20!white,%
    left=0mm,%
    right=0mm,%
    top=0mm,%
    bottom=0mm,%
    boxsep=0mm,%
  },%
  infobox/.style=%
  {%
    ddboxdefault,%
    width=\linewidth-10.888pt,%
    colback=orange!10!white,%
    colframe=orange!60!black,%
    colbacktitle=orange!20!white%
  },%
}%
%    \end{macrocode}
%    \begin{macrocode}
%</cfg>
%    \end{macrocode}
% \subsection{diadia.lua}
% \changes{v1.1}{2015/05/15}{added diadia.lua}
%    \begin{macrocode}
%<*lua>
%    \end{macrocode}
%    \begin{macrocode}
#!/usr/bin/env texlua
--
-- diadia [options]
--
-- loads and processes a diadia data file
--
-- License: LPPL
--
%    \end{macrocode}
% At first, we define a version variable and variables for the command line options.
%    \begin{macrocode}
local version = "v1.0 (2015/05/15)"

local infile = ""
local outfile = ""
local mode = "*"
local startdate = ""
local enddate = ""
local columns = ""
%    \end{macrocode}
% Here, we define the central \texttt{data} variable.
%    \begin{macrocode}
local data = {}
%    \end{macrocode}
% A simple function to output the version information.
%    \begin{macrocode}
function pversion()
  print("diadia.lua " .. version)
  print("(C) Josef Kleber 2015   License: LPPL")
  os.exit(0)
end
%    \end{macrocode}
% A function to output the help information.
%    \begin{macrocode}
function phelp()
  print([[
diadia.lua [options]

 allows you to
 
 - cut a chunk out of the data file
   e.g.: -i in.dat -o out.dat -s YYYY-MM-DD -e YYYY-MM-DD
   
 - compose a new data file based on given columns of an
   existing data file
   e.g.: -i in.dat -o out.dat -c 1,2
   
 - create a new data file with date and value (1st and
   2nd column of existing file) and added value average
   columns of the last 7, 14, 30, 60 and 90 days
   e.g.: -i in.dat -o out.dat [-s YYYY-MM-DD -e YYYY-MM-DD]

 Options:

 -m  specify the mode (cut|compose|average)

 -i  specify the input file

 -o  specify the output file

 -c  specify the columns for compose mode

 -s  specify the start date (YYYY-MM-DD) in
     cut and average mode
 
 -e  specify the end date
 
 -v  prints version information

 -h  prints help information

]])
  pversion()
end
%    \end{macrocode}
% This function checks if a given date string matches the YYYY-MM-DD format.
%    \begin{macrocode}
function check_date(date)
  if string.find(date, "(%d%d%d%d)-(%d%d)-(%d%d)") == nil
  then
    io.stderr:write ("Error 21: wrong date format (YYYY-MM-DD)\n")
    os.exit(11)
  end
end
%    \end{macrocode}
% This function parses a date string and returns \texttt{year}, \texttt{month} and \texttt{day}.
%    \begin{macrocode}
function parse_date(date)
  return string.match(date, "(%d%d%d%d)%-(%d%d)%-(%d%d)")
end
%    \end{macrocode}
% This function parses a given line (string) and returns a found date.
%    \begin{macrocode}
function parse_dateinline(line)
  return string.match(line, "(%d%d%d%d%-%d%d%-%d%d)")
end
%    \end{macrocode}
% This function takes a Unix time and returns a date string in the YYYY-MM-DD format.
%    \begin{macrocode}
function daystring(unixtime)
  return os.date("%Y-%m-%d", unixtime)
end
%    \end{macrocode}
% This function computes the Unix time of a given date.
%    \begin{macrocode}
function unixtime(year,month,day)
  return os.time{year=year, month=month, day=day}
end
%    \end{macrocode}
% A simple rounding function.
%    \begin{macrocode}
function round(number)
  return math.floor(number+0.5)
end
%    \end{macrocode}
% This function checks the length of a given string and returns a string of length 3.
%    \begin{macrocode}
function ptd(value)
  local val = tostring(value)
  local slen = string.len(val)
  if slen == 3
  then
    return val
  else
    return val .. " "
  end
end
%    \end{macrocode}
% This function calculates the average value of a given \texttt{date} in the last \texttt{days} days in a \texttt{data} table.
%    \begin{macrocode}
function calc_avg(data,date,days)
  local sum = 0
  local wdays = 0
  local wday
%    \end{macrocode}
% We calculate the Unix time of the given day (\texttt{enddate}) and the derived \texttt{startday}. 
%    \begin{macrocode}
  local endday = unixtime(parse_date(date))
  local startday = endday - 60*60*24*(days-1)
%    \end{macrocode}
% We loop through our \texttt{data} table until we reach \texttt{endday}
%    \begin{macrocode}
  while startday <= endday
  do
%    \end{macrocode}
% We create a date string and check if there is a \texttt{data} entry with this key.
% If so, we sum up the value and increase the \texttt{wdays} counter
%    \begin{macrocode}
    wday = daystring(startday)
    if data[wday] ~= nil
    then
      sum = sum + data[wday]
      wdays = wdays + 1
    end
    startday = startday + 60*60*24
  end
%    \end{macrocode}
% If entries were found, we return the rounded average value as string.
%    \begin{macrocode}
  if wdays == 0
  then
    return "nan"
  else
    return tostring(round(sum/wdays))
  end
end
%    \end{macrocode}
% This function reads in the first two columns of a given \texttt{file} into a \texttt{data} table.
%    \begin{macrocode}
function read_data(file)
  local data = {}
  local date
  local startdate
  local enddate
  local dat
  local firstline = true
%    \end{macrocode}
% We itertate over \texttt{file} lines.
%    \begin{macrocode}
  for line in io.lines(file)
  do
%    \end{macrocode}
% If we match \enquote{date}, we've found the header row and ignore it.
%    \begin{macrocode}
    if string.match(line, "date")
    then
    else
%    \end{macrocode}
% Otherwise, we match for a \texttt{date} and a \texttt{value}.
%    \begin{macrocode}
      date, dat = string.match(line, "(%d%d%d%d%-%d%d%-%d%d)%s+(%S+)")
%    \end{macrocode}
% We set \texttt{startdate} with the first \texttt{date} we've found.
%    \begin{macrocode}
      if firstline == true
      then
        startdate = date
        firstline = false
      end
%    \end{macrocode}
% Moreover, we write a non-empty and non-\texttt{nan} value in our \texttt{data} table.
%    \begin{macrocode}
      if dat ~= "nan" and dat ~= "{}" and dat ~= ""
      then
        data[date] = dat
      end
    end
  end
  enddate = date
%    \end{macrocode}
% Finally, we return \texttt{data}, \texttt{startdate} and \texttt{enddate}.
%    \begin{macrocode}
  return data,startdate,enddate
end
%    \end{macrocode}
% This function writes a new \texttt{data file} based on given start and end date.
%    \begin{macrocode}
function write_avg_file(data,file,startdate,enddate)
  local sdate
  local edate
  local wday
%    \end{macrocode}
% First, we compute the Unix times of \texttt{startdate} and \texttt{enddate} for comparisons
%    \begin{macrocode}
  sdate = unixtime(parse_date(startdate))
  edate = unixtime(parse_date(enddate))
%    \end{macrocode}
% We open a \texttt{file} with write privilege and write the header row.
%    \begin{macrocode}
  outfile = assert(io.open(file, "w"))
  outfile:write("date        value avg07 avg14 avg30 avg60 avg90")
%    \end{macrocode}
% Then, we loop through our \texttt{data} table. If we do find a \texttt{data} entry, we write the \texttt{date},
% \texttt{value} and averages into the \texttt{file}.
%    \begin{macrocode}
  while sdate <= edate+7200
  do
    wday = daystring(sdate)
    if data[wday] ~= nil
    then
      outfile:write("\n" .. wday .. "  "
                    .. ptd(data[wday]) .. "   " 
                    .. ptd(calc_avg(data,wday,7)) .. "   "
                    .. ptd(calc_avg(data,wday,14)) .. "   "
                    .. ptd(calc_avg(data,wday,30)) .. "   "
                    .. ptd(calc_avg(data,wday,60)) .. "   "
                    .. ptd(calc_avg(data,wday,90)))
    end
    sdate = sdate + 60*60*24
  end
%    \end{macrocode}
% Finally, we close the \texttt{file}.
%    \begin{macrocode}
  outfile:close()
end
%    \end{macrocode}
% It's time to evaluate the commad line options with a \texttt{getopt} routine.
%    \begin{macrocode}
do
  local newarg = {}
  local i, limit = 1, #arg
  while (i <= limit) do
    if arg[i] == "-i" then
      infile = arg[i+1]
      i = i + 1
    elseif arg[i] == "-o" then
      outfile = arg[i+1]
      i = i + 1
    elseif arg[i] == "-s" then
      startdate = arg[i+1]
      i = i + 1
    elseif arg[i] == "-e" then
      enddate = arg[i+1]
      i = i + 1
    elseif arg[i] == "-c" then
      columns = arg[i+1]
      i = i + 1
    elseif arg[i] == "-m" then
      mode = arg[i+1]
      i = i + 1
    elseif arg[i] == "-v" then
      pversion()
    elseif arg[i] == "-h" then
      phelp()
    else
      newarg[#newarg+1] = arg[i]
    end
    i = i + 1
  end
  arg = newarg
end
%    \end{macrocode}
% In \texttt{average} mode, we first read in the \texttt{infile} and check for given start and end dates and use them if present.
%    \begin{macrocode}
if mode == "average"
then
  local startd
  local endd
  
  print("set mode to " .. mode)
  print("reading data file " .. infile)
  data,startd,endd = read_data(infile)
  if startdate ~= ""
  then
    startd = startdate
  end
  if enddate ~= ""
  then
    endd = enddate
  end
  print("writing data file " .. outfile)
%    \end{macrocode}
% Finally, we write the new \texttt{outfile}.
%    \begin{macrocode}
  write_avg_file(data,outfile,startd,endd)
  os.exit(0)
end
%    \end{macrocode}
% In \texttt{compose} mode, we first read in the \texttt{data file}.
%    \begin{macrocode}
if mode == "compose"
then
  local row = 0
  local column = 0
  local ofile
  local cols

  print("set mode to " .. mode)
  print("reading data file " .. infile)
  for line in io.lines(infile)
  do
    row = row + 1
    data[row] = {}
    column = 0
    for value in string.gmatch(line, "%S+")
    do
      column = column + 1
      data[row][column] = value
    end
  end
%    \end{macrocode}
% Then, we evaluate the given list of columns. I have no idea how it works exactly.
% Many thanks to Paul Kulchenko and  Egor Skriptunoff\newline
% \href{https://stackoverflow.com/questions/30242212/how-to-output-more-than-one-column/}{https://stackoverflow.com/questions/30242212/how-to-output-more-than-one-column/}
%    \begin{macrocode}
  cols = assert(load("return table.concat({"..columns:gsub("%d+","(...)[%0]").."},'  ')"))
  ofile = assert(io.open(outfile, "w"))
  print("writing data file " .. outfile)
%    \end{macrocode}
% Finally, we loop through the rows of our \texttt{data} table and write the choosen columns.
% We don't issue a new line character in the last row!
%    \begin{macrocode}
  for irow = 1,row
  do
    if irow == row
    then
      ofile:write(cols(data[irow]))
    else
      ofile:write(cols(data[irow]).."\n")
    end
  end
  ofile:close()
  os.exit(0)
end
%    \end{macrocode}
% In \texttt{cut} mode we check the format and compute the Unix times of the given start and end dates.
%    \begin{macrocode}
if mode == "cut"
then
  local ofile
  local date
  local sdate
  local edate
  local cdate
  
  check_date(startdate)
  check_date(enddate)
  sdate = unixtime(parse_date(startdate))
  edate = unixtime(parse_date(enddate))
  print("set mode to " .. mode)
  print("reading data file " .. infile)
  print("writing data file " .. outfile)
%    \end{macrocode}
% We open the \texttt{outfile} with writing privilege and loop trough \texttt{infile}.
%    \begin{macrocode}
  ofile = assert(io.open(outfile, "w"))
  for line in io.lines(infile)
  do
%    \end{macrocode}
% Of course, we copy the header row.
%    \begin{macrocode}
    if string.match(line, "date")
    then
      ofile:write(line)
%    \end{macrocode}
% Furthermore, we check if the date of the current \texttt{line} is within the given dates and write the \texttt{line} to the file.
%    \begin{macrocode}
    else
      date = parse_dateinline(line)
      cdate = unixtime(parse_date(date))
      if cdate >= sdate and cdate <= edate
      then
        ofile:write("\n" .. line)
      end
    end
  end
  ofile:close()
  os.exit(0)
end
%    \end{macrocode}
% Finally, we issue errors for incorrect \texttt{mode}s.
%    \begin{macrocode}
if mode == "*"
then
  io.stderr:write ("Error 11: no mode specified!")
  os.exit(11)
else
  io.stderr:write ("Error 12: invalid mode " .. mode)
  os.exit(12)
end
%    \end{macrocode}
%    \begin{macrocode}
%</lua>
%    \end{macrocode}
%\Finale