% \iffalse meta-comment
%
% Copyright (C) 2013 by Wolfgang Skala
%
% 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.
%
% \fi
%
% \iffalse
%<pgfmolbio-tex>\ProvidesPackage{pgfmolbio}[2013/08/01 v0.21 Molecular biology graphs with TikZ]
%<pgfmolbio-tex>\NeedsTeXFormat{LaTeX2e}[1999/12/01]
%<pgfmolbio-lua>module("pgfmolbio", package.seeall)
%<pmb-chr-tex>\ProvidesFile{pgfmolbio.chromatogram.tex}[2013/08/01 v0.21 SCF chromatograms]
%<pmb-chr-lua>module("pgfmolbio.chromatogram", package.seeall)
%<pmb-dom-tex>\ProvidesFile{pgfmolbio.domains.tex}[2013/08/01 v0.21 Protein domains]
%<pmb-dom-lua>module("pgfmolbio.domains", package.seeall)
%<pmb-con-tex>\ProvidesFile{pgfmolbio.convert.tex}[2013/08/01 v0.21 pgfmolbio graph conversion]
%
%<*driver>
\documentclass[captions=tableheading,cleardoublepage=empty,titlepage=false]{scrreprt}
	\setkomafont{title}{\rmfamily\bfseries}
	\addtokomafont{sectioning}{\rmfamily}

\usepackage[ngerman,english]{babel}
\usepackage[hdivide={2cm,*,5cm}]{geometry}
\usepackage{fontspec}
\usepackage{array,booktabs,tabularx}
\usepackage[chromatogram,domains]{pgfmolbio}
	\usetikzlibrary{patterns,backgrounds,decorations.pathreplacing}

\usepackage{ydoc-doc,ydoc-code,ydoc-desc,ydoc-expl}
	\AlsoImplementation
	\hypersetup{%
		colorlinks=false,%
		bookmarksnumbered,%
		bookmarksopen,%
		bookmarksopenlevel=1,%
		breaklinks,%
		pdfborder=0 0 0,%
		pdfhighlight=/N,%
	}
	\AtBeginDocument{%
		\lstMakeShortInline[style=latex-expl,basicstyle=\ttfamily,numbers=none,firstnumber=last]|%
		\lstMakeShortInline[style=lua-doc,basicstyle=\ttfamily,frame=none,numbers=none]§%
	}
	\makeatletter
	\newcommand\DescribeOption[4][=]{%
		\gdef\OptDefault{\textcolor{black!50}{Default:}~\texttt{#4}}%
		\DescribeMacros
		\let\DescribeMacros\y@egroup
		\optionalon
		\def\after@Macro@args{\y@egroup\PrintOptions\endgroup}%
		\hbox\y@bgroup
		\texttt{\textcolor{opt!50}{/pgfmolbio/#2}\textcolor{opt}{#3}~#1}%
		\ydoc@macrocatcodes
		\macroargsstyle
		\read@Macro@arg%
	}
	\def\PrintOptions{%
		\par\vspace\beforedescskip
		\begingroup
		\sbox\@tempboxa{\descframe{\usebox{\descbox}}}%
		\Needspace*{\dimexpr\ht\@tempboxa+2\baselineskip\relax}%
		\par\noindent
		\ifdim\wd\@tempboxa>\dimexpr\linewidth-2\descindent\relax
			\makebox[\linewidth][c]{\usebox\@tempboxa}%
		\else
			\hspace*{\descindent}%
			\usebox\@tempboxa
		\fi
		\endgroup
		\par\medskip\makebox{\kern10pt\OptDefault}
		\vspace\afterdescskip
		\par\noindent
	}
	\def\PrintExample{%
		\begingroup
		\BoxExample
		\@tempdima\textwidth
		\advance\@tempdima-\wd\examplecodebox\relax
		\advance\@tempdima-\wd\exampleresultbox\relax
		\advance\@tempdima-1cm\relax
		\ifdim\@tempdima>0pt
			\@tempdimb\wd\exampleresultbox
			\advance\@tempdimb2\fboxsep
			\advance\@tempdimb2\fboxrule
			\par\bigskip\noindent%
			\centerline{%
			\parbox[c]{\@tempdimb}{\fbox{\usebox\exampleresultbox}}
			\hskip1cm
			\parbox[c]{\wd\examplecodebox}{\usebox\examplecodebox}
			}%
			\par\bigskip
		\else
			\par\bigskip\noindent%
			\vbox{%
					\centerline{\fbox{\usebox\exampleresultbox}}%
					\vspace{\bigskipamount}%
					\centerline{\usebox\examplecodebox}%
			}%
			\par\bigskip
		\fi
		\endgroup
	}
	\newcommand\DescribeFeature{\@ifstar\DescribeFeatureNoAlias\DescribeFeatureAlias}
	\newcommand\DescribeFeatureAlias[2]{\paragraph{Feature \texttt{#1}} (\textit{alias} \texttt{#2})\\}
	\newcommand\DescribeFeatureNoAlias[1]{\paragraph{Feature \texttt{#1}} (\textit{no alias})\\}
	\makeatother
	\def\ometa#1{{\optional\meta{#1}}}
	\lstdefinestyle{exampleextract}{gobble=2}
	\lstdefinestyle{examplecode}{style=latex-expl}
	\def\ydoclistingssettings{\lstset{style=latex-expl}}
	\definecolor{opt}{named}{OliveGreen}
	\definecolor{mod}{named}{black}
	\definecolor{macrodesc}{named}{ProcessBlue}
	\definecolor{macroimpl}{named}{ProcessBlue}
	\newcommand\module[1]{\textsf{\textcolor{mod}{#1}}}
	\renewcommand*\optstyle[1]{\texttt{\textcolor{opt}{#1}}}

\lstdefinestyle{latex-expl}{
	language=[AlLaTeX]TeX,
	columns=fullflexible,
	keepspaces=true,
	tabsize=2,
	numbers=left,
	numberstyle=\sffamily\tiny\color{gray},
	numbersep=5pt,
	firstnumber=auto,
	prebreak={},
	basicstyle=\ttfamily\small,
	texcsstyle=*\color{MidnightBlue},
	texcsstyle=*[2]\color{ProcessBlue},
	keywordstyle=\color{RedOrange},
	commentstyle=\itshape\color{black!50},
	morekeywords={tikzpicture,pgfinterruptboundingbox,pgfinterruptpicture,pmbdomains,scope},
	moretexcs=[1]{
		@empty,@ifundefined,@nameuse,clip,colorlet,definecolor,directlua,draw,ifluatex,
		luaescapestring,node,path,pdfdraftmode,pgf@protocolsizes,pgf@x,pgf@y,pgfdeclareverticalshading,
		pgfkeys,pgfkeysalso,pgfkeysdef,pgfkeyssetvalue,pgfkeysvalueof,pgfmathsetmacro,pgfpoint,pgfqkeys,
		ProcessOptions,RequireLuaModule,textcolor,tikzset,useasboundingbox,usetikzlibrary
	},
	moretexcs=[2]{
		@pmb@chr@getkey,@pmb@chr@keydef,@pmb@chr@stylekeydef,
		@pmb@dom@feature@default@shape,@pmb@dom@helixsegment,@pmb@dom@helixhalfsegment,@pmb@dom@keydef,
		@pmb@toksa,@pmb@toksb,@tempa,adddisulfidefeatures,addfeature,featureSequence,currentResidue,
		pmb@chr@tikzpicturefalse,pmb@chr@tikzpicturetrue,ifpmb@chr@showbasenumbers,ifpmb@chr@tikzpicture,
		ifpmb@con@includedescription,ifpmb@con@outputtikzcode,ifpmb@dom@showname,ifpmb@dom@showruler,
		ifpmb@dom@showsecstructure,ifpmb@dom@tikzpicture,ifpmb@loadmodule@chromatogram,ifpmb@loadmodule@convert,
		ifpmb@loadmodule@domains,inputuniprot,inputgff,
		pgfmolbioset,pmb@con@outputtikzcodefalse,pmb@con@outputtikzcodetrue,
		pmb@dom@addfeature,pmb@dom@inputgff,pmb@dom@inputuniprot,pmb@dom@tikzpicturetrue,pmb@dom@tikzpicturefalse,
		pmb@loadmodule@chromatogramtrue,pmb@loadmodule@converttrue,
		pmb@loadmodule@domainstrue,pmb@magnifiedsequence@width,pmbchromatogram,pmbdomdrawfeature,
		pmbdomvalueof,pmbprotocolsizes,removedisulfidefeatures,removefeatureprintfunction,
		residueNumber,setdisulfidefeatures,setfeaturealias,
		setfeatureprintfunction,setfeatureshape,setfeatureshapealias,setfeaturestyle,setfeaturestylealias,
		turnXradius,turnYradius,xLeft,xLowerLeft,xLowerRight,xMid,xRight,xUpperLeft,xUpperRight,
		yLower,yMid,yShift,yUpper
	},
	escapebegin=\begin{rmfamily}\color{black!50},
	escapeend=\end{rmfamily}
}

\lstdefinestyle{latex-doc}{
	style=latex-expl,
	showlines,
	firstnumber=last,
	breaklines,
	frame=single,
	frameround=tttt,
	rulecolor=\color{black!50}
}

\lstdefinestyle{lua-doc}{
	language=lua,
	columns=fullflexible,
	keepspaces=true,
	tabsize=2,
	basicstyle=\ttfamily\small\color{ForestGreen},
	keywordstyle=\color{MidnightBlue},
	keywordstyle=[2]\color{ProcessBlue},
	stringstyle=\color{Red},
	identifierstyle=\color{Black},
	emphstyle=\color{BurntOrange!50!Black},
	showstringspaces=false,
	numbers=left,
	numberstyle=\sffamily\tiny\color{gray},
	numbersep=5pt,
	firstnumber=last,
	breaklines,
	showlines,
	frame=single,
	frameround=tttt,
	rulecolor=\color{black!50},
	belowskip=\bigskipamount
}

\lstdefinelanguage{lua}{
	morekeywords={and,break,do,else,elseif,end,false,for,function,if,in,local,
		nil,not,or,repeat,return,then,true,until,while},
	morekeywords=[2]{arg,assert,collectgarbage,dofile,error,_G,format,getfenv,
		getmetatable,__index,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,
		rawequal,rawget,rawset,select,self,setfenv,setmetatable,tonumber,tostring,__tostring,
		type,unpack,_VERSION,xpcall},
	morekeywords=[2]{module,require,package,seeall},
	morekeywords=[2]{string,byte,char,dump,find,
		format,gmatch,string,gsub,len,lower,
		match,rep,reverse,sub,trim,upper},
	morekeywords=[2]{table,concat,insert,maxn,remove,sort},
	morekeywords=[2]{math,min},
	morekeywords=[2]{io,input,open,output,close,flush,
		lines,read,seek,setvbuf,write},
	morekeywords=[2]{os.clock,os.date,os.difftime,os.execute,os.exit,os.getenv,
		os.remove,os.rename,os.setlocale,os.time,os.tmpname},
	morekeywords=[2]{tex,sprint},
	emph={addFeature,aliasFeatureStyle,calculateDisulfideLevels,Chromatogram,clearKeys,dimToString,findBasesInStr,
		getBaseKey,getMinMaxProbability,getParameters,getRange,getSampleAndPeakIndex,new,packageError,
		packageWarning,printSequenceFeature,printHelixFeature,printTikzChromatogram,printTikzDomains,Protein,
		readGffFile,readInt,readScfFile,readUniprotFile,selectStyleFromList,setCoordinateFormat,
		setFeatureStyle,setKeys,setParameters,SpecialKeys,stdProbStyle,stringToDim,toAbsoluteResidueNumber},
	sensitive=true,
	alsoletter={0123456789},
	morecomment=[l]{--},
	morecomment=[s]{--[[}{]]--},
	morestring=[b]{"},
	morestring=[d]{'}
}

\def\TikZ{Ti\textit{k}Z}

\usepackage{caption}
	\captionsetup{format=plain,indention=1em,labelsep=colon,font={footnotesize,sf},labelfont={bf},skip=0pt}
	\makeatletter\@addtoreset{example}{chapter}\makeatother
	\renewcommand\theexample{\arabic{chapter}.\arabic{example}}

\pdfpageattr{/Group <</S /Transparency /I true /CS /DeviceRGB>>}


\begin{document}
	\DocInput{pgfmolbio.dtx}
\end{document}
%</driver>
% \fi
%
% 
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
%
% \GetFileInfo{pgfmolbio.sty}
%
% \CheckSum{1254}
% 
% \pagenumbering{roman}
% \title{The \texttt{pgfmolbio} package --\texorpdfstring{\\}{}Molecular Biology Graphs with \TikZ\texorpdfstring{\footnote{This document describes version \fileversion, dated \filedate.}}{}}
% \author{\texorpdfstring{Wolfgang Skala\thanks{Division of Structural Biology, Department of Molecular Biology, University of Salzburg, Austria; \texttt{Wolfgang.Skala@stud.sbg.ac.at}}}{Wolfgang Skala}}
% \date{\filedate}
% \maketitle
%
% \begin{abstract}
% The experimental package \pkg{pgfmolbio} draws graphs typically found in molecular biology texts. Currently, the package contains three modules: \module{chromatogram} creates DNA sequencing chromatograms from files in standard chromatogram format (\file{scf}); \module{domains} draws protein domain diagrams; \module{convert} integrates \pkg{pgfmolbio} with \TeX\ engines that lack Lua support.
% \end{abstract}
%
% \tableofcontents
%
%
% \chapter{Introduction}
% \label{cha:Introduction}
% \pagenumbering{arabic}
% 
% 
% \section{About \texorpdfstring{\pkg{pgfmolbio}}{pgfmolbio}}
% \label{sec:IntroAbout}
% 
% Over the decades, \TeX\ has gained popularity across a large number of disciplines. Although originally designed as a mere typesetting system, packages such as \pkg{pgf}\footnote{Tantau, T. (2010). The \TikZ\ and \textsc{pgf} packages. \url{http://ctan.org/tex-archive/graphics/pgf/}.} and \pkg{pstricks}\footnote{van Zandt, T., Niepraschk, R., and Voß, H. (2007). PSTricks: PostScript macros for Generic \TeX. \url{http://ctan.org/tex-archive/graphics/pstricks}.} have strongly extended its \textit{drawing} abilities. Thus, one can create complicated charts that perfectly integrate with the text.
% 
% Texts on molecular biology include a range of special graphs, e.\,g. multiple sequence alignments, membrane protein topologies, DNA sequencing chromatograms, protein domain diagrams, plasmid maps and others. The \pkg{texshade}\footnote{Beitz, E. (2000). \TeX shade: shading and labeling multiple sequence alignments using \LaTeXe. \textit{Bioinformatics}~\textbf{16}(2), 135--139.\\\url{http://ctan.org/tex-archive/macros/latex/contrib/texshade}.} and \pkg{textopo}\footnote{Beitz, E. (2000). \TeX topo: shaded membrane protein topology plots in \LaTeXe. \textit{Bioinformatics} \textbf{16}(11), 1050--1051.\\\url{http://ctan.org/tex-archive/macros/latex/contrib/textopo}.} packages cover alignments and topologies, respectively, but packages dedicated to the remaining graphs are absent. Admittedly, one may create those images with various external programs and then include them in the \TeX\ document. Nevertheless, purists (like the author of this document) might prefer a \TeX-based approach.
% 
% The \pkg{pgfmolbio} package aims at becoming such a purist solution. In the current development release, \pkg{pgfmolbio} is able to
% \begin{itemize}
% 	\item read DNA sequencing files in standard chromatogram format (\file{scf}) and draw the corresponding chromatogram;
% 	\item read protein domain information from Uniprot or general feature format files (\file{gff}) and draw domain diagrams.
% \end{itemize}
% To this end, \pkg{pgfmolbio} relies on routines from \pkg{pgf}'s \TikZ\ frontend and on the Lua scripting language implemented in Lua\TeX. Consequently, the package will not work directly with traditional engines like pdf\TeX. However, a converter module ensures a high degree of backward compatibility.
% 
% Since this is a development release, \pkg{pgfmolbio} presumably includes a number of bugs, and its commands and features are likely to change in future versions. Moreover, the current version is far from complete, but since time is scarce, I am unable to predict when (and if) additional functions become available. Nevertheless, I would greatly appreciate any comments or suggestions.
% 
% 
% \section{Getting Started}
% \label{sec:IntroGettingStarted}
% 
% Before you consider using \pkg{pgfmolbio}, please make sure that both your Lua\TeX\ (at least 0.70.2) and \pkg{pgf} (at least 2.10) installations are up-to-date. Once your \TeX\ system meets these requirements, just load \pkg{pgfmolbio} as usual, i.\,e. by
% 
% \DescribeMacro\usepackage[<module>]{pgfmolbio}
% 
% The package is divided into \textit{modules}, each of which produces a certain type of graph. Currently, three \ometa{module}s are available:
% \begin{itemize}
% 	\item \module{chromatogram} (chapter~\ref{cha:Chromatogram}) allows you to draw DNA sequencing chromatograms obtained by the Sanger sequencing method.
% 	\item \module{domains} (chapter~\ref{cha:Domains}) provides macros for drawing protein domain diagrams and is also able to read domain information from files in Uniprot or general feature format.
% 	\item Furthermore, \module{convert} (chapter~\ref{cha:Convert}) is used with one of the modules above and generates ``pure'' \TikZ\ code suitable for \TeX\ engines lacking Lua support.
% \end{itemize}
% 
% \DescribeMacro\pgfmolbioset[<module>]{<key-value list>}
% Fine-tunes the graphs produced by each \pkg{pgfmolbio} module. The possible keys are described in the sections on the respective modules.
%
%
%
% 
% \chapter{The \texorpdfstring{\module{chromatogram}}{chromatogram} module}
% \label{cha:Chromatogram}
% 
% 
% \section{Overview}
% \label{sec:ChrOverview}
% 
% The \module{chromatogram} module draws DNA sequencing chromatograms stored in standard chromatogram format (\file{scf}), which was developed by Simon Dear and Rodger Staden\footnote{Dear, S. and Staden, R. (1992). A standard file format for data from DNA sequencing instruments. \textit{DNA Seq.} \textbf{3}(2), 107--110.}. The documentation for the Staden package\footnote{\url{http://staden.sourceforge.net/}} describes the current version of the \file{scf} format in detail. As far as they are crucial to understanding the Lua code, we will discuss some details of this file format in the documented source code (section~\ref{sec:DocChrLua}). Note that \pkg{pgfmolbio} only supports \file{scf} version 3.00.
% 
% 
% \section{Drawing Chromatograms}
% \label{sec:ChrDrawingChromatograms}
% 
% \DescribeMacro\pmbchromatogram[<key-value list>]{<scf file>}
% The \module{chromatogram} module defines a single command, which reads a chromatogram from an \meta{scf file} and draws it with routines from \TikZ\ (Example~\ref{exa:ChrTikzpicture}). The options, which are set in the \ometa{key-value list}, configure the appearance of the chromatogram. The following sections will elaborate on the available keys.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrTikzpicture}
% \begin{examplecode}
% \begin{tikzpicture} % optional
% 	\pmbchromatogram{SampleScf.scf}
% \end{tikzpicture} % optional
% \end{examplecode}
% \end{exampletable}
% 
% Although you will often put |\pmbchromatogram| into a |tikzpicture| environment, you may actually use the macro on its own. \pkg{pgfmolbio} checks whether the command is surrounded by a |tikzpicture| and adds this environment if necessary.
% 
% 
% \section{Displaying Parts of the Chromatogram}
% \label{sec:ChrDisplayingParts}
% 
% \DescribeOption{chromatogram/}{sample range}{1-500 step 1}<lower>'-'<upper>[' step '<int>]\relax
% \opt{sample range} selects the part of the chromatogram which \pkg{pgfmolbio} should display. The value for this key consists of two or three parts, separated by the keywords |-| and |step|. The package will draw the chromatogram data between the \meta{lower} and \meta{upper} boundary. There are two ways of specifying these limits:
% \begin{enumerate}
% 	\item If you enter a number, \pkg{pgfmolbio} includes the data from the \meta{lower} to the \meta{upper} sample point (Example~\ref{exa:ChrLimitsSamplePoints}). A \textit{sample point} represents one measurement of the fluorescence signal along the time axis, where the first sample point has index 1. One peak comprises about 20 sample points.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrLimitsSamplePoints}
% \begin{examplecode}
% \pmbchromatogram[sample range=200-600]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 	\item If you enter the keyword |base| followed by an optional space and a number, the chromatogram starts or stops at the peak corresponding to the respective base. The first detected base peak has index 1. Compare Examples~\ref{exa:ChrLimitsSamplePoints} and~\ref{exa:ChrLimitsBases} to see the difference.
% \end{enumerate}
% The optional third part of the value for \opt{sample range} orders the package to draw every \ometa{int}th sample point. If your document contains large chromatograms or a great number of them, drawing fewer sample points increases typesetting time at the cost of image quality (Example~\ref{exa:ChrSampleStep}). Nevertheless, the key may be especially useful while optimizing the layout of complex chromatograms.
% 
% \begin{exampletable}[p]
% \caption{}
% \label{exa:ChrLimitsBases}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base60
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \begin{exampletable}[p]
% \caption{}
% \label{exa:ChrSampleStep}
% \pgfmolbioset[chromatogram]{canvas height=1cm}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 20-base 50 step 1
% 	]{SampleScf.scf}
% \end{examplecode}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 20-base 50 step 2
% 	]{SampleScf.scf}
% \end{examplecode}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 20-base 50 step 4
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{General Layout}
% \label{sec:ChrGeneralLayout}
% 
% \DescribeOption{chromatogram/}{x unit}{0.2mm}<dimension>
% \DescribeOption{chromatogram/}{y unit}{0.01mm}<dimension>
% These keys set the horizontal distance between two consecutive sample points and the vertical distance between two fluorescence intensity values, respectively. Example~\ref{exa:Chrxyunit} illustrates how you can enlarge a chromatogram twofold by doubling these values.
% \begin{exampletable}
% \caption{}
% \label{exa:Chrxyunit}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		x unit=0.4mm,
% 		y unit=0.02mm
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}

% \DescribeOption{chromatogram/}{samples per line}{500}<number>
% \DescribeOption{chromatogram/}{baseline skip}{3cm}<dimension>
% A new chromatogram ``line'' starts after \meta{number} sample points, and the baselines of adjacent lines (i.\,e., the $y$-value of fluorescence signals with zero intensity) are separated by \meta{dimension}. In Example~\ref{exa:ChrSamplesPerLine}, you see two lines, each of which contains 250 of the 500 sample points drawn. Furthermore, the baselines are 3.5~cm apart.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrSamplesPerLine}
% \begin{examplecode}
% \begin{tikzpicture}%
% 		[decoration=brace]
% 	\pmbchromatogram[%
% 			sample range=401-900,
% 			samples per line=250,
% 			baseline skip=3.5cm
% 		]{SampleScf.scf}
% 	\draw[decorate]
% 		(-0.1cm, -3.5cm) -- (-0.1cm, 0cm)
% 		node[pos=0.5, rotate=90, above=5pt]
% 			{baseline skip};
% \end{tikzpicture}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption[/.style=]{chromatogram/}{canvas style}{draw=none, fill=none}<style>\newpage
% \DescribeOption{chromatogram/}{canvas height}{2cm}<dimension>
%
% The \textit{canvas} is the background of the trace area. Its left and right boundaries coincide with the start and the end of the chromatogram, respectively. Its lower boundary is the baseline, and its upper border is separated from the lower one by \meta{dimension}. Although the canvas is usually transparent, its \meta{style} can be changed. In Example~\ref{exa:ChrCanvasStyle}, we decrease the height of the canvas and color it light gray.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrCanvasStyle}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		canvas style/.style={draw=none, fill=black!10},
% 		canvas height=1.6cm
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{Traces}
% \label{sec:ChrTraces}
% 
% \DescribeOption[/.style=]{chromatogram/}{trace A style}{pmbTraceGreen}<style>
% \DescribeOption[/.style=]{chromatogram/}{trace C style}{pmbTraceBlue}<style>
% \DescribeOption[/.style=]{chromatogram/}{trace G style}{pmbTraceBlack}<style>
% \DescribeOption[/.style=]{chromatogram/}{trace T style}{pmbTraceRed}<style>
% \DescribeOption{chromatogram/}{trace style}{\textrm{(none)}}<style>
% The \textit{traces} indicate variations in fluorescence intensity during chromatography, and each trace corresponds to a base. The first four keys set the respective \meta{style} basewise, whereas \opt{trace style} changes all styles simultaneously. Note the syntax differences between \opt{trace style} and \opt{trace A style} etc. The standard styles simply color the traces; Table~\ref{tab:pmbColors} lists the color specifications.
% 
% \begin{table}[h]
% 	\centering
% 	\caption{Colors defined by the \module{chromatogram} module.}
% 	\label{tab:pmbColors}
% 	\begin{tabular}{*3{>{\ttfamily}l}l}
% 		\toprule
% 		Name          & \pkg{xcolor} model & Values & Example \\
% 		\midrule
% 		pmbTraceGreen  & RGB & ~34, 114, ~46 & \color{pmbTraceGreen}\rule{3cm}{1ex} \\
% 		pmbTraceBlue   & RGB & ~48, ~37, 199 & \color{pmbTraceBlue}\rule{3cm}{1ex} \\
% 		pmbTraceBlack  & RGB & ~~0, ~~0, ~~0 & \color{pmbTraceBlack}\rule{3cm}{1ex} \\
% 		pmbTraceRed    & RGB & 191, ~27, ~27 & \color{pmbTraceRed}\rule{3cm}{1ex} \\
% 		pmbTraceYellow & RGB & 233, 230, ~~0 & \color{pmbTraceYellow}\rule{3cm}{1ex} \\
% 		\bottomrule
% 	\end{tabular}
% \end{table}
% 
% In Example~\ref{exa:ChrTraceStyle}, we change the style of all traces to a thin line and then add some patterns and colors to the A and T trace.
% \begin{exampletable}[h]
% \caption{}
% \label{exa:ChrTraceStyle}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		trace style=thin,
% 		trace A style/.append style={dashdotted, green},
% 		trace T style/.style={thick, dashed, purple}
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
%
% \DescribeOption{chromatogram/}{traces drawn}{ACGT}'A|C|G|T|'!\textrm{any combination thereof}!
% The value of this key governs which traces appear in the chromatogram. Any combination of the single-letter abbreviations for the standard bases will work. Example~\ref{exa:ChrTracesDrawn} only draws the cytosine and guanine traces.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrTracesDrawn}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		traces drawn=CG
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{Ticks}
% \label{sec:ChrTicks}
% 
% \DescribeOption[/.style=]{chromatogram/}{tick A style}{thin, pmbTraceGreen}<style>
% \DescribeOption[/.style=]{chromatogram/}{tick C style}{thin, pmbTraceBlue}<style>
% \DescribeOption[/.style=]{chromatogram/}{tick G style}{thin, pmbTraceBlack}<style>
% \DescribeOption[/.style=]{chromatogram/}{tick T style}{thin, pmbTraceRed}<style>
% \DescribeOption{chromatogram/}{tick style}{\textrm{(none)}}<style>
% \textit{Ticks} below the baseline indicate the maxima of the trace peaks. The first four keys set the respective \meta{style} basewise, whereas \opt{tick style} changes all styles simultaneously. Note the syntax differences between \opt{tick style} and \opt{tick A style} etc. Example~\ref{exa:ChrTickStyle} illustrates how one can draw thick ticks, which are red if they indicate a cytosine peak.
% \begin{exampletable}[ht]
% \caption{}
% \label{exa:ChrTickStyle}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		tick style=thick,
% 		tick C style/.append style={red}
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{chromatogram/}{tick length}{1mm}<dimension>
% This key determines the length of each tick. In Example~\ref{exa:ChrTickLength}, the ticks are twice as long as usual.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrTickLength}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		tick length=2mm
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{chromatogram/}{ticks drawn}{ACGT}'A|C|G|T|'!\textrm{any combination thereof}!
% The value of this key governs which ticks appear in the chromatogram. Any combination of the single-letter abbreviations for the standard bases will work. Example~\ref{exa:ChrTicksDrawn} only displays the cytosine and guanine ticks.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrTicksDrawn}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		ticks drawn=CG
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{Base Labels}
% \label{sec:ChrBaseLabels}
% 
% \DescribeOption{chromatogram/}{base label A text}{\cs{strut} A}<text>
% \DescribeOption{chromatogram/}{base label C text}{\cs{strut} C}<text>
% \DescribeOption{chromatogram/}{base label G text}{\cs{strut} G}<text>
% \DescribeOption{chromatogram/}{base label T text}{\cs{strut} T}<text>
% \textit{Base labels} below each tick spell the nucleotide sequence deduced from the traces. By default, the \meta{text} that appears in these labels equals the single-letter abbreviation of the respective base. The |\strut| macro ensures equal vertical spacing. In Example~\ref{exa:ChrBaseLabelText}, we print lowercase letters beneath adenine and thymine.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrBaseLabelText}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		base label A text=\strut a,
% 		base label T text=\strut t
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption[/.style=]{chromatogram/}{base label A style}{below=4pt, font=\cs{ttfamily}\cs{footnotesize}, pmbTraceGreen}<style>
% \DescribeOption[/.style=]{chromatogram/}{base label C style}{below=4pt, font=\cs{ttfamily}\cs{footnotesize}, pmbTraceBlue}<style>
% \DescribeOption[/.style=]{chromatogram/}{base label G style}{below=4pt, font=\cs{ttfamily}\cs{footnotesize}, pmbTraceBlack}<style>
% \DescribeOption[/.style=]{chromatogram/}{base label T style}{below=4pt, font=\cs{ttfamily}\cs{footnotesize}, pmbTraceRed}<style>
% \DescribeOption{chromatogram/}{base label style}{\textrm{(none)}}<style>
% The first four keys set the respective \meta{style} basewise, whereas \opt{base label style} changes all styles simultaneously. Each base label is a \TikZ\ node anchored to the lower end of the respective tick. Thus, the \meta{style} should contain placement keys such as |below| or |anchor=south|. Example~\ref{exa:ChrBaseLabelStyle} shows some (imaginative) base label styles.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrBaseLabelStyle}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		base label style=%
% 			{below=2pt, font=\sffamily\footnotesize},
% 		base label T style/.append style=%
% 			{below=4pt, font=\tiny}
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{chromatogram/}{base labels drawn}{ACGT}'A|C|G|T|'!\textrm{any combination thereof}!
% The value of this key governs which base labels appear in the chromatogram. Any combination of the single-letter abbreviations for the standard bases will work. Example~\ref{exa:ChrBaseLabelsDrawn} only displays cytosine and guanine base labels.
% \begin{exampletable}[ht]
% \caption{}
% \label{exa:ChrBaseLabelsDrawn}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		base labels drawn=CG
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{Base Numbers}
% \label{sec:ChrBaseNumbers}
% 
% \DescribeOption{chromatogram/}{show base numbers}{true}<boolean>
% Turns the \textit{base numbers} on or off, which indicate the indices of the base peaks below the traces.
% \DescribeOption[/.style=]{chromatogram/}{base number style}{pmbTraceBlack, below=-3pt, font=\cs{sffamily}\cs{tiny}}<style>
%  Determines the placement and appearance of the base numbers. Example~\ref{exa:ChrBaseNumberStyle} contains bold red base numbers that are shifted slightly upwards.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrBaseNumberStyle}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 40-base 50,
% 		base number style/.style={below=-3pt,%
% 			font=\rmfamily\bfseries\tiny, red}
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{chromatogram/}{base number range}{auto-auto step 10}<lower>'-'<upper>[' step '<interval>]
% This key decides that every \ometa{interval}th base number from \meta{lower} to \meta{upper} should show up in the output; the |step| part is optional. If you specify the keyword |auto| instead of a number for \meta{lower} or \meta{upper}, the base numbers start or finish at the leftmost or rightmost base peak shown, respectively. In Example~\ref{exa:ChrBaseNumberRange}, only peaks 42 to 46 receive a number.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrBaseNumberRange}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 40-base 50,
% 		base number range=42-46 step 1,
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{Probabilities}
% \label{sec:ChrProbabilities}
% 
% Programs such as \file{phred}\footnote{Ewing, B., Hillier, L., Wendl, M.\,C., and Green, P. (1998). Base-calling of automated sequencer traces using phred. I. Accuracy assessment. \textit{Genome Res.} \textbf{8}(3), 175--185.} assign a \textit{probability} or \textit{quality value} $Q$ to each called base after chromatography. $Q$ is calculated from the error probability $P_e$ by $Q = -10 \log_{10} P_e$. For example, a $Q$ value of 20 means that 1 in 100 base calls is wrong.
% 
% \DescribeOption{chromatogram/}{probability distance}{0.8cm}<dimension>
% Sets the distance between the base probability rules and the baseline.
% \DescribeOption{chromatogram/}{probabilities drawn}{ACGT}'A|C|G|T|'!\textrm{any combination thereof}!
% Governs which probabilities appear in the chromatogram. Any combination of the single-letter abbreviations for the standard bases will work. In Example~\ref{exa:ChrProbabilities}, we shift the probability indicator upwards and only show the quality values of cytosine and thymine peaks.
% \begin{exampletable}
% \caption{}
% \label{exa:ChrProbabilities}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 10-base 30,
% 		probabilities drawn=CT,
% 		probability distance=1mm
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{chromatogram/}{probability style function}{nil}<Lua function name>
% By default, the probability rules are colored black, red, yellow and green for quality scores $<10$, $<20$, $<30$ and $\geq30$, respectively. However, you can override this behavior by providing a \meta{Lua function name} to \opt{probability style function}. This Lua function must read a single argument of type number and return a string appropriate for the optional argument of \TikZ's |\draw| command. For instance, the function shown in Example~\ref{exa:ChrProbStyleFunction} determines the lowest and highest probability and colors intermediate values according to a red--yellow--green gradient.
% \begin{exampletable}[htp]
% \caption{}
% \label{exa:ChrProbStyleFunction}
% \begin{examplecode}
% \directlua{
% 	function probabilityGradient (prob)
% 		local minProb, maxProb = pmbChromatogram:getMinMaxProbability()
% 		local scaledProb = prob / maxProb * 100
% 		local color = ''
% 		if scaledProb < 50 then
% 			color = 'yellow!' .. scaledProb * 2 .. '!red'
% 		else
% 			color = 'green!' .. (scaledProb - 50) * 2 .. '!yellow'
% 		end
% 		return 'ultra thick, ' .. color
% 	end
% }
% \pmbchromatogram[%
% 		samples per line=1000,
% 		sample range=base 1-base 50,
% 		probability style function=probabilityGradient
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
%
%
% \section{Miscellaneous Keys}
% \label{sec:ChrMiscKeys}
% 
% \DescribeOption{chromatogram/}{bases drawn}{ACGT}'A|C|G|T|'!\textrm{any combination thereof}!
% This key simultaneously sets \opt{traces drawn}, \opt{ticks drawn}, \opt{base labels drawn} and \opt{probabilities drawn} (see Example~\ref{exa:ChrBasesDrawn}).
% \begin{exampletable}[p]
% \caption{}
% \label{exa:ChrBasesDrawn}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50-base 60,
% 		bases drawn=AC
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% 
% \chapter{The \texorpdfstring{\module{domains}}{domains} module}
% \label{cha:Domains}
% 
% \section{Overview}
% \label{sec:DomOverview}
% 
% Protein domain diagrams appear frequently in databases such as Pfam\footnote{Finn, R.\,D., Mistry, J. \textit{et al.} (2010). The Pfam protein families database. \textit{Nucleic Acids Res.} \textbf{38}, D211--D222.} or \textsc{prosite}\footnote{Sigrist, C.\,J.\,A., Cerutti, L. \textit{et al.} (2010). \textsc{prosite}, a protein domain database for functional characterization and annotation. \textit{Nucleic Acids Res.} \textbf{38}, D161--D166.}. Domain diagrams are often drawn using standard graphics software or tools such as \textsc{prosite}'s MyDomains image creator\footnote{\url{http://prosite.expasy.org/mydomains/}}. However, the \module{domains} module provides an integrated approach for generating domain diagrams from \TeX\ code or from external files.
% 
% 
% \section{Domain Diagrams and Their Features}
% \label{sec:DomDiagrams}
% 
% \DescribeEnv[\meta{features}]{pmbdomains}[<key-value list>]{<sequence length>}
% Draws a domain diagram with the \meta{features} given. The \ometa{key-value list} configures its appearance. \meta{sequence length} is the total number of residues in the protein. (Although you must eventually specify a sequence length, you may actually leave the mandatory argument empty and use the \opt{sequence length} key instead; see section~\ref{sec:DomFileInput}).
% 
% You can put a |pmbdomains| environment into a |tikzpicture|, but you also may use the environment on its own. \pkg{pgfmolbio} checks whether it is surrounded by a |tikzpicture| and adds this environment if necessary.
%
% \DescribeOption{domains/}{name}{Protein}<text>
% The name of the protein, which usually appears centered above the diagram.
% 
% \DescribeOption{domains/}{show name}{true}<boolean>
% Determines whether both the name and sequence length are shown.
% 
% \DescribeMacro\addfeature[<key-value list>]{<type>}{<start>}{<stop>}
% Adds a feature of the given \meta{type} to the current domain diagram (only defined inside |pmbdomains|). The feature spans the residues from \meta{start} to \meta{stop}. These arguments are either numbers, which refer to residues in the relative numbering scheme, or numbers in parentheses, which refer to absolute residue numbers (see section~\ref{sec:DomGeneralLayout}).
% 
% \DescribeOption{domains/}{description}{\textrm{(none)}}<text>
% Sets the feature description (Example~\ref{exa:DomTikzpicture}).
% 
% \begin{exampletable}
% \caption{}
% \label{exa:DomTikzpicture}
% \begin{examplecode}
% \begin{tikzpicture} % optional
% 	\begin{pmbdomains}[name=\TeX ase]{200}
% 		\addfeature{disulfide}{40}{129}
% 		\addfeature{disulfide}{53}{65}
% 		\addfeature[description=Domain 1]{domain}{30}{80}
% 		\addfeature[description=Domain 2]{domain}{93}{163}
% 		\addfeature{domain}{168}{196}
% 	\end{pmbdomains}
% \end{tikzpicture} % optional
% \end{examplecode}
% \end{exampletable}
%
%
% \section{General Layout}
% \label{sec:DomGeneralLayout}
%
% \DescribeOption{domains/}{x unit}{0.5mm}<dimension>
% The width of a single residue.
% 
% \DescribeOption{domains/}{y unit}{6mm}<dimension>
% The height of a default \texttt{domain} feature.
%
% \DescribeOption{domains/}{residues per line}{200}<number>
% A new domain diagram ``line'' starts after \meta{number} residues.
% 
% \DescribeOption{domains/}{baseline skip}{3}<factor>
% The baselines of consecutive lines (i.\,e., the main chain $y$-coordinates) are separated by \meta{factor} times the value of \opt{y unit}. In Example~\ref{exa:DomResiduesPerLine}, you see four lines, each of which contains up to 30~residues. Note how domains are correctly broken across lines. Furthermore, the baselines are $2 \times 4 = 8$~mm apart.
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomResiduesPerLine}
% \begin{examplecode}
% \begin{pmbdomains}%
% 		[show name=false, x unit=2mm, y unit=4mm,
% 		residues per line=30, baseline skip=2]{110}
% 	\addfeature[description=Domain 1]{domain}{10}{23}
% 	\addfeature[description=Domain 2]{domain}{29}{71}
% 	\addfeature[description=Domain 3]{domain}{80}{105}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \DescribeOption{domains/}{residue numbering}{auto}<numbering scheme>
% A protein's amino acid residues are usually numbered consecutively starting from~1. However, there are different numbering schemes. For example, residue numbering in a serine protease related to chymotrypsin typically follows the numbering in chymotrypsinogen\footnote{Bode, W., Mayr, I. \textit{et al.} (1989). The refined 1.9 Å crystal structure of human $\alpha$-thrombin: interaction with \textsc{d}-Phe-Pro-Arg chloromethylketone and significance of the Tyr-Pro-Pro-Trp insertion segment. \textit{EMBO J.} \textbf{8}(11), 3467--3475.}. The target protease sequence is aligned to the chymotrypsinogen sequence, and equivalent residues receive the same number. Insertions into the target sequence are indicated by appending letters to the last aligned residue (e.\,g., 186, \textit{186A}, \textit{186B}, 187), whereas gaps in the target sequence cause gaps in the numbering (e.\,g., 124, 125, 128, 129).
%
% In \pkg{pgfmolbio}, you can specify a relative \meta{numbering scheme} via the \opt{residue numbering} key. The keyword |auto| indicates that residues are numbered from 1 to (sequence length), i.\,e. absolute and relative numberings coincide. This is the case in all examples above. The complete syntax for the key is
% \begin{quote}
% 	\meta{numbering scheme} := \MacroArgs{<range>[','<range>', ...']}\\
% 	\meta{range} := \MacroArgs<start>'-'<end>' | '<start>\\
% 	\meta{start} := \MacroArgs<number>' | '<number><letter>\\
% 	\meta{end} := \MacroArgs<number>' | '<letter>
% \end{quote}
% 
% Example~\ref{exa:DomResidueNumbering} shows a custom \meta{numbering scheme}, in this case for kallikrein-related peptidase 2 (KLK2), a chymotrypsin-like serine proteases. (In the following explanation, the subscripts `abs' and `rel' denote absolute and relative numbering, respectively).
% \begin{itemize}
% 	\item Residue 1\textsubscript{abs} is labeled 16\textsubscript{rel}, residue 2\textsubscript{abs} is labeled 17\textsubscript{rel} etc. until residue 24\textsubscript{abs}, which is labeled 39\textsubscript{rel} (range |16-39|).
% 	\item Residue 25\textsubscript{abs} corresponds to 41\textsubscript{rel} etc. until residue 57\textsubscript{abs}/73\textsubscript{rel} (range |41-73|).
% 	\item Residue 40\textsubscript{rel} is missing -- no residue in KLK2 is equivalent to residue 40 in chymotrypsinogen.
% 	\item An insertion of 11 amino acids follows residue 95\textsubscript{rel}. These residues are numbered from 95A\textsubscript{rel} to 95K\textsubscript{rel}. Note that both |95A-K| and |95A-95K| are valid ranges.
% 	\item The number of the last residue is 245A\textsubscript{rel}(range |245A|).
% \end{itemize}
% 
% \begin{exampletable}
% \caption{}
% \label{exa:DomResidueNumbering}
% \begin{examplecode}
% \begin{pmbdomains}[%
% 		sequence=IVGGWECEKHSQPWQVAVYSHGWAHCGGVLVHPQWVLTAAHCLK%
% 			KNSQVWLGRHNLFEPEDTGQRVPVSHSFPHPLYNMSLLKHQSLRPDEDSSH%
% 			DLMLLRLSEPAKITDVVKVLGLPTQEPALGTTCYASGWGSIEPEEFLRPRS%
% 			LQCVSLHLLSNDMCARAYSEKVTEFMLCAGLWTGGKDTCGGDSGGPLVCNG%
% 			VLQGITSWGPEPCALPEKPAVYTKVVHYRKWIKDTIAANP,
% 		residue numbering={16-39,41-73,75-95,95A-K,96-125,%
% 			128-186,186A-186B,187-203,208-223,223A,224-245,245A},
% 		x unit=4mm,
% 		residues per line=40,
% 		show name=false,
% 		ruler range=auto-auto step 1,
% 		ruler distance=-.3,
% 		baseline skip=2
% 	]{237}
% 	\setfeaturestyle{other/main chain}{*1{draw, line width=2pt, black!10}}
% 	\addfeature{other/sequence}{16}{245A}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \DescribeOption{domains/}{residue range}{auto-auto}<lower>'-'<upper>
% All residues from \meta{lower} to \meta{upper} will appear in the output. Possible values for \meta{lower} and \meta{upper} are:
% \begin{itemize}
% 	\item |auto|, which indicates the first or last residue, respectively;
% 	\item a plain number, which denotes a residue in the \textit{relative} numbering scheme set by \opt{residue numbering};
% 	\item a parenthesized number, which denotes a residue in the \textit{absolute} numbering scheme.
% \end{itemize}
% In Example~\ref{exa:DomResidueRange}, only residues 650\textsubscript{abs} to 850\textsubscript{rel} are shown. If a domain boundary lies outside of the range shown, only the appropriate part of the domain appears.
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomResidueRange}
% \begin{examplecode}
% \begin{pmbdomains}[%
% 		show name=false, residue range=(650)-850,
% 		residue numbering={1-500,601-1100}]{1000}
% 	\addfeature[description=Domain 1]{domain}{(630)}{(660)}
% 	\addfeature[description=Domain 2]{domain}{(680)}{(710)}
% 	\addfeature[description=Domain 3]{domain}{840}{1000}
% 	\addfeature[description=Domain 4 (invisible)]{domain}{1010}{1040}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \DescribeOption{domains/}{enlarge left}{0cm}<dimension>
% \DescribeOption{domains/}{enlarge right}{0cm}<dimension>
% \DescribeOption{domains/}{enlarge top}{1cm}<dimension>
% \DescribeOption{domains/}{enlarge bottom}{0cm}<dimension>
% % \pkg{pgfmolbio} clips features that would protrude into the left or right margin. However, limits in the \TikZ\ clipping mechanism prevent correct automatic updates of the bounding box for the domain diagram. Although the package tries hard to establish a bounding box that is sufficiently large, the process may require manual intervention. To this end, each \opt{enlarge ...} key enlarges the bounding box at the respective side (Example~\ref{exa:DomEnlargeBB}).
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomEnlargeBB}
% \begin{examplecode}
% \tikzset{%
% 	baseline, tight background,%
% 	background rectangle/.style={draw=red, thick}%
% }
% \pgfmolbioset[domains]{show name=false, y unit=1cm, show ruler=false}
% 
% \begin{tikzpicture}[show background rectangle]
% 	\begin{pmbdomains}{80}
% 		\addfeature[description=Oops!]{domain}{20}{60}
% 	\end{pmbdomains}
% \end{tikzpicture}
% \begin{tikzpicture}[show background rectangle]
% 	\begin{pmbdomains}[enlarge bottom=-5mm]{80}
% 		\addfeature[description=Better!]{domain}{20}{60}
% 	\end{pmbdomains}
% \end{tikzpicture}
% \end{examplecode}
% \end{exampletable}
%
%
% \section{Feature Styles and Shapes}
% \label{sec:DomFeatureStylesAndShapes}
%
% Each (implicit and explicit) feature of a domain chart has a certain \textit{shape} and \textit{style}. For instance, you can see five different feature \textit{shapes} in Example~\ref{exa:DomTikzpicture}: We explicitly added two features of shape (and type) \texttt{disulfide} and three features of shape \texttt{domain}. Furthermore, the package implicitly included features of shape \texttt{other/name}, \texttt{other/main chain} and \texttt{other/ruler}. 
% 
% Although the three \texttt{domain} features agree in shape, they differ in color, or (more generally) \textit{style}. Since \pkg{pgfmolbio} distinguishes between shapes and styles, you may draw equally shaped features with different colors, strokes, shadings etc.
%
% \DescribeMacro\setfeaturestyle{<type>}{<style list>}
% Specifies a \meta{style list} for the given feature \meta{type}. The complete syntax ist
% 
% \begin{quote}
% 	\meta{style list} := \MacroArgs{<style list item>[','<style list item>', ...']}\\
% 	\meta{style list item} := \MacroArgs<multiplier><style>\\
% 	\meta{multiplier} := \MacroArgs['*'<number>]\\
% 	\meta{style} := \MacroArgs<single key-value pair>' | '{<key-value list>}
% \end{quote}
% 
% A style list item of the general form |*|\meta{n}|{|\meta{style}|}| instructs the package to repeat the \meta{style} \meta{n}-times. (This syntax is reminiscent of column specifications in a |tabular| environment. However, do \textit{not} enclose numbers with more than one digit in curly braces!) You may omit the trivial multiplier |*1|, but never forget the curly braces surrounding a \meta{style} that contains two or more key-value pairs. Furthermore, \pkg{pgfmolbio} loops over the style list until all features have been drawn.
% 
% For instance, the style list in Example~\ref{exa:DomFeatureStyle} fills the first feature red, then draws a green one with a thick stroke, and finally draws two dashed blue features. 
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureStyle}
% \begin{examplecode}
% \begin{pmbdomains}[show name=false]{200}
% 	\setfeaturestyle{domain}%
% 		{fill=red, {thick, fill=green}, *2{blue, dashed}}
% 	\addfeature{domain}{11}{30}
% 	\addfeature{domain}{41}{60}
% 	\addfeature{domain}{71}{90}
% 	\addfeature{domain}{101}{120}
% 	\addfeature{domain}{131}{150}
% 	\addfeature{domain}{161}{180}
% 	\addfeature{domain}{191}{200}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}

% \DescribeOption{domains/}{style}{\textrm{(empty)}}<style>
% Although |\setfeaturestyle| may appear in a |pmbdomains| environment, changes introduced in this way are not limited to the current \TeX\ group (since feature styles are stored in Lua variables). Instead, use the \opt{style} key to locally override a feature style (Example~\ref{exa:DomFeatureStyleKey}).
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureStyleKey}
% \begin{examplecode}
% \begin{pmbdomains}[show name=false]{100}
% 	\addfeature{domain}{11}{30}
% 	\begingroup
% 		\setfeaturestyle{domain}{{thick, fill=red}}
% 		\addfeature{domain}{41}{60}
% 	\endgroup
% 	\addfeature{domain}{71}{90} % the new style persists ...
% \end{pmbdomains}
% 
% \begin{pmbdomains}[show name=false]{100}
% 	\addfeature{domain}{11}{30}
% 	\addfeature[style={thick, fill=red}]{domain}{41}{60}
% 	\addfeature{domain}{71}{90} % correct solution
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \DescribeMacro\setfeaturestylealias{<new type>}{<existing type>}
% After calling this macro, the \meta{new type} and \meta{existing type} share a common style, while they still differ in their shapes.
%
% \DescribeMacro\setfeatureshape{<type>}{<TikZ code>}\relax
% Defines a new feature shape named \meta{type} or changes an existing one. \textbf{Caution:} If you change a shape within |pmbdomains|, you will also change the features of equal type that you already added. Thus, it is best to use |\setfeatureshape| only outside of this environment.
% 
% \begin{exampletable}[p]
% \caption{}
% \label{exa:DomFeatureShape1}
% \begin{examplecode}
% \setfeatureshape{domain}{%
% 	\draw [/pgfmolbio/domains/current style]
% 		(\xLeft, \yMid + .5 * \pmbdomvalueof{y unit}) rectangle
% 		(\xRight, \yMid - .5 * \pmbdomvalueof{y unit});
% 	\node at (\xMid, \yMid) {\pmbdomvalueof{description}};
% }
% 
% \begin{pmbdomains}[show name=false]{200}
% 	\addfeature[description=Domain 1]{domain}{30}{80}
% 	\addfeature[description=Domain 2]{domain}{93}{163}
% 	\addfeature[description=Domain 3]{domain}{168}{196}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \begin{exampletable}[p]
% \caption{}
% \label{exa:DomFeatureShape2}
% \begin{examplecode}
% \setfeatureshape{domain}{%
% 	\pgfmathsetmacro\middlecorners{%
% 		\xLeft + (\xRight - \xLeft) * .618%
% 	}
% 	\draw [/pgfmolbio/domains/current style]
% 		(\xLeft, \yMid + 2mm) --
% 		(\middlecorners pt, \yMid + 3mm) --
% 		(\xRight, \yMid) --
% 		(\middlecorners pt, \yMid - 3mm) --
% 		(\xLeft, \yMid - 2mm) --
% 		cycle;
% }
% 
% \begin{pmbdomains}[show name=false]{200}
% 	\addfeature[description=Domain 1]{domain}{30}{80}
% 	\addfeature[description=Domain 2]{domain}{93}{163}
% 	\addfeature[description=Domain 3]{domain}{168}{196}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureShape3}
% \begin{examplecode}
% \pgfdeclareverticalshading[bordercolor,middlecolor]{mydomain}{100bp}{
% 	color(0bp)=(bordercolor);
% 	color(25bp)=(bordercolor);
% 	color(40bp)=(middlecolor);
% 	color(60bp)=(middlecolor);
% 	color(75bp)=(bordercolor);
% 	color(100bp)=(bordercolor)
% }
% 
% \tikzset{%
% 	domain middle color/.code=\colorlet{middlecolor}{#1},%
% 	domain border color/.code=\colorlet{bordercolor}{#1}%
% }
% 
% \setfeatureshape{domain}{%
% 	\draw [shading=mydomain, rounded corners=2mm,
% 		/pgfmolbio/domains/current style]
% 		(\xLeft, \yMid + .5 * \pmbdomvalueof{y unit}) rectangle
% 		(\xRight, \yMid - .5 * \pmbdomvalueof{y unit});
% 	\node [above=3mm] at (\xMid, \yMid)
% 		{\pmbdomvalueof{domain font}{\pmbdomvalueof{description}}};
% }
% 
% \begin{pmbdomains}[show name=false]{200}
% 	\setfeaturestyle{domain}{%
% 		{domain middle color=yellow!85!orange,%
% 		domain border color=orange},%
% 		{domain middle color=green,%
% 		domain border color=green!50!black}%
% 		{domain middle color=cyan,%
% 		domain border color=cyan!50!black}%
% 	}
% 	\addfeature[description=Domain 1]{domain}{30}{80}
% 	\addfeature[description=Domain 2]{domain}{93}{163}
% 	\addfeature[description=Domain 3]{domain}{168}{196}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
% 
% Several commands that are only available in the \meta{TikZ code} allow you to design generic feature shapes:
% \begin{itemize}
% 	\item |\xLeft|, |\xMid| and |\xRight| expand to the left, middle and right $x$-coordinate of the feature. The coordinates are in a format suitable for |\draw| and similar commands.
% 	\item |\yMid| expands to the $y$-coordinate of the feature, i.\,e. the $y$-coordinate of the current line.
% 	\item You can access any values stored in the package’s \meta{key}s with the macro |\pmbdomvalueof{|\meta{key}|}|.
% 	\item The style key \opt{/pgfmolbio/domains/current style} represents the current feature style selected from the associated style list.
% \end{itemize}
% The commands above are available for all features. By contrast, the following macros are limited to certain feature types:
% \begin{itemize}
% 	\item |\featureSequence| provides the amino acid sequence of the current feature. This macro is only available for explicitly added features and for \texttt{other/main chain}.
% 	\item |\residueNumber| equals the current residue number. This macro is only available for shape \texttt{other/ruler} (see section~\ref{sec:DomRuler}).
% 	\item |\currentResidue| expands to a single letter amino acid abbreviation. This macro is only available for shape \texttt{other/sequence} (see section~\ref{sec:DomSequences}).
% \end{itemize}
%
% In Example~\ref{exa:DomFeatureShape1}, we develop a simple \texttt{domain} shape, which is a rectangle containing a centered label with the feature description. Example~\ref{exa:DomFeatureShape2} calculates an additional coordinate for a pentagonal domain shape and stores this coordinate in |\middlecorners|. Note that you have to insert ``pt'' after |\middlecorners| when using the stored coordinate. The domains in Example~\ref{exa:DomFeatureShape3} display a custom shading and inherit their style from the style list. 
%
% \DescribeMacro\setfeatureshapealias{<new type>}{<existing type>}
% After calling this macro, the \meta{new type} and \meta{existing type} share a common shape, while they still differ in their styles.
%
% \DescribeMacro\setfeaturealias{<new type>}{<existing type>}
% This is a shorthand for calling both |\setfeatureshape| and |\setfeaturestyle|.
%
%
% \section{Standard Features}
% \label{sec:DomStandardFeatures}
% 
% \pkg{pgfmolbio} provides a range of standard features. This section explains simple features (i.\,e., those that support no or only few options), while later sections cover advanced ones. Some features include predefined aliases, which facilitate inclusion of external files (see section~\ref{sec:DomFileInput}).
%
% \DescribeFeature*{default}
% A fallback for undefined features, in which case \TeX\ issues a warning (Example~\ref{exa:DomFeatureDefault}).
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureDefault}
% \begin{examplecode}
% \begin{pmbdomains}[show name=false]{100}
% 	\addfeature{default}{21}{50}
% 	\addfeature{unknown}{61}{90} % i.e. default shape/style
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \DescribeFeature{domain}{DOMAIN}
% A generic feature for protein domains. It consists of a rectangle with rounded corners and a label in the center, which shows the value of \opt{description}.
%
% \DescribeOption{domains/}{domain font}{\string\footnotesize}<font commands>
% Sets the font for the label of a \texttt{domain} feature. The last command may take a single argument (Example~\ref{exa:DomFeatureDomain}).
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureDomain}
% \begin{examplecode}
% \begin{pmbdomains}[show name=false]{100}
% 	\addfeature[description=Domain 1]{domain}{21}{50}
% 	\addfeature[description=Domain 2,%
% 		domain font=\tiny\textit]{DOMAIN}{61}{90}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \DescribeFeature{signal peptide}{SIGNAL}
% Adds a signal peptide (Example~\ref{exa:DomFeatureProSignal}).
% 
% \DescribeFeature{propeptide}{PROPEP}
% Adds a propeptide (Example~\ref{exa:DomFeatureProSignal}).
% 
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureProSignal}
% \begin{examplecode}
% \begin{pmbdomains}[show name=false]{100}
% 	\addfeature{signal peptide}{1}{15}
% 	\addfeature{propeptide}{16}{50}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \DescribeFeature{carbohydrate}{CARBOHYD}
% Adds glycosylation (Example~\ref{exa:DomFeatureCarbohyd}).
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureCarbohyd}
% \begin{examplecode}
% \begin{pmbdomains}[show name=false]{100}
% 	\addfeature[description=GlcNAc]{carbohydrate}{25}{25}
% 	\addfeature[description=Xyl]{CARBOHYD}{60}{60}
% 	\addfeature[description=Domain 1]{domain}{21}{50}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \DescribeFeature*{other/main chain}
% This feature is automatically added to the feature list at the end of each |pmbdomains| environment. It represents the protein main chain, which appears as a grey line by default. Nevertheless, you can alter the backbone just like any other feature (Example~\ref{exa:DomFeatureMainchain}).
%
% \begin{exampletable}[p]
% \caption{}
% \label{exa:DomFeatureMainchain}
% \begin{examplecode}
% \setfeatureshape{other/main chain}{%
% 	\draw [/pgfmolbio/domains/current style]
% 		(\xLeft, \yMid + .5 * \pmbdomvalueof{y unit}) rectangle
% 		(\xRight, \yMid - .5 * \pmbdomvalueof{y unit});
% 	\draw (\xLeft, \yMid) --
% 		(\xLeft - 2mm, \yMid)
% 		node [left] {\tiny H$_2$N};
% 	\draw (\xRight, \yMid) --
% 		(\xRight + 2mm, \yMid)
% 		node [right] {\tiny COOH};
% }
% \begin{pmbdomains}%
% 		[show name=false, enlarge left=-0.8cm, enlarge right=1.2cm]{100}
% 	\setfeaturestyle{other/main chain}{{draw=black,fill=black!20}}
% 	\addfeature[description=1]{domain}{10}{25}
% 	\addfeature[description=2]{domain}{30}{55}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \DescribeFeature*{other/name}
% This feature is automatically added to the feature list at the end of each |pmbdomains| environment. It relates to the protein name, which is normally displayed at the top center of the chart, together with the number of residues (Example~\ref{exa:DomFeatureName}). The following auxiliary commands are available for the feature style \TikZ\ code: |\xLeft|, |\xMid|, |\xRight| and \opt{current style}.
%
% \begin{exampletable}[p]
% \caption{}
% \label{exa:DomFeatureName}
% \begin{examplecode}
% \setfeatureshape{other/name}{%
% 	\node [/pgfmolbio/domains/current style]
% 		at (\xLeft, \pmbdomvalueof{baseline skip}
% 			* \pmbdomvalueof{y unit} / 2)
% 		{A \pmbdomvalueof{sequence length} residues long protein
% 			called `\pmbdomvalueof{name}'};
% }
% \begin{pmbdomains}[name=\TeX ase]{150}
% 	\setfeaturestyle{other/name}{{font=\bfseries, right}}
% 	\addfeature[description=1]{domain}{10}{25}
% 	\addfeature[description=2]{domain}{55}{123}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
%
% \section{Disulfides and Ranges}
% \label{sec:DomDisulfides}
%
% \DescribeFeature{disulfide}{DISULFID}
% \pkg{pgfmolbio} indicates disulfide bridges by brackets above the main chain. Since disulfides are often interleaved in linear representations of proteins, the package automatically stacks them in order to avoid overlaps (Example~\ref{exa:DomFeatureDisulfide}).
%
% \DescribeOption{domains/}{level}{\textrm{(empty)}}<number>
% Manually sets the level of a disulfide feature.
% 
% \DescribeOption{domains/}{disulfide base distance}{1}<number>
% The distance (as a multiple of $y$-units) between the main chain and the first level.
% 
% \DescribeOption{domains/}{disulfide level distance}{.2}<number>
% The space (as a multiple of $y$-units) between levels (see the figure below).
%
% \begin{center}
% 	\begin{tikzpicture}[decoration=brace]
% 		\begin{pmbdomains}[show name=false, disulfide level distance=.6]{100}
% 			\setfeaturestyle{disulfide}{draw=red, draw=blue, draw=violet}
% 			\addfeature{disulfide}{2}{10}
% 			\addfeature{disulfide}{5}{50}
% 			\addfeature{disulfide}{8}{15}
% 			\addfeature{disulfide}{20}{45}
% 			\addfeature[level=1]{disulfide}{70}{85}
% 			\addfeature[level=1]{disulfide}{80}{92}
% 			\addfeature{domain}{25}{60}
% 			\draw [dashed, black!80]
% 				(-5 * \pmbdomvalueof{x unit},
% 					\pmbdomvalueof{disulfide base distance} * \pmbdomvalueof{y unit}) --
% 				(105 * \pmbdomvalueof{x unit},
% 					\pmbdomvalueof{disulfide base distance} * \pmbdomvalueof{y unit})
% 				node [right] {\small Level 1};
% 			\draw [dashed, black!60]
% 				(-5 * \pmbdomvalueof{x unit},
% 					\pmbdomvalueof{disulfide base distance} * \pmbdomvalueof{y unit} +
% 					\pmbdomvalueof{disulfide level distance} * \pmbdomvalueof{y unit}) --
% 				(105 * \pmbdomvalueof{x unit},
% 					\pmbdomvalueof{disulfide base distance} * \pmbdomvalueof{y unit} +
% 					\pmbdomvalueof{disulfide level distance} * \pmbdomvalueof{y unit})
% 				node [right] {\small Level 2};
% 			\draw [dashed, black!40]
% 				(-5 * \pmbdomvalueof{x unit},
% 					\pmbdomvalueof{disulfide base distance} * \pmbdomvalueof{y unit} +
% 					2 * \pmbdomvalueof{disulfide level distance} * \pmbdomvalueof{y unit}) --
% 				(105 * \pmbdomvalueof{x unit},
% 					\pmbdomvalueof{disulfide base distance} * \pmbdomvalueof{y unit} +
% 					2 * \pmbdomvalueof{disulfide level distance} * \pmbdomvalueof{y unit})
% 				node [right] {\small Level 3};
% 			\draw [decorate]
% 				(-6 * \pmbdomvalueof{x unit},
% 					0) --
% 				(-6 * \pmbdomvalueof{x unit},
% 					\pmbdomvalueof{disulfide base distance} * \pmbdomvalueof{y unit})
% 				node [pos=.5, left] {\small\texttt{disulfide base distance}};
% 			\draw [decorate]
% 				(-6 * \pmbdomvalueof{x unit},
% 					\pmbdomvalueof{disulfide base distance} * \pmbdomvalueof{y unit} +
% 					\pmbdomvalueof{disulfide level distance} * \pmbdomvalueof{y unit}) --
% 				(-6 * \pmbdomvalueof{x unit},
% 					\pmbdomvalueof{disulfide base distance} * \pmbdomvalueof{y unit} +
% 					2 * \pmbdomvalueof{disulfide level distance} * \pmbdomvalueof{y unit})
% 				node [pos=.5, left] {\small\texttt{disulfide level distance}};
% 		\end{pmbdomains}
% 	\end{tikzpicture}
% \end{center}
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureDisulfide}
% \begin{examplecode}
% \begin{pmbdomains}[show name=false,
% 		disulfide base distance=.7,
% 		disulfide level distance=.4]{100}
% 	\setfeaturestyle{disulfide}{draw=red, draw=blue, draw=violet}
% 	\addfeature{disulfide}{2}{10}
% 	\addfeature{disulfide}{5}{50}
% 	\addfeature{disulfide}{8}{15}
% 	\addfeature{disulfide}{20}{45}
% 	\addfeature[level=1]{disulfide}{70}{85}
% 	\addfeature[level=1]{disulfide}{80}{92}
% 	\addfeature{domain}{25}{60}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
% 
% \begin{DescribeMacros}
% 	\Macro\setdisulfidefeatures{<key list>}
% 	\Macro\adddisulfidefeatures{<key list>}
% 	\Macro\removedisulfidefeatures{<key list>}
% \end{DescribeMacros}
% These macros edit the list of ``disulfide-like'' features, i.\,e. those subject to the automatic stacking mechanism. |\setdisulfidefeatures| renews this list, replacing any previous contents. |\adddisulfidefeatures| adds the features in its \meta{key list} to an existing list, while |\removedisulfidefeatures| removes selected features. By default, there are three disulfide-like features: \texttt{disulfide}, \texttt{DISULFID} and \texttt{range}. Note that |\setfeaturealias| and its relatives do not influence the list.
% 
% \DescribeFeature*{range}
% Indicates a range of residues. \texttt{range} features are disulfide-like in order to prevent them from overlapping.
%
% \DescribeOption{domains/}{range font}{\string\sffamily\string\scriptsize}<font commands>
% Changes the font for the range label. The last command may take a single argument (Example~\ref{exa:DomFeatureRange}).
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureRange}
% \begin{examplecode}
% \begin{pmbdomains}[show name=false]{100}
% 	\addfeature[description=1]{domain}{10}{25}
% 	\addfeature[description=2]{domain}{40}{70}
% 	\addfeature[description=Range 1]{range}{15}{30}
% 	\addfeature[description=Range 2]{range}{25}{60}
% 	\addfeature[description=Range 3,%
% 		style={very thick, draw=black},%
% 		range font=\tiny\textcolor{red}]{range}{68}{86}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
%
% \section{Ruler}
% \label{sec:DomRuler}
%
% \DescribeFeature*{other/ruler}
% This feature is automatically added to the feature list at the end of each |pmbdomains| environment. It draws a ruler below the main chain, which indicates the residue numbers (Example~\ref{exa:DomFeatureRuler}). The following auxiliary commands are available for the feature style \TikZ\ code: |\xMid|, |\yMid|, |\residueNumber| and \opt{current style}.
% 
% \DescribeOption{domains/}{show ruler}{true}<boolean>
% Determines whether the rule is drawn.
%
% \DescribeOption{domains/}{ruler range}{auto-auto}<ruler range list>
% The complete syntax for \opt{ruler range} is
% \begin{quote}
% 	\meta{ruler range list} := \MacroArgs{<ruler range>[','<ruler range>', ...']}\\
% 	\meta{ruler range} := \MacroArgs<lower>'-'<upper>[' step '<interval>]\\
% 	\meta{lower} := \MacroArgs'auto | '<number>[<letter>]' | '(<number>)\\
% 	\meta{upper} := \MacroArgs'auto | '<number>[<letter>]' | '(<number>)\\
% 	\meta{interval} := \MacroArgs<number>
% \end{quote}
% Each \meta{ruler range} tells the package to mark every \ometa{interval}th residue from \meta{lower} to \meta{upper} by an \texttt{other/ruler} feature; the |step| part is optional. Possible values for \meta{lower} and \meta{upper} are:
% \begin{itemize}
% 	\item |auto|, which indicates the leftmost or rightmost residue shown, respectively;
% 	\item a plain number (with an optional letter), which denotes a residue in the \textit{relative} numbering scheme set by \opt{residue numbering};
% 	\item a parenthesized number, which denotes a residue in the \textit{absolute} numbering scheme.
% \end{itemize}
% 
% \DescribeOption{domains/}{default ruler step size}{50}<number>
% Step size for a \meta{ruler range} that lacks the optional |step| part.
% 
% \DescribeOption{domains/}{ruler distance}{-.5}<factor>
% Separation (multiples of the $y$-unit) between ruler and main chain (Example~\ref{exa:DomFeatureRuler}).
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureRuler}
% \begin{examplecode}
% \begin{pmbdomains}[x unit=2mm,
% 		show name=false,
% 		residue numbering={1-40,101-120},
% 		ruler range={auto-10 step 1, 31-(41), 110-120 step 2},
% 		default ruler step size=5,
% 		ruler distance=-.7]{60}
% 	\addfeature{domain}{10}{25}
% 	\addfeature{domain}{40}{(50)}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
%
% \section{Sequences}
% \label{sec:DomSequences}
%
% \DescribeOption{domains/}{sequence}{\textrm{empty}}<sequence>
% Sets the amino acid \meta{sequence} of a protein (single-letter abbreviations).
%
% \DescribeFeature*{other/sequence}
% Displays a sequence which is vertically centered at the main chain. Since a residue is only 0.5~mm wide by default, you should increase the \opt{x unit} when showing \texttt{sequence} features (Example~\ref{exa:DomFeatureSequence}).
% 
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureSequence}
% \begin{examplecode}
% \begin{pmbdomains}[%
% 		sequence=MGSKRSVPSRHRSLTTYEVMFAVLFVILV%
% 			ALCAGLIAVSWLSIQGSVKDAAFGKSHEARGTL,
% 		residues per line=50,
% 		x unit=2mm, show name=false,
% 		ruler range=auto-auto step 10]{50}
% 	\setfeaturestyle{other/sequence}{font=\ttfamily\footnotesize}
% 	\addfeature{domain}{20}{35}
% 	\addfeature{other/sequence}{7}{42}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \begin{DescribeMacros}
% 	\Macro\setfeatureprintfunction{<key list>}{<Lua function>}
% 	\Macro\removefeatureprintfunction{<key list>}
% 	\Macro\pmbdomdrawfeature{<type>}
% \end{DescribeMacros}
% Some features require sophisticated coordinate calculations. Hence, you might ocasionally want to call a Lua function as ``preprocessor'' before executing the \meta{TikZ code} of |\setfeatureshape|. For this purpose, |\setfeatureprintfunction| registers such a \meta{Lua function} and |\removefeatureprintfunction| deletes the preprocessing function(s) for all features in the \meta{key list}.
%
% A suitable Lua function
% \begin{itemize}
% 	\item receives up to six arguments in the following order (see also section~\ref{ssc:DocDomLuaPrintFunctions}):
% 		\begin{enumerate}
% 			\item A table describing the feature (see section~\ref{ssc:DocDomLuaProteinClass} for its fields);
% 			\item the left $x$-coordinate of the feature (an integer);
% 			\item its right $x$-coordinate (an integer);
% 			\item the $y$-coordinate of the current line (an integer);
% 			\item the dimension stored in \opt{x unit}, converted to scaled points (an integer);
% 			\item the dimension stored in \opt{y unit}, converted to scaled points (an integer);
% 		\end{enumerate}
% 	\item performs all necessary calculations and defines all \TeX\ macros required by |\setfeatureshape|;
% 	\item may execute |\pmbdomdrawfeature| with the appropriate feature \meta{type} to draw the feature.
% \end{itemize}
% 
%
% Example~\ref{exa:DomPrintFunction} devises a new print function, §printFunnySequence§ (lines 2--17). It is similar to the default print function for \texttt{other/sequence} features, but adds random values to the $y$-coordinate of the individual letters.
% 
% §printFunnySequence§ is a function with six arguments (line 2). We add the width of half a residue to the left $x$-coordinate, §xLeft§ (line 3), since each letter should be horizontally centered. We iterate over each letter in the §sequence§ field of the §feature§ table (lines 4--16). In each loop, calculated coordinates are stored in the \TeX\ macros |\xMid| (lines 5--7) and |\yMid| (lines 8--10). The construction |\string\\...| is expanded to |\\...| when §tex.sprint§ passes its argument back to \TeX. §pgfmolbio.dimToString§ converts a number representing a dimension in scaled points to a string (e.\,g., 65536 to ``1pt'', see section~\ref{sec:DocPkgLua}). The letter of the current residue is stored in |\currentResidue| (lines 11--13). Finally, each letter is drawn by calling |\pmbdomdrawfeature{other/sequence}| (line 14), and the $x$-coordinate increases by one (line 15). Line 25 registers §printFunnySequence§ for \texttt{other/sequence} features.
%
% \begin{exampletable}
% \caption{}
% \label{exa:DomPrintFunction}
% \begin{examplecode}
% \directlua{
% 	function printFunnySequence (feature, xLeft, xRight, yMid, xUnit, yUnit)
% 		xLeft = xLeft + 0.5
% 		for currResidue in feature.sequence:gmatch(".") do
% 			tex.sprint("\string\\def\string\\xMid{" ..
% 				pgfmolbio.dimToString(xLeft * xUnit) ..
% 				"}")
% 			tex.sprint("\string\\def\string\\yMid{" ..
% 				pgfmolbio.dimToString((yMid + math.random(-5, 5) / 20) * yUnit) ..
% 				"}")
% 			tex.sprint("\string\\def\string\\currentResidue{" ..
% 				currResidue ..
% 				"}")
% 			tex.sprint("\string\\pmbdomdrawfeature{other/sequence}")
% 			xLeft = xLeft + 1
% 		end
% 	end
% }
% 
% \begin{pmbdomains}[%
% 		sequence=MGSKRSVPSRHRSLTTYEVMFAVLFVILVALCAGLIAVSWLSIQGSVKDAAF,
% 		x unit=2mm, show name=false,
% 		ruler range=auto-auto step 10]{40}
% 	\setfeaturestyle{other/sequence}{font=\ttfamily\footnotesize}
% 	\setfeatureprintfunction{other/sequence}{printFunnySequence}
% 	\addfeature{domain}{20}{30}
% 	\addfeature{other/sequence}{7}{38}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeFeature*{other/magnified sequence above}
% Displays its sequence as a single string above the main chain, with dashed lines indicating the sequence start and stop on the backbone. This feature allows you to show sequences without the need to increase the \opt{x unit}.
% 
% \DescribeFeature*{other/magnified sequence below}
% Displays the sequence \textit{below} the backbone.
%
% \DescribeOption{domains/}{magnified sequence font}{\string\ttfamily\string\footnotesize}<font commands>
% The font used for a magnified sequence (Example~\ref{exa:DomFeatureMagnifiedSequence}).
% 
% \begin{exampletable}
% \caption{}
% \label{exa:DomFeatureMagnifiedSequence}
% \begin{examplecode}
% \begin{pmbdomains}[%
% 		sequence=MGSKRSVPSRHRSLTTYEVMFAVLFVIL%
% 			VALCAGLIAVSWLSIQGSVKDAAFGKSHEARGTL,
% 		enlarge left=-1cm, enlarge right=1cm, enlarge bottom=-1cm,
% 		show name=false, show ruler=false]{50}
% 	\addfeature{other/magnified sequence above}{7}{20}
% 	\addfeature[magnified sequence font=\scriptsize\sffamily]%
% 		{other/magnified sequence below}{34}{42}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
%
% \section{Secondary Structure}
% \label{sec:DomSecondaryStructure}
% 
% \DescribeOption{domains/}{show secondary structure}{false}<boolean>
% Determines whether the secondary structure is shown.
% 
% \DescribeOption{domains/}{secondary structure distance}{1}<factor>
% Secondary structures appear along a thin line \meta{factor} times the value of \opt{y unit} above the main chain. In accordance with the categories established by the Dictionary of Protein Secondary Structure\footnote{Kabsch, W. and Sander, C. (1983). Dictionary of protein secondary structure: pattern recognition of hydrogen-bonded and geometrical features. \textit{Biopolymers} \textbf{22}(12), 2577--2637.}, \pkg{pgfmolbio} provides seven features for displaying secondary structure types (Example~\ref{exa:DomShowSecStructure}):
% 
% \begin{exampletable}
% \caption{}
% \label{exa:DomShowSecStructure}
% \begin{examplecode}
% \begin{pmbdomains}[%
% 		show name=false,
% 		sequence=MGSKRSVPSRHRSLTTYEVMFAVLFVILVALCAGL,
% 		x unit=2.5mm,
% 		enlarge top=1.5cm,
% 		ruler range=auto-auto step 1,
% 		show secondary structure=true,
% 		secondary structure distance=1.5
% 	]{35}
% 	\setfeaturestyle{other/sequence}{{font=\ttfamily\small}}
% 	\addfeature{alpha helix}{2}{8}
% 	\addfeature{pi helix}{9}{11}
% 	\addfeature{310 helix}{13}{18}
% 	\addfeature{beta strand}{20}{23}
% 	\addfeature{beta bridge}{25}{28}
% 	\addfeature{beta turn}{30}{31}
% 	\addfeature{bend}{33}{34}
% 	\addfeature{other/sequence}{1}{35}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeFeature{alpha helix}{HELIX}
% Shows an $\alpha$-helix.
% 
% \DescribeFeature*{pi helix}
% Shows a $\pi$-helix.
% 
% \DescribeFeature*{310 helix}
% Shows a $3_{10}$-helix.
% 
% \DescribeFeature{beta strand}{STRAND}
% Shows a $\beta$-strand.
% 
% \DescribeFeature{beta turn}{TURN}
% Shows a $\beta$-turn.
% 
% \DescribeFeature*{beta bridge}
% Shows a $\beta$-bridge.
% 
% \DescribeFeature*{bend}
% Shows a bend.
% 
% \begin{figure}
% 	\centering
% 	\caption{Shading colors of helix features.}
% 	\label{fig:DomHelixColors}
% 	\begin{tabular}{*4{>{\ttfamily}l}}
% 		\toprule
% 		\rmfamily\itshape Name & \multicolumn{3}{c}{\itshape \pkg{xcolor} definition} \\
% 		\cmidrule(lr){2-4}
% 			& \rmfamily $\alpha$-helix & \rmfamily $\pi$-helix & \rmfamily $3_{10}$-helix \\
% 		\midrule
% 		helix back border color  & \multicolumn{3}{c}{\ttfamily white!50!black \color{white!50!black}\rule{1ex}{1ex}} \\
% 		helix back main color    & \multicolumn{3}{c}{\ttfamily white!90!black \color{white!90!black}\rule{1ex}{1ex}} \\
% 		helix back middle color  & \multicolumn{3}{c}{\ttfamily white \color{white}\rule{1ex}{1ex}} \\
% 		\midrule
% 		helix front border color & red!50!black \color{red!50!black}\rule{1ex}{1ex}
% 			& yellow!50!black \color{yellow!50!black}\rule{1ex}{1ex}
% 			& magenta!50!black \color{magenta!50!black}\rule{1ex}{1ex} \\
% 		helix front main color & red!90!black \color{red!90!black}\rule{1ex}{1ex}
% 			& yellow!70!red~~ \color{yellow!70!red}\rule{1ex}{1ex}
% 			& magenta!90!black \color{magenta!90!black}\rule{1ex}{1ex} \\
% 		helix front middle color & red!10!white \color{red!10!white}\rule{1ex}{1ex}
% 			& yellow!10!white \color{yellow!10!white}\rule{1ex}{1ex}
% 			& magenta!10!white \color{magenta!10!white}\rule{1ex}{1ex} \\
% 		\bottomrule
% 	\end{tabular}\hspace*{-67pt}\par\bigskip
% 	\begin{tikzpicture}[font=\ttfamily\scriptsize]
% 		\makeatletter
% 		\draw [shading=helix full back] (1.5, 0) \@pmb@dom@helixsegment{1.5mm};
% 		\tikzset{left}
% 		\draw [->] (0, 0) node {helix back border color} -- (.5, 0);
% 		\draw [->] (0, .225) node {helix back main color} -- (.5, .225);
% 		\draw [->] (0, .675) node {helix back middle color} -- (.5, .675);
% 		\draw [->] (0, 1.575) node {helix back main color} -- (.5, 1.575);
% 		\draw [->] (0, 2.25) node {helix back border color} -- (.5, 2.25);
% 		\tikzset{right}
% 		\draw [shading=helix full front] (4, 0) [xscale=-1] \@pmb@dom@helixsegment{1.5mm};
% 		\draw [<-] (5, 0) -- (5.5, 0) node {helix front border color};
% 		\draw [<-] (5, .675) -- (5.5, .675) node {helix front main color};
% 		\draw [<-] (5, 1.575) -- (5.5, 1.575) node {helix front middle color};
% 		\draw [<-] (5, 2.025) -- (5.5, 2.025) node {helix front main color};
% 		\draw [<-] (5, 2.25) -- (5.5, 2.25) node {helix front border color};
% 		\tikzset{font=\rmfamily\scriptsize}
% 		\draw (-4, -.2) -- (-4, -.5) -- (2.5, -.5)
% 			node [pos=.5, below] {Shading \texttt{helix full back}}
% 			-- (2.5, -.2);
% 		\draw (3, -.2) -- (3, -.5) -- (9.5, -.5)
% 			node [pos=.5, below] {Shading \texttt{helix full front}}
% 			-- (9.5, -.2);
% 	\end{tikzpicture}
% \end{figure}
% 
% \begin{table}[p]
% 	\centering
% 	\caption{Customizing helices in the \module{domains} module.}
% 	\label{tab:DomHelixHelperFeatures}
% 	\begin{tabular}{*2{>{\ttfamily}l} *2{>{\ttfamily\color{ProcessBlue}}l}}
% 		\toprule
% 		\rmfamily\itshape (a) Subfeatures
% 			& \rmfamily\itshape (b) Corresponding shadings
% 			& \multicolumn{2}{l}{\itshape (c) Coordinates} \\
% 		\cmidrule(r){1-1}\cmidrule(r){2-2}\cmidrule{3-4}
% 		helix/half upper back  & helix half upper back  & \string\xLeft  & \string\yMid   \\
% 		helix/half lower back  & helix half lower back  & \string\xRight & \string\yMid   \\
% 		helix/full back        & helix full back        & \string\xMid   & \string\yLower \\
% 		helix/half upper front & helix half upper front & \string\xRight & \string\yMid   \\
% 		helix/full front       & helix full front       & \string\xMid   & \string\yLower \\
% 		\bottomrule
% 	\end{tabular}
% \end{table}
% 
% \begin{exampletable}[p]
% \caption{}
% \label{exa:DomHelixColors}
% \begin{examplecode}
% \begin{pmbdomains}[%
% 		show name=false,
% 		x unit=2.5mm,
% 		enlarge top=1.5cm,
% 		ruler range=auto-auto step 5,
% 		show secondary structure
% 	]{35}
% 	\setfeaturestyle{alpha helix}{%
% 		*1{helix front border color=blue!50!black,%
% 		helix front main color=orange,%
% 		helix front middle color=yellow!50},%
% 		*1{helix front border color=olive,%
% 		helix front main color=magenta,%
% 		helix front middle color=green!50}%
% 	}
% 	\addfeature{alpha helix}{2}{8}
% 	\addfeature{alpha helix}{9}{15}
% 	\addfeature{alpha helix}{20}{27}
% 	\addfeature{alpha helix}{30}{34}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
% 
% \begin{exampletable}[p]
% \caption{}
% \label{exa:DomHelixHelperFeature}
% \begin{examplecode}[basicstyle=\ttfamily\tiny]
% \pgfmathsetmacro\yShift{%
% 	\pmbdomvalueof{secondary structure distance}
% 		* \pmbdomvalueof{y unit}%
% }
% 
% \setfeatureshape{helix/half upper back}{%
% 	\draw [shading=helix half upper back]
% 		(\xLeft, \yMid + \yShift pt) --
% 		(\xLeft + .5 * \pmbdomvalueof{x unit},
% 			\yMid + 1.5 * \pmbdomvalueof{x unit} + \yShift pt) --
% 		(\xLeft + 1.5 * \pmbdomvalueof{x unit},
% 			\yMid + 1.5 * \pmbdomvalueof{x unit} + \yShift pt) --
% 		(\xLeft + \pmbdomvalueof{x unit}, \yMid + \yShift pt) --
% 		cycle;
% }
% 
% \setfeatureshape{helix/half lower back}{%
% 	\draw [shading=helix half lower back]
% 		(\xRight, \yMid + \yShift pt) --
% 		(\xRight - .5 * \pmbdomvalueof{x unit},
% 			\yMid - 1.5 * \pmbdomvalueof{x unit} + \yShift pt) --
% 		(\xRight - 1.5 * \pmbdomvalueof{x unit},
% 			\yMid - 1.5 * \pmbdomvalueof{x unit} + \yShift pt) --
% 		(\xRight - \pmbdomvalueof{x unit}, \yMid + \yShift pt) --
% 		cycle;
% }
% 
% \setfeatureshape{helix/full back}{%
% 	\draw [shading=helix full back]
% 		(\xMid, \yLower + \yShift pt) --
% 		(\xMid - \pmbdomvalueof{x unit}, \yLower + \yShift pt) --
% 		(\xMid, \yLower + 3 * \pmbdomvalueof{x unit} + \yShift pt) --
% 		(\xMid + \pmbdomvalueof{x unit},
% 			\yLower + 3 * \pmbdomvalueof{x unit} + \yShift pt) --
% 		cycle;
% }
% 
% \setfeatureshape{helix/half upper front}{%
% 	\draw [shading=helix half upper front]
% 		(\xRight, \yMid + \yShift pt) --
% 		(\xRight - .5 * \pmbdomvalueof{x unit},
% 			\yMid + 1.5 * \pmbdomvalueof{x unit} + \yShift pt) --
% 		(\xRight - 1.5 * \pmbdomvalueof{x unit},
% 			\yMid + 1.5 * \pmbdomvalueof{x unit} + \yShift pt) --
% 		(\xRight - \pmbdomvalueof{x unit}, \yMid + \yShift pt) --
% 		cycle;
% }
% 
% \setfeatureshape{helix/full front}{%
% 	\draw [shading=helix full front]
% 		(\xMid, \yLower + \yShift pt) --
% 		(\xMid + \pmbdomvalueof{x unit}, \yLower + \yShift pt) --
% 		(\xMid, \yLower + 3 * \pmbdomvalueof{x unit} + \yShift pt) --
% 		(\xMid - \pmbdomvalueof{x unit},
% 			\yLower + 3 * \pmbdomvalueof{x unit} + \yShift pt) --
% 		cycle;
% }
% 
% \begin{pmbdomains}[%
% 		show name=false, sequence=MGSKRSVPSR,
% 		x unit=2.5mm, enlarge top=1.5cm,
% 		ruler range=auto-auto step 1,
% 		show secondary structure
% 	]{10}
% 	\setfeaturestyle{other/sequence}{{font=\ttfamily\small}}
% 	\addfeature{alpha helix}{2}{6}
% 	\addfeature{alpha helix}{8}{9}
% 	\addfeature{other/sequence}{1}{10}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
%
% \bigskip  While changing the appearance of nonhelical secondary structure elements is simple, the complex helical features employ the print function §printHelixFeature§ (section~\ref{ssc:DocDomLuaPrintFunctions}). However, their appearance can be customized on several levels:
% \begin{enumerate}
% 	\item The elements of a helical feature are drawn by five ``subfeatures'', which are called by §printHelixFeature§ (Table~\ref{tab:DomHelixHelperFeatures}a).
% 	\item For each subfeature, there is a corresponding shading (Table~\ref{tab:DomHelixHelperFeatures}b; see section~\ref{ssc:DocDomTexSecondaryStructure} and section~83 of the \TikZ\ manual for their definitions).
% 	\item These shadings use six colors in total, three for front and three for back shadings (Figure~\ref{fig:DomHelixColors}). For each color, there is a key of the same name, so you can change helix colors in feature style lists (Example~\ref{exa:DomHelixColors}).
% \end{enumerate}
% 
% 
% \section{File Input}
% \label{sec:DomFileInput}
% 
% \begin{DescribeMacros}
% 	\Macro\inputuniprot{<Uniprot file>}
% 	\Macro\inputgff{<gff file>}
% \end{DescribeMacros}
% Include the features defined in an \meta{Uniprot file} or \meta{gff file}, respectively (Example~\ref{exa:DomInputExternalFiles}). These macros are only defined in |pmbdomains|.
% 
% \begin{exampletable}[hb]
% \caption{}
% \label{exa:DomInputExternalFiles}
% \begin{examplecode}
% \begin{pmbdomains}[show secondary structure]{}
% 	\setfeaturestyle{disulfide}{{draw=olive,thick}}
% 	\inputuniprot{SampleUniprot.txt}
% \end{pmbdomains}
% \end{examplecode}
% \begin{examplecode}
% \begin{pmbdomains}[show name=false,show secondary structure]{200}
% 	\setfeaturestyle{disulfide}{{draw=olive,thick}}
% 	\inputgff{SampleGff.gff}
% \end{pmbdomains}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{domains/}{sequence length}{\textrm{(empty)}}<number>
% Note that in Example~\ref{exa:DomInputExternalFiles}, we had to set a sequence length for the |pmbdomains| environment that contains the |\inputgff| macro. \file{gff} files lack a sequence length field. By contrast, \pkg{pgfmolbio} reads the sequence length from an Uniprot file, and thus the mandatory argument of |pmbdomains| may remain empty. In general, the sequence length is stored in the key of the same name.
% 
% 
% 
% \chapter{The \texorpdfstring{\module{convert}}{convert} module}
% \label{cha:Convert}
% 
%
% \section{Overview}
% \label{sec:ConOverview}
% 
% The \module{convert} module supports users who wish to include \pkg{pgfmolbio} graphs, but who do not want to typeset their documents with a \TeX\ engine that implements Lua. To this end, the \module{convert} workflow comprises two steps: (1) Running Lua\LaTeX\ on an input file that contains at least one |\pmbchromatogram| or similar macros/environments. This will generate one \file{tex} file per graph macro/environment that contains only \TikZ\ commands. (2) Including this file in another \TeX\ document (via |\input|) which is then processed by any \TeX\ engine that supports \TikZ.
% 
% 
% \section{Converting Chromatograms}
% \label{sec:ConChromatograms}
%
% In order to create the external \TikZ\ file, run an input file like the one below through Lua\LaTeX:
% \begin{lstlisting}[style=latex-expl,gobble=2]
% \documentclass{article}
% \usepackage[chromatogram,convert]{pgfmolbio}
% 
% \begin{document}
% 	\pmbchromatogram[sample range=base 50-base 60]{SampleScf.scf}
% 	\pmbchromatogram[/pgfmolbio/convert/output file name=mytikzfile]%
% 		{SampleScf.scf}
% 	\pmbchromatogram[sample range=base 60-base 70]{SampleScf.scf}
% \end{document}
% \end{lstlisting}
% The \module{convert} module disables \file{pdf} output and introduces the following keys:
% 
% \DescribeOption{convert/}{output file name}{(auto)}<text>\relax
% \DescribeOption{convert/}{output file extension}{tex}<text>\relax
% With the default value for \opt{output file name} (``|(auto)|''), \pkg{pgfmolbio} creates files that are named \file{pmbconverted} and numbered consecutively (\file{pmbconverted0.tex}, \file{pmbconverted1.tex} etc.). Both keys can be changed locally (e.\,g., in the optional argument of |\pmbchromatogram|), but this turns off automatic numbering.
% 
% The code above produces the files \file{pmbconverted0.tex}, \file{mytikzfile.tex} and \file{pmbconverted2.tex}. Below is an annotated excerpt from \file{pmbconverted0.tex}:
% \begin{lstlisting}[style=latex-expl,gobble=2,escapeinside=`',basicstyle=\ttfamily\scriptsize,breaklines]
% \begin{tikzpicture}
% 	`[canvas section]'
% 	\draw [/pgfmolbio/chromatogram/canvas style] (0mm, -0mm) rectangle (25mm, 20mm);
% 	`[traces section]'
% 	\draw [/pgfmolbio/chromatogram/trace A style] (0mm, 6.37mm) -- (0.2mm, 6.66mm) -- `[many coordinates]' -- (25mm, 0mm);
% 	\draw [/pgfmolbio/chromatogram/trace C style] (0mm, 0.06mm) -- (0.2mm, 0.05mm) -- `[...]' -- (25mm, 6.27mm);
% 	\draw [/pgfmolbio/chromatogram/trace G style] (0mm, 0.01mm) -- (0.2mm, 0.01mm) -- `[...]' -- (25mm, 0.05mm);
% 	\draw [/pgfmolbio/chromatogram/trace T style] (0mm, 0mm) -- (0.2mm, 0mm) -- `[...]' -- (25mm, 0.06mm);
% 	`[ticks/base labels/probabilities section]'
% 	\draw [/pgfmolbio/chromatogram/tick A style] (0mm, -0mm) -- (0mm, -1mm) node [/pgfmolbio/chromatogram/base label A style] {\pgfkeysvalueof{/pgfmolbio/chromatogram/base label A text}} node [/pgfmolbio/chromatogram/base number style] {\strut 50};
% 	\draw [ultra thick, pmbTraceGreen] (0mm, -8mm) -- (0.9mm, -8mm);
% 	\draw [/pgfmolbio/chromatogram/tick T style] (1.8mm, -0mm) -- (1.8mm, -1mm) node [/pgfmolbio/chromatogram/base label T style] {\pgfkeysvalueof{/pgfmolbio/chromatogram/base label T text}};
% 	\draw [ultra thick, pmbTraceGreen] (0.9mm, -8mm) -- (3mm, -8mm);
% 	\draw [/pgfmolbio/chromatogram/tick A style] (4.2mm, -0mm) -- (4.2mm, -1mm) node [/pgfmolbio/chromatogram/base label A style] {\pgfkeysvalueof{/pgfmolbio/chromatogram/base label A text}};
% 	\draw [ultra thick, pmbTraceGreen] (3mm, -8mm) -- (5.4mm, -8mm);
% 	`[...]'
% 	`[more ticks, base labels and probability rules]'
% \end{tikzpicture}
% \end{lstlisting}
% 
% You can change the format of the coordinates by the following keys:
% 
% \DescribeOption{}{coordinate unit}{mm}<unit>
% \DescribeOption{}{coordinate format string}{\letterpercent s\letterpercent s}<format string>\relax
% \pkg{pgfmolbio} internally calculates dimensions in scaled points, but usually converts them before returning them to \TeX. To this end, it selects the \meta{unit} stored in \opt{coordinate unit} (any of the standard \TeX\ units of measurement: \texttt{bp}, \texttt{cc}, \texttt{cm}, \texttt{dd}, \texttt{in}, \texttt{mm}, \texttt{pc}, \texttt{pt} or \texttt{sp}). In addition, the package formats the dimension according to the \meta{format string} given by \opt{coordinate format string}. This string basically follows the syntax of C's \texttt{printf} function, as described in the Lua reference manual. (Note: Use |\letterpercent| instead of \texttt{\%}, since \TeX\ treats anything following a percent character as comment.)
% 
% Depending on the values of \opt{coordinate unit} and \opt{coordinate format string}, dimensions will be printed in different ways (Table~\ref{tab:CoordFormat}).
% 
% \begin{table}
% 	\centering
% 	\caption{Effects of \texttt{\color{opt}coordinate unit} and \texttt{\color{opt}coordinate format string} when converting an internal \pkg{pgfmolbio} dimension of 200000~[sp].}
% 	\label{tab:CoordFormat}
% 	\begin{tabularx}{\textwidth}{*3{>{\ttfamily}l}X}
% 		\toprule
% 		\multicolumn{2}{c}{\itshape Values} & \multicolumn{1}{l}{\itshape Output} & \itshape Notes \\
% 		\cmidrule(r){1-2}\cmidrule(r){3-3}\cmidrule{4-4}
% 		sp & \%s\%s   & 200000sp          & simple conversion \\
% 		mm & \%s\%s   & 1.0725702011554mm & default settings, may lead to a large number of decimal places \\
% 		mm & \%.3f\%s & 1.073mm           & round to three decimal places \\
% 		cm & \%.3f    & 0.107             & don't print any unit, i.\,e. use \TikZ's \texttt{xyz} coordinate system \\
% 		\bottomrule
% 	\end{tabularx}
% \end{table}
% 
% \bigskip
% The output files can be included in a file which is processed by pdf\LaTeX:
% \begin{lstlisting}[style=latex-expl,gobble=2]
% \documentclass{article}
% \usepackage[chromatogram]{pgfmolbio}
% 
% \begin{document}
% 	\input{pmbconverted.tex}
% \end{document}
% \end{lstlisting}
% 
% Several keys of the \module{chromatogram} module must contain their final values before conversion, while others can be changed afterwards, i.\,e., before the generated file is loaded with |\input| (Table~\ref{tab:ConvertChrKeys}).
% 
% \begin{table}[ht]
% 	\centering
% 	\caption{Keys of the \module{chromatogram} module that require final values prior to conversion.}
% 	\label{tab:ConvertChrKeys}
% 	\begin{tabular}{*3{>{\ttfamily\color{opt}}l}}
% 		\toprule
% 		\multicolumn{2}{c}{\itshape Required} & \multicolumn{1}{c}{\itshape Not required} \\
% 		\cmidrule(r){1-2}\cmidrule(l){3-3}
% 		base labels drawn          & sample range      & base label style \\
% 		base number range          & samples per line  & base label X style \\
% 		baseline skip              & show base numbers & base label X text \\
% 		bases drawn                & tick length       & base number style \\
% 		canvas height              & ticks drawn       & canvas style \\
% 		probabilities drawn        & traces drawn      & tick style \\
% 		probability distance       & x unit            & tick X style \\
% 		probability style function & y unit            & trace style \\
% 		                           &                   & trace X style \\
% 		\bottomrule
% 	\end{tabular}
% \end{table}
% 
% 
% \section{Converting Domain Diagrams}
% \label{sec:ConDomains}
% 
% \DescribeOption{convert/}{output code}{tikz}'pgfmolbio | tikz'
% In principle, domain diagrams are converted like sequencing chromatograms (section~\ref{sec:ConChromatograms}). However, \opt{output code} lets you choose the kind of code \module{convert} writes to the output file: |pgfmolbio| generates a |pmbdomains| environment containing |\addfeature| commands, |tikz| produces \TikZ\ code.
% 
% ``Converting'' one |pmbdomains| environment in the input file to another one in the output file might seem pointless. Nonetheless, this conversion mechanism can be highly useful for extracting features from a Uniprot or \file{gff} file. For example, consider the following input file:
% \begin{lstlisting}[style=latex-expl,gobble=2]
% \documentclass{article}
% \usepackage[domains,convert]{pgfmolbio}
% 
% \begin{document}
% 	\pgfmolbioset[convert]{output code=pgfmolbio}
% 	\begin{pmbdomains}{}
% 		\inputuniprot{SampleUniprot.txt}
% 	\end{pmbdomains}
% \end{document}
% \end{lstlisting}
% The corresponding output is
% \begin{lstlisting}[style=latex-expl,gobble=2,escapeinside=`']
% \begin{pmbdomains}
% 		[name={TestProtein},
% 		sequence=MGSKRSVPSRHRSL`[...]'PLATPGNVSIECP]{200}
% 	\addfeature[description={Disulfide 1}]{DISULFID}{5}{45}
% 	\addfeature[description={Disulfide 2}]{DISULFID}{30}{122}
% 	\addfeature[description={Disulfide 3}]{DISULFID}{51}{99}
% 	\addfeature[description={Domain 1}]{DOMAIN}{10}{40}
% 	\addfeature[description={Domain 2}]{DOMAIN}{60}{120}
% 	\addfeature[description={Domain 3}]{DOMAIN}{135}{178}
% 	\addfeature[description={Strand 1}]{STRAND}{15}{23}
% 	\addfeature[description={Strand 2}]{STRAND}{25}{32}
% 	\addfeature[description={Helix 1}]{HELIX}{60}{75}
% 	\addfeature[description={Helix 2}]{HELIX}{80}{108}
% 	\addfeature[description={Sugar 1}]{CARBOHYD}{151}{151}
% 	\addfeature[description={Sugar 2}]{CARBOHYD}{183}{183}
% \end{pmbdomains}
% \end{lstlisting}
% Obviously, this method is particularly suitable for Uniprot files containing many features.
% 
% \DescribeOption{convert/}{include description}{true}<boolean>
% Decides whether the feature description obtained from the input should appear in the output. Since the description field in FT entries of Uniprot files can be quite long, you may not wish to show it in the output. For example, the output of the example above with \opt{include description}|=false| looks like
% \begin{lstlisting}[style=latex-expl,gobble=2,escapeinside=`']
% \begin{pmbdomains}
% 		[name={TestProtein},
% 		sequence=MGSKRSVPSRHRSL`[...]'PLATPGNVSIECP]{200}
% 	\addfeature{DISULFID}{5}{45}
% 	\addfeature{DISULFID}{30}{122}
% 	\addfeature{DISULFID}{51}{99}
% 	`[...]'
% \end{pmbdomains}
% \end{lstlisting}
% 
% \bigskip
% With \opt{output code}|=tikz|, we obtain the following (annotated) output file:
% \begin{lstlisting}[style=latex-expl,gobble=2,escapeinside=`',basicstyle=\ttfamily\scriptsize,breaklines]
% `[set relevant keys]'
% \pgfmolbioset[domains]{name={TestProtein},sequence={MGSKRS`[...]'VSIECP},sequence length=200}
% `[the actual \TikZ\ picture]'
% \begin{tikzpicture}
% 	`[each feature appears within its own scope]'
% 	\begin{scope}\begin{pgfinterruptboundingbox}
% 		\def\xLeft{0mm}
% 		\def\xMid{50mm}
% 		\def\xRight{100mm}
% 		\def\yMid{-0mm}
% 		\def\featureSequence{MGSKRS`[...]'VSIECP}
% 		\clip (-50mm, \yMid + 100mm) rectangle (150mm, \yMid - 100mm);
% 		\pgfmolbioset[domains]{style={{draw, line width=2pt, black!25}},@layer=1}
% 		\pmbdomdrawfeature{other/main chain}
% 	\end{pgfinterruptboundingbox}\end{scope}
% 	`[more features]'
% 	`[...]'
% 	`[helix features require additional drawing commands]'
% 	\begin{scope}\begin{pgfinterruptboundingbox}
% 		\def\xLeft{29.5mm}
% 		\def\xMid{33.5mm}
% 		\def\xRight{37.5mm}
% 		\def\yMid{-0mm}
% 		\def\featureSequence{GTLKIISGATYNPHLQ}
% 		\clip (-50mm, \yMid + 100mm) rectangle (87.5mm, \yMid - 100mm);
% 		\pgfmolbioset[domains]{style={{helix front border color=red!50!black,helix front main color=red!90!black,helix front middle color=red!10!white}},description={Helix 1}}
% 		\pgfmolbioset[domains]{current style}
% 		\def\xLeft{29.5mm}
% 		\def\yMid{-0mm}
% 		\pmbdomdrawfeature{helix/half upper back}
% 		\def\xMid{30.75mm}
% 		\def\yLower{-0.75mm}
% 		\pmbdomdrawfeature{helix/full back}
% 		`[more helix parts]'
% 	\end{pgfinterruptboundingbox}\end{scope}
% 	`[...]'
% 	`[ruler section]'
% 	\begin{scope}
% 		\pgfmolbioset[domains]{current style/.style={black}}
% 			\def\xMid{0.25mm}
% 			\let\xLeft\xMid\let\xRight\xMid
% 			\def\yMid{-0mm}
% 			\def\residueNumber{1}
% 			\pmbdomdrawfeature{other/ruler}
% 		\pgfmolbioset[domains]{current style/.style={black!50}}
% 			\def\xMid{25.25mm}
% 			\let\xLeft\xMid\let\xRight\xMid
% 			\def\yMid{-0mm}
% 			\def\residueNumber{51}
% 			\pmbdomdrawfeature{other/ruler}
% 		`[more ruler numbers]'
% 		`[...]'
% 	\end{scope}
% 	`[name section]'
% 	\begin{scope}
% 		\pgfmolbioset[domains]{current style/.style={font=\sffamily }}
% 		\def\xLeft{0mm}
% 		\def\xMid{50mm}
% 		\def\xRight{100mm}
% 		\def\yMid{0mm}
% 		\pmbdomdrawfeature{other/name}
% 	\end{scope}
% 	`[adjust picture size]'
% 	\pmbprotocolsizes{\pmbdomvalueof{enlarge left}}{\pmbdomvalueof{enlarge top}}
% 	\pmbprotocolsizes{100mm + \pmbdomvalueof{enlarge right}}{-0mm + \pmbdomvalueof{enlarge bottom}}
% \end{tikzpicture}
% \end{lstlisting}
% 
% Several keys of the \module{domains} module must contain their final values before conversion, and some macros can't be used afterwards (Table~\ref{tab:ConvertDomKeysAndMacros}).
% 
% \begin{table}[ht]
% 	\caption{Keys and macros of the \module{domain} module that require final values prior to conversion or can't be used afterwards, respectively.}
% 	\label{tab:ConvertDomKeysAndMacros}\small
% 	\begin{tabular}{*3{>{\ttfamily\color{opt}}l}}
% 		\toprule
% 		\multicolumn{2}{c}{\itshape Required} & \multicolumn{1}{c}{\itshape Not required} \\
% 		\cmidrule(r){1-2}\cmidrule(l){3-3}
% 		baseline skip            & ruler distance               & domain font \\
% 		default ruler step size  & ruler range                  & enlarge bottom \\
% 		description              & secondary structure distance & enlarge left \\
% 		disulfide base distance  & sequence                     & enlarge right \\
% 		disulfide level distance & sequence length              & enlarge top \\
% 		level                    & show ruler                   & magnified sequence font \\
% 		name                     & style                        & range font \\
% 		residue numbering        & x unit                       & show secondary structure \\
% 		residue range            & y unit                       & \\
% 		residues per line        &                              & \\
% 		\cmidrule(r){1-2}\cmidrule(l){3-3}
% 		\color{ProcessBlue}\string\adddisulfidefeatures
% 			& \color{ProcessBlue}\string\setfeatureprintfunction
% 			& \color{ProcessBlue}\string\setfeaturealias \\
% 		\color{ProcessBlue}\string\removedisulfidefeatures
% 			& \color{ProcessBlue}\string\setfeaturestyle
% 			& \color{ProcessBlue}\string\setfeatureshape \\
% 		\color{ProcessBlue}\string\removefeatureprintfunction
% 			& \color{ProcessBlue}\string\setfeaturestylealias
% 			& \color{ProcessBlue}\string\setfeatureshapealias \\
% 		\color{ProcessBlue}\string\setdisulfidefeatures & & \\
% 		\bottomrule
% 	\end{tabular}\hspace*{-53pt}
% \end{table}
% 
% 
% \StopEventually{}
% \chapter{Implementation}
% \label{cha:Implementation}
% \renewcommand*\thelstnumber{\arabic{section}.\arabic{lstnumber}}
%
% \iffalse
%<*pgfmolbio-tex>
% \fi
%
% \section{\texorpdfstring{\file{pgfmolbio.sty}}{pgfmolbio.sty}}
% \label{sec:DocPkgTex}
%
% \def\ydoclistingssettings{\lstset{style=latex-doc}}
% The options for the main style file determine which module(s) should be loaded.
%
%    \begin{macrocode}
\newif\ifpmb@loadmodule@chromatogram
\newif\ifpmb@loadmodule@domains
\newif\ifpmb@loadmodule@convert

\DeclareOption{chromatogram}{%
  \pmb@loadmodule@chromatogramtrue%
}
\DeclareOption{domains}{%
  \pmb@loadmodule@domainstrue%
}
\DeclareOption{convert}{%
  \pmb@loadmodule@converttrue%
}

\ProcessOptions

%    \end{macrocode}
% The main style file also loads the following packages and \TikZ\ libraries.
%    \begin{macrocode}
\RequirePackage{ifluatex}
\ifluatex
  \RequirePackage{luatexbase-modutils}
    \RequireLuaModule{lualibs}
    \RequireLuaModule{pgfmolbio}
\fi
\RequirePackage[svgnames,dvipsnames]{xcolor}
\RequirePackage{tikz}
  \usetikzlibrary{positioning,svg.path}

%    \end{macrocode}
% \begin{macro}{\pgfmolbioset}[2]{The \ometa{module} to which the options apply.}{A \meta{key-value list} which configures the graphs.}
%    \begin{macrocode}
\newcommand\pgfmolbioset[2][]{%
  \def\@tempa{#1}%
  \ifx\@tempa\@empty%
    \pgfqkeys{/pgfmolbio}{#2}%
  \else%
    \pgfqkeys{/pgfmolbio/#1}{#2}%
  \fi%
}

%    \end{macrocode}
% \end{macro}
% We introduce two package-wide keys.
%    \begin{macrocode}
\pgfkeyssetvalue{/pgfmolbio/coordinate unit}{mm}
\pgfkeyssetvalue{/pgfmolbio/coordinate format string}{\letterpercent s\letterpercent s}

%    \end{macrocode}
% Furthermore, we define two scratch token registers. Strictly speaking, the two conditionals belong to the \module{convert} module, but all modules need to know them.
%    \begin{macrocode}
\newtoks\@pmb@toksa
\newtoks\@pmb@toksb
\newif\ifpmb@con@includedescription
\newif\ifpmb@con@outputtikzcode

%    \end{macrocode}
% \begin{macro}{\pmbprotocolsizes}[2]{$x$-coordinate.}{$y$-coordinate.}
% An improved version of |\pgf@protocolsizes| that accepts coordinate calculations.
%    \begin{macrocode}
\def\pmbprotocolsizes#1#2{%
  \pgfpoint{#1}{#2}%
  \pgf@protocolsizes{\pgf@x}{\pgf@y}%
}

%    \end{macrocode}
% \end{macro}
% Finally, we load the modules requested by the user.
%    \begin{macrocode}
\ifpmb@loadmodule@chromatogram
  \input{pgfmolbio.chromatogram.tex}
\fi
\ifpmb@loadmodule@domains
  \input{pgfmolbio.domains.tex}
\fi
\ifpmb@loadmodule@convert
  \input{pgfmolbio.convert.tex}
\fi
%    \end{macrocode}
%
% \iffalse
%</pgfmolbio-tex>
%<*pgfmolbio-lua>
% \fi
% 
% 
% \section{\texorpdfstring{\file{pgfmolbio.lua}}{pgfmolbio.lua}}
% \label{sec:DocPkgLua}
% 
% \def\ydoclistingssettings{\lstset{style=lua-doc}}\setcounter{lstnumber}{1}
% Identification of the Lua module.
%    \begin{macrocode}
if luatexbase then
  luatexbase.provides_module({
    name          = "pgfmolbio",
    version       = 0.2,
    date          = "2012/10/01",
    description   = "Molecular biology graphs wit LuaLaTeX",
    author        = "Wolfgang Skala",
    copyright     = "Wolfgang Skala",
    license       = "LPPL",
  })
end

%    \end{macrocode}
% §setCoordinateFormat§ sets the output format of §dimToString§ (see below). Both its parameters §unit§ and §fmtString§ are strings, which correspond to the values of \opt{coordinate unit} and \opt{coordinate format string}.
%    \begin{macrocode}
local coordUnit, coordFmtStr

function setCoordinateFormat(unit, fmtString)
  coordUnit = unit
  coordFmtStr = fmtString
end

%    \end{macrocode}
% §stringToDim§ converts a string describing a \TeX\ dimension to a number corresponding to scaled points. §dimToString§ converts a dimension in scaled points to a string, formatting it according to the values of the local variables §coordUnit§ and §coordFmtString§.
%    \begin{macrocode}
function stringToDim(x)
  if type(x) == "string" then
    return dimen(x)[1]
  end
end

function dimToString(x)
  return number.todimen(x, coordUnit, coordFmtStr)
end

%    \end{macrocode}
% §getRange§ extracts a variable number of strings from §rangeInput§ by applying the regular expressions in the table §matchStrings§, which derives from the varargs. §rangeInput§ contains the values of any of the \opt{... range} keys.
%    \begin{macrocode}
function getRange(rangeInput, ...)
  if type(rangeInput) ~= "string" then return end
  local result = {}
  local matchStrings = table.pack(...)
  for i = 1, matchStrings.n do
    if type(matchStrings[i]) == "string" then
      table.insert(result, rangeInput:match(matchStrings[i]))
    end
  end
  return unpack(result)
end

%    \end{macrocode}
% §packageWarning§ and §packageError§ throw \TeX\ warnings and errors, respectively. §packageError§ also sets the global variable §errorCatched§ to §true§. Some Lua functions check the value of this variable and terminate if an error has occurred.
%    \begin{macrocode}
function packageWarning(message)
  tex.sprint("\\PackageWarning{pgfmolbio}{" .. message .. "}")
end

function packageError(message)
  tex.error("Package pgfmolbio Error: " .. message)
  errorCatched = true
end

errorCatched = false

%    \end{macrocode}
% We extend the §string§ table by the function §string.trim§, which removes leading and trailing spaces.
%    \begin{macrocode}
if not string.trim then
  string.trim = function(self)
    return self:match("^%s*(.-)%s*$")
  end
end

%    \end{macrocode}
% §outputFileId§ is a counter to enumerate several output files by the \module{convert} module.
%    \begin{macrocode}
outputFileId = 0
%    \end{macrocode}
% \iffalse
%</pgfmolbio-lua>
%<*pmb-chr-tex>
% \fi
%
% \section{\texorpdfstring{\file{pgfmolbio.chromatogram.tex}}{pgfmolbio.chromatogram.tex}}
% \label{sec:DocChrTex}
%
% \def\ydoclistingssettings{\lstset{style=latex-doc}}\setcounter{lstnumber}{1}
% Since the Lua script of the \module{chromatogram} module does the bulk of the work, we can keep the \TeX\ file relatively short.
% 
%    \begin{macrocode}
\ifluatex
  \RequireLuaModule{pgfmolbio.chromatogram}
\fi

%    \end{macrocode}
% We define five custom colors for the traces and probability indicators (see Table~\ref{tab:pmbColors}).
%    \begin{macrocode}
\definecolor{pmbTraceGreen}{RGB}{34,114,46}
\definecolor{pmbTraceBlue}{RGB}{48,37,199}
\definecolor{pmbTraceBlack}{RGB}{0,0,0}
\definecolor{pmbTraceRed}{RGB}{191,27,27}
\definecolor{pmbTraceYellow}{RGB}{233,230,0}

%    \end{macrocode}
% \begin{macro}{\@pmb@chr@keydef}[2]{\meta{key} name}{default \meta{value}}
% Most of the keys simply store their value. |\@pmb@chr@keydef| simplifies the declaration of such keys by calling |\pgfkeyssetvalue| with the appropriate path, \meta{key} and \meta{value}.
%    \begin{macrocode}
\def\@pmb@chr@keydef#1#2{%
  \pgfkeyssetvalue{/pgfmolbio/chromatogram/#1}{#2}%
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@pmb@chr@stylekeydef}[2]{\meta{key} name}{default \meta{value}}
% This macro initializes a style \meta{key} with a \meta{value}.
%    \begin{macrocode}
\def\@pmb@chr@stylekeydef#1#2{%
  \pgfkeys{/pgfmolbio/chromatogram/#1/.style={#2}}%
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@pmb@chr@getkey}[1]{\meta{key} name}
% |\@pmb@chr@getkey| retrieves the value stored by the \meta{key}.
%    \begin{macrocode}
\def\@pmb@chr@getkey#1{%
  \pgfkeysvalueof{/pgfmolbio/chromatogram/#1}%
}

%    \end{macrocode}
% \end{macro}
% After providing these auxiliary macros, we define all keys of the \module{chromatogram} module.
%    \begin{macrocode}
\@pmb@chr@keydef{sample range}{1-500 step 1}

\@pmb@chr@keydef{x unit}{0.2mm}
\@pmb@chr@keydef{y unit}{0.01mm}
\@pmb@chr@keydef{samples per line}{500}
\@pmb@chr@keydef{baseline skip}{3cm}
\@pmb@chr@stylekeydef{canvas style}{draw=none, fill=none}
\@pmb@chr@keydef{canvas height}{2cm}

\@pmb@chr@stylekeydef{trace A style}{pmbTraceGreen}
\@pmb@chr@stylekeydef{trace C style}{pmbTraceBlue}
\@pmb@chr@stylekeydef{trace G style}{pmbTraceBlack}
\@pmb@chr@stylekeydef{trace T style}{pmbTraceRed}
\pgfmolbioset[chromatogram]{%
  trace style/.code=\pgfkeysalso{
    trace A style/.style={#1},
    trace C style/.style={#1},
    trace G style/.style={#1},
    trace T style/.style={#1}
  }%
}
\@pmb@chr@keydef{traces drawn}{}

\@pmb@chr@stylekeydef{tick A style}{thin, pmbTraceGreen}
\@pmb@chr@stylekeydef{tick C style}{thin, pmbTraceBlue}
\@pmb@chr@stylekeydef{tick G style}{thin, pmbTraceBlack}
\@pmb@chr@stylekeydef{tick T style}{thin, pmbTraceRed}
\pgfmolbioset[chromatogram]{%
  tick style/.code=\pgfkeysalso{
    tick A style/.style={#1},
    tick C style/.style={#1},
    tick G style/.style={#1},
    tick T style/.style={#1}
  }%
}
\@pmb@chr@keydef{tick length}{1mm}
\@pmb@chr@keydef{ticks drawn}{}

\@pmb@chr@keydef{base label A text}{\strut A}
\@pmb@chr@keydef{base label C text}{\strut C}
\@pmb@chr@keydef{base label G text}{\strut G}
\@pmb@chr@keydef{base label T text}{\strut T}
\@pmb@chr@stylekeydef{base label A style}%
  {below=4pt, font=\ttfamily\footnotesize, pmbTraceGreen}
\@pmb@chr@stylekeydef{base label C style}%
  {below=4pt, font=\ttfamily\footnotesize, pmbTraceBlue}
\@pmb@chr@stylekeydef{base label G style}%
  {below=4pt, font=\ttfamily\footnotesize, pmbTraceBlack}
\@pmb@chr@stylekeydef{base label T style}%
  {below=4pt, font=\ttfamily\footnotesize, pmbTraceRed}
\pgfmolbioset[chromatogram]{%
  base label style/.code=\pgfkeysalso{
    base label A style/.style={#1},
    base label C style/.style={#1},
    base label G style/.style={#1},
    base label T style/.style={#1}
  }%
}
\@pmb@chr@keydef{base labels drawn}{}

\newif\ifpmb@chr@showbasenumbers
\pgfmolbioset[chromatogram]{%
  show base numbers/.is if=pmb@chr@showbasenumbers,
  show base numbers
}
\@pmb@chr@stylekeydef{base number style}%
  {pmbTraceBlack, below=-3pt, font=\sffamily\tiny}
\@pmb@chr@keydef{base number range}{auto-auto step 10}

\@pmb@chr@keydef{probability distance}{0.8cm}
\@pmb@chr@keydef{probabilities drawn}{}
\@pmb@chr@keydef{probability style function}{nil}

\pgfmolbioset[chromatogram]{
  bases drawn/.code=\pgfkeysalso{
    traces drawn=#1,
    ticks drawn=#1,
    base labels drawn=#1,
    probabilities drawn=#1
  },
  bases drawn=ACGT
}

%    \end{macrocode}
% If \pkg{pgfmolbio} is used with a \TeX\ engine that does not support Lua, the package ends here.
%    \begin{macrocode}
\ifluatex\else\expandafter\endinput\fi

%    \end{macrocode}
% \begin{macro}{\pmbchromatogram}[2]{A \ometa{key-value list} that configures the chromatogram.}{The name of an \meta{scf file}.}
% If |\pmbchromatogram| appears outside of a |tikzpicture|, we implicitly start this environment, otherwise we begin a new group. ``Within a |tikzpicture|'' means that |\useasboundingbox| is defined.
%    \begin{macrocode}
\newif\ifpmb@chr@tikzpicture

\newcommand\pmbchromatogram[2][]{%
  \@ifundefined{useasboundingbox}%
    {\pmb@chr@tikzpicturefalse\begin{tikzpicture}}%
    {\pmb@chr@tikzpicturetrue\begingroup}%
%    \end{macrocode}
% Of course, we consider the \ometa{key-value list} before drawing the chromatogram.
%    \begin{macrocode}
  \pgfmolbioset[chromatogram]{#1}%
%    \end{macrocode}
% We generate a new §Chromatogram§ object and invoke several Lua functions: (1) §readScfFile§ reads the given \meta{scf file} (section~\ref{ssc:DocChrLuaReadScfFile}). (2) §setParameters§ passes the values stored by the keys to the Lua script. Note that this function is called twice, since §baseNumberRange§ requires that §sampleRange§ has been already set, and the implementation of §setParameters§ does not ensure this (section~\ref{ssc:DocChrLuaSetParameters}). (3) §pgfmolbio.setCoordinateFormat§ sets the coordinate output format (section~\ref{sec:DocPkgLua}).
%    \begin{macrocode}
  \directlua{
    pmbChromatogram = pgfmolbio.chromatogram.Chromatogram:new()
    pmbChromatogram:readScfFile("#2")
    pmbChromatogram:setParameters{
      sampleRange = "\@pmb@chr@getkey{sample range}",
      xUnit = "\@pmb@chr@getkey{x unit}",
      yUnit = "\@pmb@chr@getkey{y unit}",
      samplesPerLine = "\@pmb@chr@getkey{samples per line}",
      baselineSkip = "\@pmb@chr@getkey{baseline skip}",
      canvasHeight = "\@pmb@chr@getkey{canvas height}",
      tracesDrawn = "\@pmb@chr@getkey{traces drawn}",
      tickLength = "\@pmb@chr@getkey{tick length}",
      ticksDrawn = "\@pmb@chr@getkey{ticks drawn}",
      baseLabelsDrawn = "\@pmb@chr@getkey{base labels drawn}",
      showBaseNumbers = "\ifpmb@chr@showbasenumbers true\else false\fi",
      probDistance = "\@pmb@chr@getkey{probability distance}",
      probabilitiesDrawn = "\@pmb@chr@getkey{probabilities drawn}",
      probStyle = \@pmb@chr@getkey{probability style function}
    }
    pmbChromatogram:setParameters{
      baseNumberRange = "\@pmb@chr@getkey{base number range}",
    }
    pgfmolbio.setCoordinateFormat(
      "\pgfkeysvalueof{/pgfmolbio/coordinate unit}",
      "\pgfkeysvalueof{/pgfmolbio/coordinate format string}"
    )
%    \end{macrocode}
% If the \module{convert} module is loaded, we open the appropriate output file, change §tex.sprint§ so that the function writes to this file and then call §printTikzChromatogram§. Without the \module{convert} module, §printTikzChromatogram§ simply returns the drawing commands for the chromatogram to the \TeX\ input stream (section~\ref{ssc:DocChrLuaPrint}).
%    \begin{macrocode}
    \ifpmb@loadmodule@convert
      local filename =
        "\pgfkeysvalueof{/pgfmolbio/convert/output file name}"
      if filename == "(auto)" then
        filename = "pmbconverted" .. pgfmolbio.outputFileId
      end
      filename = filename ..
        ".\pgfkeysvalueof{/pgfmolbio/convert/output file extension}"
      outputFile, ioError = io.open(filename, "w")
      if ioError then
        tex.error(ioError)
      end
      tex.sprint = function (a) outputFile:write(a) end
      tex.sprint("\string\\begin{tikzpicture}")
      pmbChromatogram:printTikzChromatogram()
      tex.sprint("\string\n\string\\end{tikzpicture}")
      outputFile:close()
      pgfmolbio.outputFileId = pgfmolbio.outputFileId + 1
    \else
      pmbChromatogram:printTikzChromatogram()
    \fi
  }%
%    \end{macrocode}
% At the end of |\pmbchromatogram|, we either close the |tikzpicture| or the group, depending on how we started.
%    \begin{macrocode}
  \ifpmb@chr@tikzpicture\endgroup\else\end{tikzpicture}\fi%
}
%    \end{macrocode}
% \end{macro}
%
% \iffalse
%</pmb-chr-tex>
%<*pmb-chr-lua>
% \fi
%
% \section{\texorpdfstring{\file{pgfmolbio.chromatogram.lua}}{pgfmolbio.chromatogram.lua}}
% \label{sec:DocChrLua}
%
% \def\ydoclistingssettings{\lstset{style=lua-doc}}\setcounter{lstnumber}{1}
% This Lua script is the true workhorse of the \module{chromatogram} module. Remember that the documentation for the Staden package\footnote{\url{http://staden.sourceforge.net/}} is the definite source for information on the \file{scf} file format.
%    \begin{macrocode}
if luatexbase then
  luatexbase.provides_module{
    name          = "pgfmolbio.chromatogram",
    version       = 0.2,
    date          = "2012/10/01",
    description   = "DNA sequencing chromatograms",
    author        = "Wolfgang Skala",
    copyright     = "Wolfgang Skala",
    license       = "LPPL",
  }
end

%    \end{macrocode}
%
% \subsection{Module-Wide Variables and Auxiliary Functions}
% \label{ssc:DocChrLuaAuxiliaryFunctions}
%
% \begin{itemize}
% 	\item §ALL_BASES§: A table of four indexed string fields, which represent the nucleotide single-letter abbreviations.
% 	\item §PGFKEYS_PATH§: A string that contains the \pkg{pgfkeys} path for \module{chromatogram} keys.
% \end{itemize}
%    \begin{macrocode}
local ALL_BASES = {"A", "C", "G", "T"}
local PGFKEYS_PATH = "/pgfmolbio/chromatogram/"

%    \end{macrocode}
% These local functions point to functions in \file{pgfmolbio.lua} (section~\ref{sec:DocPkgLua}).
%    \begin{macrocode}
local stringToDim = pgfmolbio.stringToDim
local dimToString = pgfmolbio.dimToString
local packageError = pgfmolbio.packageError
local packageWarning = pgfmolbio.packageWarning
local getRange = pgfmolbio.getRange

%    \end{macrocode}
% §stdProbStyle§ is the default \opt{probability style function}. It returns a string representing an optional argument of |\draw|. Depending on the value of §prob§, the probability rule thus drawn is colored black, red, yellow or green for quality scores $< 10$, $< 20$, $< 30$ or $\geq 30$, respectively (see also section~\ref{sec:ChrProbabilities}).
%    \begin{macrocode}
local function stdProbStyle(prob)
  local color = ""
  if prob >= 0 and prob < 10 then
    color = "black"
  elseif prob >= 10 and prob < 20 then
    color = "pmbTraceRed"
  elseif prob >= 20 and prob < 30 then
    color = "pmbTraceYellow"
  else
    color = "pmbTraceGreen"
  end
  return "ultra thick, " .. color
end

%    \end{macrocode}
% §findBasesInStr§ searches for nucleotide single-letter abbreviations in its string argument. It returns a table of zero to four indexed string fields (one field per character found, which contains that letter).
%    \begin{macrocode}
local function findBasesInStr(target)
  if not target then return end
  local result = {}
  for _, v in ipairs(ALL_BASES) do
    if target:upper():find(v) then
      table.insert(result, v)
    end
  end
  return result
end

%    \end{macrocode}
% §readInt§ reads §n§ bytes from a §file§, starting at §offset§ or at the current position if §offset§ is §nil§. By assuming big-endian byte order, the byte sequence is converted to a number and returned.
%    \begin{macrocode}
local function readInt(file, n, offset)
  if offset then file:seek("set", offset) end
  local result = 0
  for i = 1, n do
    result = result * 0x100 + file:read(1):byte()
  end
  return result
end

%    \end{macrocode}
% 
% \subsection{The \texorpdfstring{\texttt{Chromatogram}}{Chromatogram} Class}
% \label{ssc:DocChrLuaClass}
% 
% The §Chromatogram§ class (table) represents a single \file{scf} chromatogram. The constructor §Chromatogram:new§ returns a new instance and initializes its variables, which store the values of \module{chromatogram} keys. Most variables are self-explanatory, since their name is similar to their corresponding key.
%    \begin{macrocode}
Chromatogram = {}

function Chromatogram:new()
  newChromatogram = {
    sampleMin = 1,
    sampleMax = 500,
    sampleStep = 1,
    peakMin = -1,
    peakMax = -1,
    xUnit = stringToDim("0.2mm"),
    yUnit = stringToDim("0.01mm"),
    samplesPerLine = 500,
    baselineSkip = stringToDim("3cm"),
    canvasHeight = stringToDim("2cm"),
    traceStyle = {
      A = PGFKEYS_PATH .. "trace A style",
      C = PGFKEYS_PATH .. "trace C style",
      G = PGFKEYS_PATH .. "trace G style",
      T = PGFKEYS_PATH .. "trace T style"
    },
    tickStyle = {
      A = PGFKEYS_PATH .. "tick A style",
      C = PGFKEYS_PATH .. "tick C style",
      G = PGFKEYS_PATH .. "tick G style",
      T = PGFKEYS_PATH .. "tick T style"
    },
    tickLength = stringToDim("1mm"),
    baseLabelText = {
      A = "\\pgfkeysvalueof{" .. PGFKEYS_PATH .. "base label A text}",
      C = "\\pgfkeysvalueof{" .. PGFKEYS_PATH .. "base label C text}",
      G = "\\pgfkeysvalueof{" .. PGFKEYS_PATH .. "base label G text}",
      T = "\\pgfkeysvalueof{" .. PGFKEYS_PATH .. "base label T text}"
    },
    baseLabelStyle = {
      A = PGFKEYS_PATH .. "base label A style",
      C = PGFKEYS_PATH .. "base label C style",
      G = PGFKEYS_PATH .. "base label G style",
      T = PGFKEYS_PATH .. "base label T style"
    },
    showBaseNumbers = true,
    baseNumberMin = -1,
    baseNumberMax = -1,
    baseNumberStep = 10,
    probDistance = stringToDim("0.8cm"),
    probStyle = stdProbStyle,
    tracesDrawn = ALL_BASES,
    ticksDrawn = "ACGT",
    baseLabelsDrawn = "ACGT",
    probabilitiesDrawn = "ACGT",
  }
  setmetatable(newChromatogram, self)
  self.__index = self
  return newChromatogram
end

%    \end{macrocode}
% §getMinMaxProbability§ returns the minimum and maximum probability value in the current chromatogram.
%    \begin{macrocode}
function Chromatogram:getMinMaxProbability()
  local minProb = 0
  local maxProb = 0
  for _, currPeak in ipairs(self.selectedPeaks) do
    for __, currProb in pairs(currPeak.prob) do
      if currProb > maxProb then maxProb = currProb end
      if currProb < minProb then minProb = currProb end
    end
  end
  return minProb, maxProb
end

%    \end{macrocode}
% §getSampleAndPeakIndex§ returns the sample (§sampleId§) and peak index (§peakId§) that correspond to §baseIndex§. If §baseIndex§ is a number, the function simply returns it as sample index. However, if §baseIndex§ is a string of the form §"base§ \meta{number}§"§ (as in a valid value for the \opt{sample range} key), the function returns the offset of the \meta{number}-th peak. §isLowerLimit§ must be §true§ if the function should return the indices of the lower end of a range.
%    \begin{macrocode}
function Chromatogram:getSampleAndPeakIndex(baseIndex, isLowerLimit)
  local sampleId, peakId
  
  sampleId = tonumber(baseIndex)
  if sampleId then
    for i, v in ipairs(self.peaks) do
      if isLowerLimit then
        if v.offset >= sampleId then
          peakId = i
          break
        end
      else
        if v.offset == sampleId then
          peakId = i
          break
        elseif v.offset > sampleId then
          peakId = i - 1
          break
        end
      end
    end
  else
    peakId = tonumber(baseIndex:match("base%s*(%d+)"))
    if peakId then
      sampleId = self.peaks[peakId].offset
    end
  end
  return sampleId, peakId
end

%    \end{macrocode}
%
% \subsection{Read the \texorpdfstring{\file{scf}}{scf} File}
% \label{ssc:DocChrLuaReadScfFile}
% 
% §Chromatogram:readScfFile§ introduces three further fields to §Chromatogram§:
% \begin{itemize}
% 	\item §header§: A table of 14 named number fields that save the information in the \file{scf} header.
% 	\item §samples§: A table of four named subtables §A§, §C§, §G§, §T§. Each subtable contains §header.samplesNumber§ indexed number fields that represent the fluorescence intensities along a trace.
% 	\item §peaks§: A table of §header.basesNumber§ indexed subtables which in turn contain three named fields:
% 		\begin{itemize}
% 			\item §offset§: A number indicating the offset of the current peak.
% 			\item §prob§: A table of four named number fields §A§, §C§, §G§, §T§. These numbers store the probability that the current peak is one of the four bases.
% 			\item §base§: A string that states the base represented by the current peak.
% 		\end{itemize}
% \end{itemize}
% 
% §Chromatogram:readScfFile§ checks whether the requested \file{scf} file ``§filename§'' corresponds to the most recently opened one (via §lastScfFile§). In this case, the variables §peaks§ and §samples§ already contain the relevant data, so we can refrain from re-reading the file. Otherwise, the program tries to open and evaluate the specified file, raising an error on failure.
%    \begin{macrocode}
function Chromatogram:readScfFile(filename)
  if filename ~= self.lastScfFile then
    self.lastScfFile = filename
    local scfFile, errorMsg = io.open(filename, "rb")
    if not scfFile then packageError(errorMsg) end

    self.samples = {A = {}, C = {}, G = {}, T = {}}
    self.peaks = {}
%    \end{macrocode}
% The function collects the relevant data from the file. \textit{Firstly}, §header§ saves the information in the file header:
% \begin{itemize}
% 	\item §magicNumber§: Each \file{scf} file must start with the four bytes §2E736366§, which is the string ``§.scf§''. If this sequence is absent, the \module{chromatogram} module raises an error.
% 	\item §samplesNumber§: The number of sample points.
% 	\item §samplesOffset§: The offset of the sample data start.
% 	\item §basesNumber§: The number of recognized bases.
% 	\item §version§: Since the \module{chromatogram} module currently only supports \file{scf} version 3.00 (the string ``§3.00§'' equals §332E3030§), \TeX\ stops with an error message if the file version is different.
% 	\item §sampleSize§: The size of each sample point in bytes.
% \end{itemize}
%    \begin{macrocode}
    self.header = {
      magicNumber = readInt(scfFile, 4, 0),
      samplesNumber = readInt(scfFile, 4),
      samplesOffset = readInt(scfFile, 4),
      basesNumber = readInt(scfFile, 4),
      leftClip = readInt(scfFile, 4),
      rightClip = readInt(scfFile, 4),
      basesOffset = readInt(scfFile, 4),
      comments = readInt(scfFile, 4),
      commentsOffset = readInt(scfFile, 4),
      version = readInt(scfFile, 4),
      sampleSize = readInt(scfFile, 4),
      codeSet = readInt(scfFile, 4),
      privateSize = readInt(scfFile, 4),
      privateOffset = readInt(scfFile, 4)
    }
    if self.header.magicNumber ~= 0x2E736366 then
      packageError(
        "Magic number in scf scfFile '" ..
        self.lastScfFile ..
        "' corrupt!"
      )
    end
    if self.header.version ~= 0x332E3030 then
      packageError(
        "Scf scfFile '" ..
        self.lastScfFile ..
        "' is not version 3.00!"
      )
    end
%    \end{macrocode}
% \textit{Secondly}, §samples§ receives the samples data from the file. Note that the values of the sample points are stored as unsigned integers representing second derivatives (i.\,e., differences between differences between two consecutive sample points). Hence, we convert them back to signed, absolute values.
%    \begin{macrocode}
    scfFile:seek("set", self.header.samplesOffset)
    for baseIndex, baseName in ipairs(ALL_BASES) do
      for i = 1, self.header.samplesNumber do
        self.samples[baseName][i] =
          readInt(scfFile, self.header.sampleSize)
      end

      for _ = 1, 2 do
        local preValue = 0
        for i = 1, self.header.samplesNumber do
          self.samples[baseName][i] = self.samples[baseName][i] + preValue
          if self.samples[baseName][i] > 0xFFFF then
            self.samples[baseName][i] = self.samples[baseName][i] - 0x10000
          end
          preValue = self.samples[baseName][i]
        end
      end
    end
%    \end{macrocode}
% \textit{Finally}, we store the peak information in §peaks§.
%    \begin{macrocode}
    for i = 1, self.header.basesNumber do
      self.peaks[i] = {
        offset = readInt(scfFile, 4),
        prob = {A, C, G, T},
        base
      }
    end

    for i = 1, self.header.basesNumber do
      self.peaks[i].prob.A = readInt(scfFile, 1)
    end

    for i = 1, self.header.basesNumber do
      self.peaks[i].prob.C = readInt(scfFile, 1)
    end

    for i = 1, self.header.basesNumber do
      self.peaks[i].prob.G = readInt(scfFile, 1)
    end

    for i = 1, self.header.basesNumber do
      self.peaks[i].prob.T = readInt(scfFile, 1)
    end

    for i = 1, self.header.basesNumber do
      self.peaks[i].base = string.char(readInt(scfFile, 1))
    end
    
    scfFile:close()
  end
end

%    \end{macrocode}
%
% \subsection{Set Chromatogram Parameters}
% \label{ssc:DocChrLuaSetParameters}
%
% §Chromatogram:setParameters§ passes options from the \module{chromatogram} module to the Lua script. Each field of the table §keyHash§ is named after a §Chromatogram§ attribute and represents a function that receives one string parameter (the value of a \LaTeX\ key). For instance, §keyHash.sampleRange§ extracts the range and step values from the value stored in the \opt{sample range} key.
%    \begin{macrocode}
function Chromatogram:setParameters(newParms)
  local keyHash = {
    sampleRange = function(v)
      local sampleRangeMin, sampleRangeMax, sampleRangeStep =
        getRange(
          v:trim(),
          "^([base]*%s*%d+)%s*%-",
          "%-%s*([base]*%s*%d+)",
          "step%s*(%d+)$"
        )
      self.sampleMin, self.peakMin =
        self:getSampleAndPeakIndex(sampleRangeMin, true)
      self.sampleMax, self.peakMax =
        self:getSampleAndPeakIndex(sampleRangeMax, false)
      if self.sampleMin >= self.sampleMax then
        packageError("Sample range is smaller than 1.")
      end
      self.sampleStep = sampleRangeStep or self.sampleStep
    end,
    xUnit = stringToDim,
    yUnit = stringToDim,
    samplesPerLine = tonumber,
    baselineSkip = stringToDim,
    canvasHeight = stringToDim,
    tickLength = stringToDim,
    showBaseNumbers = function(v)
      if v == "true" then return true else return false end
    end,
    baseNumberRange = function(v)
      local baseNumberRangeMin, baseNumberRangeMax, baseNumberRangeStep =
        getRange(
          v:trim(),
          "^([auto%d]*)%s+%-",
          "%-%s+([auto%d]*$)"
        )
      if tonumber(baseNumberRangeMin) then
        self.baseNumberMin = tonumber(baseNumberRangeMin)
      else
        self.baseNumberMin = self.peakMin
      end
      if tonumber(baseNumberRangeMax) then
        self.baseNumberMax = tonumber(baseNumberRangeMax)
      else
        self.baseNumberMax = self.peakMax
      end
      if self.baseNumberMin >= self.baseNumberMax then
        packageError("Base number range is smaller than 1.")
      end
      if self.baseNumberMin < self.peakMin then
        self.baseNumberMin = self.peakMin
        packageWarning("Lower base number range is smaller than lower sample range. It was adjusted to " .. self.baseNumberMin .. ".")
      end
      if self.baseNumberMax > self.peakMax then
        self.baseNumberMax = self.peakMax
        packageWarning("Upper base number range exceeds upper sample range. It was adjusted to " .. self.baseNumberMax .. ".")
      end
      self.baseNumberStep = tonumber(baseNumberRangeStep)
        or self.baseNumberStep
    end,
    probDistance = stringToDim,
    probStyle = function(v) return v end,
    tracesDrawn = findBasesInStr,
    ticksDrawn = function(v) return v end,
    baseLabelsDrawn = function(v) return v end,
    probabilitiesDrawn = function(v) return v end,
    probStyle = function(v) return v end
  }
%    \end{macrocode}
% We iterate over all fields in the argument of §setParameters§. If a field of the same name exists in §keyHash§, we call this field with the value of the corresponding field in §newParms§ as parameter.
%    \begin{macrocode}
  for key, value in pairs(newParms) do
    if keyHash[key] then
      self[key] = keyHash[key](value)
    end
  end
end

%    \end{macrocode}
% 
% \subsection{Print the Chromatogram}
% \label{ssc:DocChrLuaPrint}
%
% §Chromatogram:printTikzChromatogram§ writes all commands that draw the chromatogram to the \TeX\ input stream (via §tex.sprint§), but only if no error has occurred previously.
%    \begin{macrocode}
function Chromatogram:printTikzChromatogram()
  if pgfmolbio.errorCatched then return end
%    \end{macrocode}
% \paragraph{(1) Select peaks to draw} In order to simplify the drawing operations, we select the peaks that appear in the final output and store information on them in §selectedPeaks§. §selectedPeaks§ is a table of zero to §header.basesNumber§ indexed subtables. It is similar to §peaks§ but only describes the peaks in the displayed part of the chromatogram, which is selected by the \opt{samples range} key. Each subtable of §selectedPeaks§ consists of the following five named fields:
% 	\begin{itemize}
% 		\item §offset§: A number indicating the offset of the current peak in ``transformed'' coordinates (i.\,e., the $x$-coordinate of the first sample point shown equals 1).
% 		\item §base§: See §peaks.base§ (section~\ref{ssc:DocChrLuaReadScfFile}).
% 		\item §prob§: See §peaks.prob§ (section~\ref{ssc:DocChrLuaReadScfFile}).
% 		\item §baseIndex§: A number that stores the index of the current peak. The first detected peak in the chromatogram has index~1.
% 		\item §probXRight§: A number corresponding to the right $x$-coordinate of the probability indicator.
% 	\end{itemize}
%    \begin{macrocode}
  self.selectedPeaks = {}
  local tIndex = 1
  for rPeakIndex, currPeak in ipairs(self.peaks) do
    if currPeak.offset >= self.sampleMin
        and currPeak.offset <= self.sampleMax then
      self.selectedPeaks[tIndex] = {
        offset = currPeak.offset + 1 - self.sampleMin,
        base = currPeak.base,
        prob = currPeak.prob,
        baseIndex = rPeakIndex,
        probXRight = self.sampleMax + 1 - self.sampleMin
      }
%    \end{macrocode}
% The right $x$-coordinate of the probability indicator (§probXRight§) is the mean between the offsets of the adjacent peaks. For the last peak, §probXRight§ equals the largest transformed $x$-coordinate.
%    \begin{macrocode}
      if tIndex > 1 then
        self.selectedPeaks[tIndex-1].probXRight =
          (self.selectedPeaks[tIndex-1].offset
          + self.selectedPeaks[tIndex].offset) / 2
      end
      tIndex = tIndex + 1
    end
  end
  
%    \end{macrocode}
% Furthermore, we adjust §baseNumberMin§ and §baseNumberMax§ if any peak was detected in the displayed part of the chromatogram. The value §-1§, which indicates the keyword |auto|, is replaced by the index of the first or last peak, respectively.
%    \begin{macrocode}
  if tIndex > 1 then
    if self.baseNumberMin == -1 then
      self.baseNumberMin = self.selectedPeaks[1].baseIndex
    end
    if self.baseNumberMax == -1 then
      self.baseNumberMax = self.selectedPeaks[tIndex-1].baseIndex
    end
  end
  
%    \end{macrocode}
% \paragraph{(2) Canvas} For each line, we draw a rectangle in \opt{canvas style} whose left border coincides with the $y$-axis.\\
% §yLower§, §yUpper§, §xRight§: rectangle coordinates;\\
% §currLine§: current line, starting from 0;\\
% §samplesLeft§: sample points left to draw after the end of the current line.
%    \begin{macrocode}
  local samplesLeft = self.sampleMax - self.sampleMin + 1
  local currLine = 0
  while samplesLeft > 0 do
    local yLower = -currLine * self.baselineSkip
    local yUpper = -currLine * self.baselineSkip + self.canvasHeight
    local xRight =
      (math.min(self.samplesPerLine, samplesLeft) - 1) * self.xUnit
    tex.sprint(
      "\n\t\\draw [" .. PGFKEYS_PATH .. "canvas style] (" ..
      dimToString(0) ..
      ", " ..
      dimToString(yLower) ..
      ") rectangle (" ..
      dimToString(xRight) ..
      ", " ..
      dimToString(yUpper) ..
      ");"
    )
    samplesLeft = samplesLeft - self.samplesPerLine
    currLine = currLine + 1
  end
  
%    \end{macrocode}
% \paragraph{(3) Traces} The traces in §tracesDrawn§ are drawn sequentially.\\
% §currSampleIndex§: original $x$-coordinate of a sample point;\\
% §sampleX§: transformed $x$-coordinate of a sample point, starting at 1;\\
% §x§ and §y§: ``real'' coordinates (in scaled points) of a sample point;\\
% §currLine§: current line, starting at 0;\\
% §firstPointInLine§: boolean that indicates if the current sample point is the first in the line.
%    \begin{macrocode}
  for _, baseName in ipairs(self.tracesDrawn) do
    tex.sprint("\n\t\\draw [" .. self.traceStyle[baseName] .. "] ")
    local currSampleIndex = self.sampleMin
    local sampleX = 1
    local x = 0
    local y = 0
    local currLine = 0
    local firstPointInLine = true
    
%    \end{macrocode}
% We iterate over each sample point. As long as the current sample point is within the selected range, we calculate the real coordinates of the sample point; add the lineto operator |--| if at least one sample point has already appeared in the current line; and write the point to the \TeX\ input stream.
%    \begin{macrocode}
    while currSampleIndex <= self.sampleMax do
      x = ((sampleX - 1) % self.samplesPerLine) * self.xUnit
      y = self.samples[baseName][currSampleIndex] * self.yUnit
        - currLine * self.baselineSkip
      if sampleX % self.sampleStep == 0 then
        if not firstPointInLine then
          tex.sprint(" -- ")
        else
          firstPointInLine = false
        end
        tex.sprint(
          "(" ..
          dimToString(x) ..
          ", " ..
          dimToString(y) ..
          ")"
        )
      end
%    \end{macrocode}
% Besides, we add line breaks at the appropriate positions.
%    \begin{macrocode}
      if sampleX ~= self.sampleMax + 1 - self.sampleMin then
        if sampleX >= (currLine + 1) * self.samplesPerLine then
          currLine = currLine + 1
          tex.sprint(";\n\t\\draw [" .. self.traceStyle[baseName] .. "] ")
          firstPointInLine = true
        end
      else
        tex.sprint(";")
      end
    sampleX = sampleX + 1
    currSampleIndex = currSampleIndex + 1
    end
  end
  
%    \end{macrocode}
% \paragraph{(4) Annotations} We iterate over each selected peak and start by finding the line in which the first peak resides.\\
% §currLine§: current line, starting at 0;\\
% §lastProbX§: right $x$-coordinate of the probability rule of the last peak;\\
% §probRemainder§: string that draws the remainder of a probability indicator following a line break;\\
% §x§, §yUpper§, §yLower§: ``real'' tick coordinates;\\
% §tickOperation§: string that equals either \TikZ's moveto or lineto operation, depending on whether the current peak should be marked with a tick.
%    \begin{macrocode}
  local currLine = 0
  local lastProbX = 1
  local probRemainder = false

  for _, currPeak in ipairs(self.selectedPeaks) do
    while currPeak.offset > (currLine + 1) * self.samplesPerLine do
      currLine = currLine + 1
    end

    local x = ((currPeak.offset - 1) % self.samplesPerLine) * self.xUnit
    local yUpper = -currLine * self.baselineSkip
    local yLower = -currLine * self.baselineSkip - self.tickLength
    local tickOperation = ""
    if self.ticksDrawn:upper():find(currPeak.base) then
      tickOperation = "--"
    end
    
%    \end{macrocode}
% \paragraph{(4a) Ticks and labels} Having calculated all coordinates, we draw the tick and the base label, given the latter has been specified by \opt{base labels drawn}.
%    \begin{macrocode}
    tex.sprint(
      "\n\t\\draw [" ..
      self.tickStyle[currPeak.base] ..
      "] (" ..
      dimToString(x) ..
      ", " ..
      dimToString(yUpper) ..
      ") " ..
      tickOperation ..
      " (" ..
      dimToString(x) ..
      ", " ..
      dimToString(yLower) ..
      ")"
    )
    if self.baseLabelsDrawn:upper():find(currPeak.base) then
      tex.sprint(
        " node [" ..
        self.baseLabelStyle[currPeak.base] ..
        "] {" ..
        self.baseLabelText[currPeak.base] ..
        "}"
      )
    end

%    \end{macrocode}
% \paragraph{(4b) Base numbers} If \opt{show base numbers} is true and the current base number is within the interval given by \opt{base number range}, a base number is printed.
%    \begin{macrocode}
    if self.showBaseNumbers
        and currPeak.baseIndex >= self.baseNumberMin
        and currPeak.baseIndex <= self.baseNumberMax
        and (currPeak.baseIndex - self.baseNumberMin)
          % self.baseNumberStep == 0 then
      tex.sprint(
        " node [" ..
        PGFKEYS_PATH ..
        "base number style] {\\strut " ..
        currPeak.baseIndex ..
        "}"
      )
    end
    tex.sprint(";")
    
%    \end{macrocode}
% \paragraph{(4c) Probabilities} First, we draw the remainder of the last probability rule. Such a remainder has been stored in §probRemainder§ if the last rule had protruded into the right margin (see below). Furthermore, we determine if a probability rule should appear beneath the current peak. 
%    \begin{macrocode}
    if probRemainder then
      tex.sprint(probRemainder)
      probRemainder = false
    end
    local drawCurrProb =
      self.probabilitiesDrawn:upper():find(currPeak.base)
%    \end{macrocode}
% Now comes the tricky part. Whenever we choose to paint a probability rule, we may envision three scenarios. \textit{Firstly}, the probability rule starts in the left margin of the current line (i.\,e., §xLeft§ is negative). This means that the part protruding into the left margin must instead appear at the end of the last line. Therefore, we calculate the coordinates of this part (storing them in §xLeftPrev§, §xRightPrev§ and §yPrev§) and draw the segment. Since the remainder of the rule necessarily starts at the left border of the current line, we set §xLeft§ to zero.
%    \begin{macrocode}
    local xLeft = lastProbX - 1 - currLine * self.samplesPerLine
    if xLeft < 0 then
      local xLeftPrev = (self.samplesPerLine + xLeft) * self.xUnit
      local xRightPrev = (self.samplesPerLine - 1) * self.xUnit
      local yPrev = -(currLine-1) * self.baselineSkip - self.probDistance
      if drawCurrProb then
        tex.sprint(
          "\n\t\\draw [" ..
          self.probStyle(currPeak.prob[currPeak.base]) ..
          "] (" ..
          dimToString(xLeftPrev) ..
          ", " ..
          dimToString(yPrev) ..
          ") -- (" ..
          dimToString(xRightPrev) ..
          ", " ..
          dimToString(yPrev) ..
          ");"
        )
      end
      xLeft = 0
    else
      xLeft = xLeft * self.xUnit
    end
    
%    \end{macrocode}
% \textit{Secondly}, the probability rule ends in the right margin of the current line (i.\,e., §xRight§ at least equals §samplesPerLine§). This means that the part protruding into the right margin must instead appear at the start of the following line. Therefore, we calculate the coordinates of this part (storing them in §xRightNext§ and §yNext§) and save the drawing command in §probRemainder§ (whose contents were printed above). Since the remainder of the rule necessarily ends at the right border of the current line, we set §xRight§ to this coordinate.
%    \begin{macrocode}
    local xRight = currPeak.probXRight - 1 - currLine * self.samplesPerLine
    if xRight >= self.samplesPerLine then
      if drawCurrProb then
        local xRightNext = (xRight - self.samplesPerLine) * self.xUnit
        local yNext = -(currLine+1) * self.baselineSkip - self.probDistance
        probRemainder =
          "\n\t\\draw [" ..
          self.probStyle(currPeak.prob[currPeak.base]) ..
          "] (" ..
          dimToString(0) ..
          ", " ..
          dimToString(yNext) ..
          ") -- (" ..
          dimToString(xRightNext) ..
          ", " ..
          dimToString(yNext) ..
          ");"
      end
      xRight = (self.samplesPerLine - 1) * self.xUnit
    else
      xRight = xRight * self.xUnit
    end
    
%    \end{macrocode}
% \textit{Thirdly}, the probability rule starts and ends within the boundaries of the current line. In this lucky case, the $y$-coordinate is the only one missing, since we previously calculated §xLeft§ (case~1) and §xRight§ (case~2). Drawing of the probability rule proceeds as usual.
%    \begin{macrocode}
    local y = -currLine * self.baselineSkip - self.probDistance
    if drawCurrProb then
      tex.sprint(
        "\n\t\\draw [" ..
        self.probStyle(currPeak.prob[currPeak.base]) ..
        "] (" ..
        dimToString(xLeft) ..
        ", " ..
        dimToString(y) ..
        ") -- (" ..
        dimToString(xRight) ..
        ", " ..
        dimToString(y) ..
        ");"
      )
    end
    lastProbX = currPeak.probXRight
  end
end
%    \end{macrocode}
% \iffalse
%</pmb-chr-lua>
%<*pmb-dom-tex>
% \fi
% 
% 
% \section{\texorpdfstring{\file{pgfmolbio.domains.tex}}{pgfmolbio.domains.tex}}
% \label{sec:DocDomTex}
% 
% \def\ydoclistingssettings{\lstset{style=latex-doc}}\setcounter{lstnumber}{1}
%    \begin{macrocode}
\ProvidesFile{pgfmolbio.domains.tex}[2012/10/01 v0.2 Protein Domains]

%    \end{macrocode}
% If the \module{domains} module is requested by Lua\TeX\, it loads the corresponding Lua module and generates a new §SpecialKeys§ object, which will store all feature styles, disulfide keys and print functions (section~\ref{ssc:DocDomLuaSpecialKeysClass}).
%    \begin{macrocode}
\ifluatex
  \RequireLuaModule{pgfmolbio.domains}
  \directlua{pmbSpecialKeys = pgfmolbio.domains.SpecialKeys:new()}
\fi

%    \end{macrocode}
% 
% \subsection{Keys}
% \label{ssc:DocDomTexKeys}
% 
% \begin{macro}{\@pmb@dom@keydef}[2]{\meta{key} name}{default \meta{value}}
% |\@pmb@dom@keydef| declares a \meta{key} in path |/pgfmolbio/domains| and assigns a default \meta{value}.
%    \begin{macrocode}
\def\@pmb@dom@keydef#1#2{%
  \pgfkeyssetvalue{/pgfmolbio/domains/#1}{#2}%
}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\pmbdomvalueof}[1]{\meta{key} name}
% |\pmbdomvalueof| retrieves the value of a \meta{key} in path |/pgfmolbio/domains|. Note that the control word lacks an |@| and is thus freely accessible within a \LaTeX\ document (see section~\ref{sec:DomFeatureStylesAndShapes}).
%    \begin{macrocode}
\def\pmbdomvalueof#1{%
  \pgfkeysvalueof{/pgfmolbio/domains/#1}%
}

%    \end{macrocode}
% \end{macro}
% Aided by these auxiliary macros, we define all keys of the \module{domains} module.
%    \begin{macrocode}
\@pmb@dom@keydef{name}{Protein}
\newif\ifpmb@dom@showname
\pgfmolbioset[domains]{%
  show name/.is if=pmb@dom@showname,
  show name
}
\@pmb@dom@keydef{description}{}

\@pmb@dom@keydef{x unit}{.5mm}
\@pmb@dom@keydef{y unit}{6mm}
\@pmb@dom@keydef{residues per line}{200}
\@pmb@dom@keydef{baseline skip}{3}
\@pmb@dom@keydef{residue numbering}{auto}
\@pmb@dom@keydef{residue range}{auto-auto}
\@pmb@dom@keydef{enlarge left}{0cm}
\@pmb@dom@keydef{enlarge right}{0cm}
\@pmb@dom@keydef{enlarge top}{1cm}
\@pmb@dom@keydef{enlarge bottom}{0cm}

\pgfmolbioset[domains]{%
  style/.code=\pgfmolbioset[domains]{current style/.style={#1}}
}

\@pmb@dom@keydef{domain font}{\footnotesize}

\@pmb@dom@keydef{level}{}
\@pmb@dom@keydef{disulfide base distance}{1}
\@pmb@dom@keydef{disulfide level distance}{.2}
\@pmb@dom@keydef{range font}{\sffamily\scriptsize}

\newif\ifpmb@dom@showruler
\pgfmolbioset[domains]{%
  show ruler/.is if=pmb@dom@showruler,
  show ruler
}
\@pmb@dom@keydef{ruler range}{auto-auto}
\@pmb@dom@keydef{default ruler step size}{50}
\@pmb@dom@keydef{ruler distance}{-.5}

\@pmb@dom@keydef{sequence}{}
\@pmb@dom@keydef{magnified sequence font}{\ttfamily\footnotesize}


\newif\ifpmb@dom@showsecstructure
\pgfmolbioset[domains]{%
  show secondary structure/.is if=pmb@dom@showsecstructure,
  show secondary structure=false
}
\@pmb@dom@keydef{secondary structure distance}{1}
\pgfmolbioset[domains]{%
  helix back border color/.code=\colorlet{helix back border color}{#1},
  helix back main color/.code=\colorlet{helix back main color}{#1},
  helix back middle color/.code=\colorlet{helix back middle color}{#1},
  helix front border color/.code=\colorlet{helix front border color}{#1},
  helix front main color/.code=\colorlet{helix front main color}{#1},
  helix front middle color/.code=\colorlet{helix front middle color}{#1},
  helix back border color=white!50!black,
  helix back main color=white!90!black,
  helix back middle color=white,
  helix front border color=red!50!black,
  helix front main color=red!90!black,
  helix front middle color=red!10!white
}

\@pmb@dom@keydef{sequence length}{}

\@pmb@dom@keydef{@layer}{}

%    \end{macrocode}
% 
% \subsection{Feature Shapes}
% \label{ssc:DocDomTexFeatureShapes}
% 
% \begin{macro}{\setfeatureshape}[2]{Shape \meta{name}.}{\TikZ\ \meta{code}.}
% Stores the \meta{code} for a shape in the macro |\@pmb@dom@feature@|\meta{name}|@shape|.
%    \begin{macrocode}
\newcommand\setfeatureshape[2]{%
  \expandafter\def\csname @pmb@dom@feature@#1@shape\endcsname{#2}%
}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\setfeatureshapealias}[2]{New shape.}{Existing shape.}
% Links a new shape to an existing one.
%    \begin{macrocode}
\newcommand\setfeatureshapealias[2]{%
  \expandafter\def\csname @pmb@dom@feature@#1@shape\endcsname{%
    \@nameuse{@pmb@dom@feature@#2@shape}%
  }%
}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\setfeaturestylealias}[2]{New style.}{Existing style.}
% This macro and the next one are only defined in Lua\TeX\. Depending on whether |\setfeaturestylealias| occurs within a |pmbdomains| environment, it either sets the feature styles of the §SpecialKeys§ object in the current §Protein§ (§pmbProtein.specialKeys§) or of the global §SpecialKeys§ object (§pmbSpecialKeys§).
% \begin{macro}{\setfeaturealias}[2]{New feature.}{Existing feature.}
% Calls |\setfeatureshapealias| and possibly |\setfeaturestylealias|.
%    \begin{macrocode}
\ifluatex
  \newcommand\setfeaturestylealias[2]{%
    \directlua{
      if pmbProtein then
        pmbProtein.specialKeys:aliasFeatureStyle("#1", "#2")
      else
        pmbSpecialKeys:aliasFeatureStyle("#1", "#2")
      end
    }%
  }
  \newcommand\setfeaturealias[2]{%
    \setfeatureshapealias{#1}{#2}%
    \setfeaturestylealias{#1}{#2}%
  }
\else
  \let\setfeaturealias\setfeatureshapealias%
\fi

%    \end{macrocode}
% \end{macro}\end{macro}
% \begin{macro}{\pmbdomdrawfeature}[1]{The feature \meta{type} that should be drawn.}
% If a feature \meta{type} (i.\,e., the corresponding macro) is undefined, we issue a warning and draw feature \texttt{default}.
%    \begin{macrocode}
\newcommand\pmbdomdrawfeature[1]{%
  \@ifundefined{@pmb@dom@feature@#1@shape}{%
    \PackageWarning{pgfmolbio}%
      {Feature shape `#1' unknown, using `default'.}%
    \@pmb@dom@feature@default@shape%
  }{%
    \@nameuse{@pmb@dom@feature@#1@shape}%
  }%
}

%    \end{macrocode}
% \end{macro}
% Definitions of standard features and their aliases.
%    \begin{macrocode}
\setfeatureshape{default}{%
  \path [/pgfmolbio/domains/current style]
    (\xLeft, \yMid + .5 * \pmbdomvalueof{y unit}) rectangle
    (\xRight, \yMid - .5 * \pmbdomvalueof{y unit});
}

\setfeatureshape{domain}{
  \draw [/pgfmolbio/domains/current style, rounded corners=2pt]
    (\xLeft, \yMid + .5 * \pmbdomvalueof{y unit}) rectangle
    (\xRight, \yMid - .5 * \pmbdomvalueof{y unit});
  \node at (\xMid, \yMid)
    {\pmbdomvalueof{domain font}{\pmbdomvalueof{description}}};
}
\setfeaturealias{DOMAIN}{domain}

\setfeatureshape{signal peptide}{%
  \path [/pgfmolbio/domains/current style]
    (\xLeft, \yMid + \pmbdomvalueof{y unit} / 5) rectangle
    (\xRight, \yMid - \pmbdomvalueof{y unit} / 5);
}
\setfeaturealias{SIGNAL}{signal peptide}

\setfeatureshape{propeptide}{%
  \path [/pgfmolbio/domains/current style]
    (\xLeft, \yMid + .5 * \pmbdomvalueof{y unit}) rectangle
    (\xRight, \yMid - .5 * \pmbdomvalueof{y unit});
}
\setfeaturealias{PROPEP}{propeptide}

\setfeatureshape{carbohydrate}{%
  \draw [/pgfmolbio/domains/current style]
    (\xMid, \yMid) --
    (\xMid, \yMid + .7 * \pmbdomvalueof{y unit})
    node [above] {\tiny\strut\pmbdomvalueof{description}};
  \fill [/pgfmolbio/domains/current style]
    (\xMid, \yMid + .7 * \pmbdomvalueof{y unit}) circle [radius=1pt];
}
\setfeaturealias{CARBOHYD}{carbohydrate}

\setfeatureshape{other/main chain}{%
  \ifpmb@dom@showsecstructure%
    \pgfmathsetmacro\yUpper{%
      \yMid + \pmbdomvalueof{secondary structure distance}
        * \pmbdomvalueof{y unit}%
    }
    \draw [thin]
      (\xLeft, \yUpper pt) --
      (\xRight, \yUpper pt);%
  \fi%
  \path [/pgfmolbio/domains/current style]
    (\xLeft, \yMid) --
    (\xRight, \yMid);%
}

\setfeatureshape{other/name}{%
  \ifpmb@dom@showname%
    \node [/pgfmolbio/domains/current style]
      at (\xMid, \pmbdomvalueof{baseline skip} * \pmbdomvalueof{y unit})
      {\pmbdomvalueof{name} (\pmbdomvalueof{sequence length} residues)};
  \fi%
}

\setfeatureshape{disulfide}{%
  \pgfmathsetmacro\yUpper{%
    \yMid + (
      \pmbdomvalueof{disulfide base distance} +
      (\pmbdomvalueof{level} - 1) *
      \pmbdomvalueof{disulfide level distance}
    ) * \pmbdomvalueof{y unit}
  }
  \path [/pgfmolbio/domains/current style]
    (\xLeft, \yMid) --
    (\xLeft, \yUpper pt) --
    (\xRight, \yUpper pt) --
    (\xRight, \yMid);
}
\setfeaturealias{DISULFID}{disulfide}

\setfeatureshape{range}{%
  \pgfmathsetmacro\yUpper{%
    \yMid + (
      \pmbdomvalueof{disulfide base distance} +
      (\pmbdomvalueof{level} - 1) *
      \pmbdomvalueof{disulfide level distance}
    ) * \pmbdomvalueof{y unit}
  }
  \path [/pgfmolbio/domains/current style]
    (\xLeft, \yUpper pt) --
    (\xRight, \yUpper pt)
    node [pos=.5, above]
      {\pmbdomvalueof{range font}{\pmbdomvalueof{description}}};
}

\setfeatureshape{other/ruler}{%
  \draw [/pgfmolbio/domains/current style]
    (\xMid,
      \yMid + \pmbdomvalueof{ruler distance} *
              \pmbdomvalueof{y unit}) --
    (\xMid,
      \yMid + \pmbdomvalueof{ruler distance} *
              \pmbdomvalueof{y unit} - 1mm)
    node [below=-1mm] {\tiny\sffamily\strut\residueNumber};
}


\setfeatureshape{other/sequence}{%
  \node [/pgfmolbio/domains/current style]
    at (\xMid, \yMid) {\strut\currentResidue};
}

\newlength\pmb@magnifiedsequence@width

\setfeatureshape{other/magnified sequence above}{%
  \settowidth\pmb@magnifiedsequence@width{%
    \begin{pgfinterruptpicture}%
      \pmbdomvalueof{magnified sequence font}%
      \featureSequence%
      \end{pgfinterruptpicture}%
    }%
  \pgfmathsetmacro\xUpperLeft{\xMid - \pmb@magnifiedsequence@width / 2}
  \pgfmathsetmacro\xUpperRight{\xMid + \pmb@magnifiedsequence@width / 2}
  
  \draw [/pgfmolbio/domains/current style]
    (\xLeft, \yMid) --
    (\xLeft, \yMid + \pmbdomvalueof{y unit} / 6) --
    (\xUpperLeft pt, \yMid + \pmbdomvalueof{y unit} * 4/6) --
    (\xUpperLeft pt, \yMid + \pmbdomvalueof{y unit} * 5/6)
    (\xUpperRight pt, \yMid + \pmbdomvalueof{y unit} * 5/6) --
    (\xUpperRight pt, \yMid + \pmbdomvalueof{y unit} * 4/6) --
    (\xRight, \yMid + \pmbdomvalueof{y unit} / 6) --
    (\xRight, \yMid);
  \node [anchor=mid]
    at (\xMid, \yMid + \pmbdomvalueof{y unit})
    {\pmbdomvalueof{magnified sequence font}\featureSequence};
}

\setfeatureshape{other/magnified sequence below}{%
  \settowidth\pmb@magnifiedsequence@width{%
    \begin{pgfinterruptpicture}%
      \pmbdomvalueof{magnified sequence font}%
      \featureSequence%
      \end{pgfinterruptpicture}%
    }%
  \pgfmathsetmacro\xLowerLeft{\xMid - \pmb@magnifiedsequence@width / 2}
  \pgfmathsetmacro\xLowerRight{\xMid + \pmb@magnifiedsequence@width / 2}
  
  \draw [/pgfmolbio/domains/current style]
    (\xLeft, \yMid) --
    (\xLeft, \yMid - \pmbdomvalueof{y unit} / 6) --
    (\xLowerLeft pt, \yMid - \pmbdomvalueof{y unit}) --
    (\xLowerLeft pt, \yMid - \pmbdomvalueof{y unit} * 7/6)
    (\xLowerRight pt, \yMid - \pmbdomvalueof{y unit} * 7/6) --
    (\xLowerRight pt, \yMid - \pmbdomvalueof{y unit}) --
    (\xRight, \yMid - \pmbdomvalueof{y unit} / 6) --
    (\xRight, \yMid);
  \node [anchor=mid]
    at (\xMid, \yMid - \pmbdomvalueof{y unit} * 8/6)
    {\pmbdomvalueof{magnified sequence font}\featureSequence};
}


%    \end{macrocode}
% 
% \subsection{Secondary Structure Elements}
% \label{ssc:DocDomTexSecondaryStructure}
% 
% \begin{macro}{\@pmb@dom@helixsegment}[1]{Scale factor for \TikZ's \texttt{svg} action.}
% Draws a full helix segment at the current canvas position. We use the (unusual) \file{svg} syntax since the helix segment was designed in Inkscape, and the \file{svg} commands were copied from the resulting vector graphics file.
%    \begin{macrocode}
\newcommand\@pmb@dom@helixsegment[1]{%
  svg [scale=#1] "%
    c  0.30427  0
       0.62523  0.59174
       0.79543  0.96646
    c  0.97673  2.15039
       1.34005  4.49858
       1.84538  6.6178
    c  0.56155  2.35498
       0.99602  4.514
       1.82948  6.72355
    c  0.11069  0.29346
       0.23841  0.69219
       0.56172  0.69219
    l -5        0
    c -0.27235  0.0237
      -0.55793 -0.51373
      -0.65225 -0.76773
    c -0.98048 -2.64055
      -1.40233 -5.46534
      -2.06809 -8.00784
    c -0.50047 -1.91127
      -0.94696 -3.73368
      -1.68631 -5.43929
    c -0.14066 -0.3245
      -0.34516 -0.78514
      -0.69997 -0.78514
    z"
}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@pmb@dom@helixhalfsegment}[1]{Scale factor for \TikZ's \texttt{svg} action.}
% Draws a half helix segment.
%    \begin{macrocode}
\newcommand\@pmb@dom@helixhalfsegment[1]{%
  svg [scale=#1] "%
    c  0.50663  2.18926
       0.96294  4.51494
       1.78125  6.71875
    c  0.09432  0.254
       0.35265  0.80495
       0.625    0.78125
    l  5        0
    c -0.32331  0
      -0.45181 -0.42529
      -0.5625  -0.71875
    c -0.83346 -2.20955
      -1.2822  -4.36377
      -1.84375 -6.78125
    l -5        0
    z"
}

%    \end{macrocode}
% \end{macro}
% Shadings for helix segments.
%    \begin{macrocode}
\pgfdeclareverticalshading[%
    helix back border color,%
    helix back main color,%
    helix back middle color%
  ]{helix half upper back}{100bp}{
  color(0bp)=(helix back middle color);
  color(5bp)=(helix back middle color);
  color(45bp)=(helix back main color);
  color(75bp)=(helix back border color);
  color(100bp)=(helix back border color)
}

\pgfdeclareverticalshading[%
    helix back border color,%
    helix back main color,%
    helix back middle color%
  ]{helix half lower back}{100bp}{
  color(0bp)=(helix back border color);
  color(25bp)=(helix back border color);
  color(35bp)=(helix back main color);
  color(55bp)=(helix back middle color);
  color(95bp)=(helix back main color);
  color(100bp)=(helix back main color)
}

\pgfdeclareverticalshading[%
    helix back border color,%
    helix back main color,%
    helix back middle color%
  ]{helix full back}{100bp}{
  color(0bp)=(helix back border color);
  color(25bp)=(helix back border color);
  color(30bp)=(helix back main color);
  color(40bp)=(helix back middle color);
  color(60bp)=(helix back main color);
  color(75bp)=(helix back border color);
  color(100bp)=(helix back border color)
}

\pgfdeclareverticalshading[%
    helix front border color,%
    helix front main color,%
    helix front middle color%
  ]{helix half upper front}{100bp}{
  color(0bp)=(helix front main color);
  color(5bp)=(helix front main color);
  color(45bp)=(helix front middle color);
  color(65bp)=(helix front main color);
  color(75bp)=(helix front border color);
  color(100bp)=(helix front border color)
}

\pgfdeclareverticalshading[%
    helix front border color,%
    helix front main color,%
    helix front middle color%
  ]{helix full front}{100bp}{
  color(0bp)=(helix front border color);
  color(25bp)=(helix front border color);
  color(40bp)=(helix front main color);
  color(60bp)=(helix front middle color);
  color(70bp)=(helix front main color);
  color(75bp)=(helix front border color);
  color(100bp)=(helix front border color)
}

%    \end{macrocode}
% The following features print single helical turns. They are drawn with appropriate coordinates by §printHelixFeature§ (section~\ref{ssc:DocDomLuaPrintFunctions}).
%    \begin{macrocode}
\setfeatureshape{helix/half upper back}{%
  \ifpmb@dom@showsecstructure%
    \pgfmathsetmacro\yShift{%
      \pmbdomvalueof{secondary structure distance} *
      \pmbdomvalueof{y unit}%
    }
    \draw [shading=helix half upper back]
      (\xLeft, \yMid + \yShift pt)
      \@pmb@dom@helixhalfsegment{\pmbdomvalueof{x unit} / 5};
  \fi%
}

\setfeatureshape{helix/half lower back}{%
  \ifpmb@dom@showsecstructure%
    \pgfmathsetmacro\yShift{%
      \pmbdomvalueof{secondary structure distance} *
      \pmbdomvalueof{y unit}%
    }
    \draw [shading=helix half lower back]
      (\xRight, \yMid + \yShift pt) [rotate=180]
      \@pmb@dom@helixhalfsegment{\pmbdomvalueof{x unit} / 5};
  \fi%
}

\setfeatureshape{helix/full back}{%
  \ifpmb@dom@showsecstructure%
    \pgfmathsetmacro\yShift{%
      \pmbdomvalueof{secondary structure distance} *
      \pmbdomvalueof{y unit}%
    }
    \draw [shading=helix full back]
      (\xMid, \yLower + \yShift pt)
      \@pmb@dom@helixsegment{\pmbdomvalueof{x unit} / 5};
  \fi%
}

\setfeatureshape{helix/half upper front}{%
  \ifpmb@dom@showsecstructure%
    \pgfmathsetmacro\yShift{%
      \pmbdomvalueof{secondary structure distance} *
      \pmbdomvalueof{y unit}%
    }
    \draw [shading=helix half upper front]
      (\xRight, \yMid + \yShift pt) [xscale=-1]
      \@pmb@dom@helixhalfsegment{\pmbdomvalueof{x unit} / 5};
  \fi%
}

\setfeatureshape{helix/full front}{%
  \ifpmb@dom@showsecstructure%
    \pgfmathsetmacro\yShift{%
      \pmbdomvalueof{secondary structure distance} *
      \pmbdomvalueof{y unit}%
    }
    \draw [shading=helix full front]
      (\xMid, \yLower + \yShift pt) [xscale=-1]
      \@pmb@dom@helixsegment{\pmbdomvalueof{x unit} / 5};
  \fi%
}

%    \end{macrocode}
% Definitions of the remaining secondary structure features.
%    \begin{macrocode}
\definecolor{strand left color}{RGB}{42,127,255}
\definecolor{strand right color}{RGB}{128,179,255}

\setfeatureshape{beta strand}{%
  \ifpmb@dom@showsecstructure%
    \pgfmathsetmacro\yShift{%
      \pmbdomvalueof{secondary structure distance} *
      \pmbdomvalueof{y unit}%
    }
    \draw [/pgfmolbio/domains/current style]
      (\xLeft, \yMid + \pmbdomvalueof{x unit} + \yShift pt) --
      (\xRight - 1.5 * \pmbdomvalueof{x unit},
        \yMid + \pmbdomvalueof{x unit} + \yShift pt) --
      (\xRight - 1.5 * \pmbdomvalueof{x unit},
        \yMid + 1.5 * \pmbdomvalueof{x unit} + \yShift pt) --
      (\xRight, \yMid + \yShift pt) --
      (\xRight - 1.5 * \pmbdomvalueof{x unit},
        \yMid - 1.5 * \pmbdomvalueof{x unit} + \yShift pt) --
      (\xRight - 1.5 * \pmbdomvalueof{x unit},
        \yMid - \pmbdomvalueof{x unit} + \yShift pt) --
      (\xLeft, \yMid - \pmbdomvalueof{x unit} + \yShift pt) --
      cycle;%
  \fi%
}
\setfeaturealias{STRAND}{beta strand}

\setfeatureshape{beta turn}{%
  \ifpmb@dom@showsecstructure%
    \pgfmathsetmacro\yShift{%
      \pmbdomvalueof{secondary structure distance} *
      \pmbdomvalueof{y unit}%
    }
    \pgfmathsetmacro\turnXradius{(\xRight - \xLeft) / 2}%
    \pgfmathsetmacro\turnYradius{\pmbdomvalueof{x unit} * 1.5}%
    \fill [white]
      (\xLeft, \yMid + 1mm + \yShift pt) rectangle
      (\xRight, \yMid - 1mm + \yShift pt);%
    \draw [/pgfmolbio/domains/current style]
      (\xLeft - .5pt, \yMid + \yShift pt) --
      (\xLeft, \yMid + \yShift pt) arc
        [start angle=180, end angle=0,
        x radius=\turnXradius pt, y radius=\turnYradius pt] --
      (\xRight + .5pt, \yMid + \yShift pt);%
  \fi%
}
\setfeaturealias{TURN}{beta turn}

\setfeatureshape{beta bridge}{%
  \ifpmb@dom@showsecstructure%
    \pgfmathsetmacro\yShift{%
      \pmbdomvalueof{secondary structure distance} *
      \pmbdomvalueof{y unit}%
    }
    \draw [/pgfmolbio/domains/current style]
      (\xLeft, \yMid + .25 * \pmbdomvalueof{x unit} + \yShift pt) --
      (\xRight - 1.5 * \pmbdomvalueof{x unit},
        \yMid + .25 * \pmbdomvalueof{x unit} + \yShift pt) --
      (\xRight - 1.5 * \pmbdomvalueof{x unit},
        \yMid + 1.5 * \pmbdomvalueof{x unit} + \yShift pt) --
      (\xRight, \yMid + \yShift pt) --
      (\xRight - 1.5 * \pmbdomvalueof{x unit},
        \yMid - 1.5 * \pmbdomvalueof{x unit} + \yShift pt) --
      (\xRight - 1.5 * \pmbdomvalueof{x unit},
        \yMid - .25 * \pmbdomvalueof{x unit} + \yShift pt) --
      (\xLeft, \yMid - .25 * \pmbdomvalueof{x unit} + \yShift pt) --
      cycle;%
  \fi%
}

\setfeatureshape{bend}{%
  \ifpmb@dom@showsecstructure%
    \pgfmathsetmacro\yShift{%
      \pmbdomvalueof{secondary structure distance} *
      \pmbdomvalueof{y unit}%
    }
    \fill [white]
      (\xLeft, \yMid + 1mm + \yShift pt) rectangle
      (\xRight, \yMid - 1mm + \yShift pt);%
    \draw [/pgfmolbio/domains/current style]
      (\xLeft - .5pt, \yMid + \yShift pt) --
      (\xLeft, \yMid + \yShift pt) --
      (\xMid, \yMid + .5 * \pmbdomvalueof{y unit} + \yShift pt) --
      (\xRight, \yMid + \yShift pt) --
      (\xRight + .5pt, \yMid + \yShift pt);%
  \fi%
}

%    \end{macrocode}
% This concludes the part of the package that is always loaded. The remaining code is only executed within Lua\TeX.
%    \begin{macrocode}
\ifluatex\else\expandafter\endinput\fi


%    \end{macrocode}
% 
% \subsection{Adding Features}
% \label{ssc:DocDomTexAddingFeatures}
% 
% \begin{macro}{\pmb@dom@inputuniprot}[1]{The \meta{name} of a Uniprot file.}
% |\pmb@dom@inputuniprot| reads some attributes and all features from a Uniprot file (§readUniprotFile§, section~\ref{ssc:DocDomLuaReadFiles}). It then updates some keys of the \module{domains} module (§getParameters§, section~\ref{ssc:DocDomLuaParameters}) and then passes the value of \opt{residue numbering} to the §pmbProtein§ object.
%    \begin{macrocode}
\newcommand\pmb@dom@inputuniprot[1]{%
  \directlua{
    pmbProtein:readUniprotFile("#1")
    pmbProtein:getParameters()
    pmbProtein:setParameters{
      residueNumbering = "\pmbdomvalueof{residue numbering}"
    }
  }%
}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\pmb@dom@inputgff}[1]{The \meta{name} of a General Feature Format (\file{gff}) file.}
% This macro reads all features from a \file{gff} file (§readGffFile§, section~\ref{ssc:DocDomLuaReadFiles}). It then passes the value of residue numbering to §pmbProtein§.
%    \begin{macrocode}
\newcommand\pmb@dom@inputgff[1]{%
  \directlua{
    pmbProtein:readGffFile("#1")
    pmbProtein:setParameters{
      residueNumbering = "\pmbdomvalueof{residue numbering}"
    }
  }%
}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\pmb@dom@addfeature}[4]{A \ometa{key-value list} that is locally applied to the feature.}{The feature \meta{key}.}{The \meta{first} \dots}{and \meta{last} residue covered by the feature.}
% This macro adds a feature to §pmbProtein§ by calling its §addFeature§ method. The \ometa{key-value list} should be stored without any expansion in the §kvList§ field of §addFeature§'s single argument table. To this end, we first store the \ometa{key-value list} in the token register |\@pmb@toksa| and then access its contents by the construction |\directlua{|[...]|\the\@pmb@toksa|[...]|}|. This code behaves similarly to |\the| inside an |\edef|, i.\,e. the contents of the token register are not further expanded.
%    \begin{macrocode}
\newcommand\pmb@dom@addfeature[4][]{%
  \begingroup%
  \pgfmolbioset[domains]{#1}%
  \@pmb@toksa{#1}%
  \directlua{
    pmbProtein:addFeature{
      key = "#2",
      start = "#3",
      stop = "#4",
      kvList = "\luaescapestring{\the\@pmb@toksa}",
      level = tonumber("\pmbdomvalueof{level}"),
      layer = tonumber("\pmbdomvalueof{@layer}")
    }
  }%
  \endgroup%
}

%    \end{macrocode}
% \end{macro}
% 
% \subsection{The Main Environment}
% \label{ssc:DocDomTexMainEnvironment}
% 
% % \begin{environment}{pmbdomains}[2]{A \ometa{key-value list} that configures the domain diagram.}{The \meta{sequence length}.}
% If |pmbdomains| appears outside of a |tikzpicture|, we implicitly start this environment, otherwise we begin a new group. ``Within a |tikzpicture|'' means that |\useasboundingbox| is defined. The \ometa{key-value list} is processed.
%    \begin{macrocode}
\newif\ifpmb@dom@tikzpicture

\newenvironment{pmbdomains}[2][]{%
  \@ifundefined{useasboundingbox}%
    {\pmb@dom@tikzpicturefalse\begin{tikzpicture}}%
    {\pmb@dom@tikzpicturetrue}%
  \pgfmolbioset[domains]{sequence length=#2, #1}%
%    \end{macrocode}
% The macros |\inputuniprot|, |\inputgff| and |\addfeature| only point to their respective internal macros (section~\ref{ssc:DocDomTexAddingFeatures}) within |pmbdomains|.
%    \begin{macrocode}
  \let\inputuniprot\pmb@dom@inputuniprot%
  \let\inputgff\pmb@dom@inputgff%
  \let\addfeature\pmb@dom@addfeature%
%    \end{macrocode}
% §pmbProtein§ is a new §Protein§ object whose §specialKeys§ attribute is initialized with the values from the package-wide §SpecialKeys§ object. Since §pmbProtein§ must know the sequence length and residue numbering before the environment's body is processed, we call §setParameters§ twice to ensure that §sequenceLength§ is set prior to §residueNumbering§.
%    \begin{macrocode}
  \directlua{
    pmbProtein = pgfmolbio.domains.Protein:new()
    pmbProtein.specialKeys =
      pgfmolbio.domains.SpecialKeys:new(pmbSpecialKeys)
    pmbProtein:setParameters{
      sequenceLength = "\pmbdomvalueof{sequence length}"
    }
    pmbProtein:setParameters{
      residueNumbering = "\pmbdomvalueof{residue numbering}"
    }
  }%
}{%
%    \end{macrocode}
% At the end of |pmbdomains|'s body, §pmbProtein§ stores all features that have been defined there. We add one more feature, \texttt{other/main chain}, which spans the whole protein and occupies the lowermost layer (this is the only instance where we need the \opt{@layer} key).
%    \begin{macrocode}
  \pmb@dom@addfeature[@layer=1]{other/main chain}%
    {(1)}{(\pmbdomvalueof{sequence length})}%
%    \end{macrocode}
% The following syntactical gem ensures that the token register |\@pmb@toksa| contains the value of the \opt{name} key without expansion of any macros within the value.
%    \begin{macrocode}
  \@pmb@toksa=%
    \expandafter\expandafter\expandafter\expandafter%
    \expandafter\expandafter\expandafter{%
      \pgfkeysvalueof{/pgfmolbio/domains/name}%
    }%
%    \end{macrocode}
% Set the remaining attributes of §pmbProtein§.
%    \begin{macrocode}
  \directlua{
    pmbProtein:setParameters{
      residueRange = "\pmbdomvalueof{residue range}",
      defaultRulerStepSize = "\pmbdomvalueof{default ruler step size}"
    }
    pmbProtein:setParameters{
      name = "\luaescapestring{\the\@pmb@toksa}",
      xUnit = "\pmbdomvalueof{x unit}",
      yUnit = "\pmbdomvalueof{y unit}",
      residuesPerLine = "\pmbdomvalueof{residues per line}",
      baselineSkip = "\pmbdomvalueof{baseline skip}",
      showRuler = "\ifpmb@dom@showruler true\else false\fi",
      rulerRange = "\pmbdomvalueof{ruler range}",
      sequence = "\pmbdomvalueof{sequence}"
    }
%    \end{macrocode}
% Calculate he appropriate levels of disulfide-like features (section~\ref{ssc:DocDomLuaDisulfideLevels}). §pgfmolbio.setCoordinateFormat§ sets the coordinate output format (section~\ref{sec:DocPkgLua}).
%    \begin{macrocode}
    pmbProtein:calculateDisulfideLevels()
    pgfmolbio.setCoordinateFormat(
      "\pgfkeysvalueof{/pgfmolbio/coordinate unit}",
      "\pgfkeysvalueof{/pgfmolbio/coordinate format string}"
    )
%    \end{macrocode}
% If the \module{convert} module is loaded, we open the appropriate output file. If we wish to output final \TikZ\ code, we change §tex.sprint§ so that the function writes to this file and then call §printTikzDomains§. Otherwise, we write a string representation of §pmbProtein§ to the file (section~\ref{ssc:DocDomLuaTostring}). Without the \module{convert} module, §printTikzDomains§ simply returns the drawing commands for the chromatogram to the \TeX\ input stream (section~\ref{ssc:DocDomLuaPrintTikzDomains}).
%    \begin{macrocode}
    \ifpmb@loadmodule@convert
      local filename =
        "\pgfkeysvalueof{/pgfmolbio/convert/output file name}"
      if filename == "(auto)" then
        filename = "pmbconverted" .. pgfmolbio.outputFileId
      end
      filename = filename ..
        ".\pgfkeysvalueof{/pgfmolbio/convert/output file extension}"
      outputFile, ioError = io.open(filename, "w")
      if ioError then
        tex.error(ioError)
      end
      \ifpmb@con@outputtikzcode
        tex.sprint = function(a) outputFile:write(a) end
        pmbProtein:getParameters()
        tex.sprint("\string\n\string\\begin{tikzpicture}")
        pmbProtein:printTikzDomains()
        tex.sprint("\string\n\string\\end{tikzpicture}")
      \else
        \ifpmb@con@includedescription
          pmbProtein.includeDescription = true
        \fi
        outputFile:write(tostring(pmbProtein))
      \fi
      outputFile:close()
      pgfmolbio.outputFileId = pgfmolbio.outputFileId + 1
    \else
      pmbProtein:printTikzDomains()
    \fi
    pmbProtein = nil
  }%
%    \end{macrocode}
% At the end of |pmbdomains|, we close an implicitly added |tikzpicture|.
%    \begin{macrocode}
  \ifpmb@dom@tikzpicture\else\end{tikzpicture}\fi%
}

%    \end{macrocode}
% \end{environment}
% 
% \subsection{Feature Styles}
% \label{ssc:DocDomTexFeatureStyles}
% 
% \begin{macro}{\setdisulfidefeatures}[1]{A list of \meta{features}.}
% Clears the list of disulfide-like features and adds the \meta{features} to the empty list. Disulfide-like features are arranged in non-overlapping layers (section~\ref{sec:DomDisulfides}). Depending on whether this macro appears inside a |pmbdomains| environment or not, the appropriate methods of either §pmbProtein.specialKeys§ or §pmbSpecialKeys§ are called, respectively.
%    \begin{macrocode}
\newcommand\setdisulfidefeatures[1]{%
  \directlua{
    if pmbProtein then
      pmbProtein.specialKeys:clearKeys("disulfideKeys")
      pmbProtein.specialKeys:setKeys("disulfideKeys", "#1", true)
    else
      pmbSpecialKeys:clearKeys("disulfideKeys")
      pmbSpecialKeys:setKeys("disulfideKeys", "#1", true)
    end
  }%
}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\adddisulfidefeatures}[1]{A list of \meta{features}.}
% Adds the \meta{features} to the list of disulfide-like features without overwriting the current list.
%    \begin{macrocode}
\newcommand\adddisulfidefeatures[1]{%
  \directlua{
    if pmbProtein then
      pmbProtein.specialKeys:setKeys("disulfideKeys", "#1", true)
    else
      pmbSpecialKeys:setKeys("disulfideKeys", "#1", true)
    end
  }%
}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\removedisulfidefeatures}[1]{A list of \meta{features}.}
% Removes the \meta{features} from the list of disulfide-like features.
%    \begin{macrocode}
\newcommand\removedisulfidefeatures[1]{%
  \directlua{
    if pmbProtein then
      pmbProtein.specialKeys:setKeys("disulfideKeys", "#1", nil)
    else
      pmbSpecialKeys:setKeys("disulfideKeys", "#1", nil)
    end
  }%
}

%    \end{macrocode}
% \end{macro}
% Declare the default disulfide-like features.
%    \begin{macrocode}
\setdisulfidefeatures{DISULFID, disulfide, range}

%    \end{macrocode}
% \begin{macro}{\setfeatureprintfunction}[2]{A \meta{list} of features.}{Name of a Lua \meta{function}.}
% Assigns a feature print \meta{function} to each feature in the \meta{list}. Feature print functions are preprocessors which, for instance, calculate coordinates for features (section~\ref{sec:DomSequences}).
%    \begin{macrocode}
\newcommand\setfeatureprintfunction[2]{%
  \directlua{
    if pmbProtein then
      pmbProtein.specialKeys:setKeys("printFunctions", "#1", #2)
    else
      pmbSpecialKeys:setKeys("printFunctions", "#1", #2)
    end
  }%
}

%    \end{macrocode}
% \end{macro}
% \begin{macro}{\removefeatureprintfunction}[1]{A \meta{list} of features.}
% Removes any feature print function from the features in the \meta{list}.
%    \begin{macrocode}
\newcommand\removefeatureprintfunction[1]{%
  \directlua{
    if pmbProtein then
      pmbProtein.specialKeys:setKeys("printFunctions", "#1", nil)
    else
      pmbSpecialKeys:setKeys("printFunctions", "#1", nil)
    end
  }%
}

%    \end{macrocode}
% \end{macro}
% Assign default feature print functions.
%    \begin{macrocode}
\setfeatureprintfunction{other/sequence}%
  {pgfmolbio.domains.printSequenceFeature}
\setfeatureprintfunction{alpha helix, pi helix, 310 helix, HELIX}%
  {pgfmolbio.domains.printHelixFeature}

%    \end{macrocode}
% 
% \begin{macro}{\setfeaturestyle}[2]{A \meta{feature} name.}{A \meta{style list}.}
% Sets the style of a \meta{feature} to the style described in the \meta{style list}. Note that the contents of \meta{style list} are passed to the Lua function without expansion (via the token register |\@pmb@toksa|).
%    \begin{macrocode}
\newcommand\setfeaturestyle[2]{%
  \@pmb@toksa{#2}%
  \directlua{
    if pmbProtein then
      pmbProtein.specialKeys:setFeatureStyle(
        "#1", "\luaescapestring{\the\@pmb@toksa}"
      )
    else
      pmbSpecialKeys:setFeatureStyle(
        "#1", "\luaescapestring{\the\@pmb@toksa}"
      )
    end
  }%
}

%    \end{macrocode}
% \end{macro}
% Declare default feature styles.
%    \begin{macrocode}
\setfeaturestyle{default}{draw}
\setfeaturestyle{domain}%
  {fill=Chartreuse,fill=LightSkyBlue,fill=LightPink,fill=Gold!50}
\setfeaturestyle{signal peptide}{fill=black}
\setfeaturestyle{propeptide}%
  {*1{fill=Gold, opacity=.5, rounded corners=4pt}}
\setfeaturestyle{carbohydrate}{red}
\setfeaturestyle{other/main chain}{*1{draw, line width=2pt, black!25}}
\setfeaturestyle{other/name}{font=\sffamily}
\setfeaturestyle{disulfide}{draw=olive}
\setfeaturestyle{range}{*1{draw,decorate,decoration=brace}}
\setfeaturestyle{other/ruler}{black, black!50}
\setfeaturestyle{other/sequence}{*1{font=\ttfamily\tiny}}%
\setfeaturestyle{other/magnified sequence above}%
  {*1{draw=black!50, densely dashed}}
\setfeaturestylealias{other/magnified sequence below}%
  {other/magnified sequence above}
\setfeaturestyle{alpha helix}{%
  *1{helix front border color=red!50!black,%
  helix front main color=red!90!black,%
  helix front middle color=red!10!white}%
}
\setfeaturestylealias{HELIX}{alpha helix}
\setfeaturestyle{pi helix}{%
  *1{helix front border color=yellow!50!black,%
  helix front main color=yellow!70!red,%
  helix front middle color=yellow!10!white}%
}
\setfeaturestyle{310 helix}{%
  *1{helix front border color=magenta!50!black,%
  helix front main color=magenta!90!black,%
  helix front middle color=magenta!10!white}%
}
\setfeaturestyle{beta strand}{%
  *1{left color=strand left color, right color=strand right color}%
}
\setfeaturestyle{beta turn}{*1{draw=violet, thick}}
\setfeaturestyle{beta bridge}{*1{fill=MediumBlue}}
\setfeaturestyle{bend}{*1{draw=magenta, thick}}
%    \end{macrocode}
% 
% \iffalse
%</pmb-dom-tex>
%<*pmb-dom-lua>
% \fi
% 
% 
% 
% \section{\texorpdfstring{\file{pgfmolbio.domains.lua}}{pgfmolbio.domains.lua}}
% \label{sec:DocDomLua}
% 
% \def\ydoclistingssettings{\lstset{style=lua-doc}}\setcounter{lstnumber}{1}
%    \begin{macrocode}
if luatexbase then
  luatexbase.provides_module({
    name          = "pgfmolbio.domains",
    version       = 0.2,
    date          = "2012/10/01",
    description   = "Domain graphs",
    author        = "Wolfgang Skala",
    copyright     = "Wolfgang Skala",
    license       = "LPPL",
  })
end

%    \end{macrocode}
% These local functions point to functions in \file{pgfmolbio.lua} (section~\ref{sec:DocPkgLua}).
%    \begin{macrocode}
local stringToDim = pgfmolbio.stringToDim
local dimToString = pgfmolbio.dimToString
local packageError = pgfmolbio.packageError
local packageWarning = pgfmolbio.packageWarning
local getRange = pgfmolbio.getRange

%    \end{macrocode}
% 
% \subsection{Predefined Feature Print Functions}
% \label{ssc:DocDomLuaPrintFunctions}
% 
% §printSequenceFeature§ prints the letters of a sequence between the $x$-coordinates §xLeft§ and §xRight§.
%    \begin{macrocode}
function printSequenceFeature(feature, xLeft, xRight, yMid, xUnit, yUnit)
  xLeft = xLeft + 0.5
  for currResidue in feature.sequence:gmatch(".") do
    tex.sprint("\n\t\t\\def\\xMid{" .. dimToString(xLeft * xUnit) .. "}")
    tex.sprint("\n\t\t\\def\\yMid{" .. dimToString(yMid * yUnit) .. "}")
    tex.sprint("\n\t\t\\def\\currentResidue{" .. currResidue .. "}")
    tex.sprint("\n\t\t\\pmbdomdrawfeature{other/sequence}")
    xLeft = xLeft + 1
  end
end

%    \end{macrocode}
% 
% §printHelixFeature§ prints a helix feature between the $x$-coordinates §xLeft§ and §xRight§.
%    \begin{macrocode}
function printHelixFeature(feature, xLeft, xRight, yMid, xUnit, yUnit)
  local residuesLeft, currX
  tex.sprint("\n\t\t\\pgfmolbioset[domains]{current style}")
  
%    \end{macrocode}
% \textit{Firstly}, three different background parts are drawn: one \texttt{half upper back} at the left, zero or more \texttt{full back} in the middle and possibly one \texttt{half lower back} at the right.
%    \begin{macrocode}
  residuesLeft = feature.stop - feature.start + 1
  currX = xLeft
  tex.sprint("\n\t\t\\def\\xLeft{" .. dimToString(currX * xUnit) .. "}")
  tex.sprint("\n\t\t\\def\\yMid{" .. dimToString(yMid * yUnit) .. "}")
  tex.sprint("\n\t\t\\pmbdomdrawfeature{helix/half upper back}")
  residuesLeft = residuesLeft - 2
  currX = currX + 2.5
  
  while residuesLeft > 0 do
    if residuesLeft == 1 then
      tex.sprint(
        "\n\t\t\\def\\xRight{" ..
        dimToString((currX + 0.5) * xUnit) ..
        "}"
      )
      tex.sprint("\n\t\t\\def\\yMid{" .. dimToString(yMid * yUnit) .. "}")
      tex.sprint("\n\t\t\\pmbdomdrawfeature{helix/half lower back}")
    else
      tex.sprint("\n\t\t\\def\\xMid{" .. dimToString(currX * xUnit) .. "}")
      tex.sprint(
        "\n\t\t\\def\\yLower{" ..
        dimToString(yMid * yUnit - 1.5 * xUnit) ..
        "}"
      )
      tex.sprint("\n\t\t\\pmbdomdrawfeature{helix/full back}")
    end
    residuesLeft = residuesLeft - 2
    currX = currX + 2
  end
  
%    \end{macrocode}
% \textit{Secondly}, two different foreground parts are drawn: at least one \texttt{full front} at the left and in the middle, and possibly one \texttt{half upper front} at the right.
%    \begin{macrocode}
  residuesLeft = feature.stop - feature.start
  currX = xLeft + 1.5
  while residuesLeft > 0 do
    if residuesLeft == 1 then
      tex.sprint(
        "\n\t\t\\def\\xRight{" ..
        dimToString((currX + 0.5) * xUnit) ..
        "}"
      )
      tex.sprint("\n\t\t\\def\\yMid{" .. dimToString(yMid * yUnit) .. "}")
      tex.sprint("\n\t\t\\pmbdomdrawfeature{helix/half upper front}")
    else
      tex.sprint("\n\t\t\\def\\xMid{" .. dimToString(currX * xUnit) .. "}")
      tex.sprint(
        "\n\t\t\\def\\yLower{" ..
        dimToString(yMid * yUnit - 1.5 * xUnit) ..
        "}"
      )
      tex.sprint("\n\t\t\\pmbdomdrawfeature{helix/full front}")
    end
    residuesLeft = residuesLeft - 2
    currX = currX + 2
  end
end

%    \end{macrocode}
% 
% \subsection{The \texorpdfstring{\texttt{SpecialKeys}}{SpecialKeys} Class}
% \label{ssc:DocDomLuaSpecialKeysClass}
% 
% The §SpecialKeys§ class contains three member variables: §disulfideKeys§ (a list of keys that indicate disulfide-like features, like \texttt{disulfide}), §featureStyles§ (a list of feature styles) and §printFunctions§ (a list of keys associated with a feature print function, like \texttt{alpha helix}). Furthermore, it provides methods to manipulate these fields.
% 
% The constructor §SpecialKeys:new§ generates a new §SpecialKeys§ object and initializes it with values from §parms§.
%    \begin{macrocode}
SpecialKeys = {}

function SpecialKeys:new(parms)
  parms = parms or {}
  local newSpecialKeys = {
    disulfideKeys = {},
    featureStyles = {},
    printFunctions = {}
  }
  
  for keyList, listContents in pairs(parms) do
    for key, value in pairs(listContents) do
      newSpecialKeys[keyList][key] = value
    end
  end
  
  setmetatable(newSpecialKeys, self)
  self.__index = self
  return newSpecialKeys
end

%    \end{macrocode}
% §SpecialKeys:setKeys§ sets a §value§ for a §key§ in the §keylist§. Possible values for §keyList§ are §"disulfideKeys"§, §"featureStyles"§ or §"printFunctions"§.
%    \begin{macrocode}
function SpecialKeys:setKeys(keylist, keys, value)
  for key in keys:gmatch("([^,]+)") do
    key = key:trim()
    self[keylist][key] = value
  end
end

%    \end{macrocode}
% 
% §SpecialKeys:setFeatureStyle§ parses the style list §style§ and associates it with a certain §key§. In Lua, a style list is an array of tables. Each table contains the fields §cycles§ and §style§. §cycles§ determines how often the §style§ (a string suitable for the mandatory argument of |\pgfmolbioset|) is to be used. In addition, an optional field §alias§ contains a reference to another key, if the current key is an alias of it (see below).
%    \begin{macrocode}
function SpecialKeys:setFeatureStyle(key, style)
  local newStyleList, styleCycles, styleContents
  
  newStyleList = {}
  while style ~= "" do
    styleCycles = 1
    if style:sub(1,1) == "{" then
      styleContents = style:match("%b{}")
      style = style:match("%b{}(.*)")
    elseif style:sub(1,1) == "*" then
      styleCycles, styleContents = style:match("%*(%d*)(%b{})")
      if styleCycles == "" then styleCycles = 1 end
      style = style:match("%*%d*%b{}(.*)")
    elseif style:sub(1,1) == "," or style:sub(1,1) == " " then
      style = style:match("[,%s]+(.*)")
      styleCycles, styleContents = nil, nil
    else
      styleContents = style:match("([^,]+),")
      if not styleContents then
        styleContents = style
        style = ""
      else
        style = style:match("[^,]+,(.*)")
      end
    end
    if styleCycles then
      table.insert(
        newStyleList,
        {cycles = styleCycles, style = styleContents}
      )
    end
  end
  self.featureStyles[key] = newStyleList
end

%    \end{macrocode}
% §SpecialKeys:aliasFeatureStyle§ sets the §alias§ field of a style list so that feature §newKey§ uses the same feature style as feature §oldKey§.
%    \begin{macrocode}
function SpecialKeys:aliasFeatureStyle(newKey, oldKey)
  self.featureStyles[newKey] = {alias = oldKey}
end

%    \end{macrocode}
% §SpecialKeys:getBaseKey§ returns either the name of §key§ itself or of its parent key if §key§ is an alias.
%    \begin{macrocode}
function SpecialKeys:getBaseKey(key)
  if self.featureStyles[key] then
    if self.featureStyles[key].alias then
      return self.featureStyles[key].alias
    end
  end
  return key
end

%    \end{macrocode}
% §SpecialKeys:clearKeys§ clears a §keylist§.
%    \begin{macrocode}
function SpecialKeys:clearKeys(keylist)
  self[keylist] = {}
end

%    \end{macrocode}
% §SpecialKeys:selectStyleFromList§ returns the §styleID§-th style from the style list associated with §key§. Firstly, the correct style list is selected.
%    \begin{macrocode}
function SpecialKeys:selectStyleFromList(key, styleID)
  local styleList

  if not self.featureStyles[key] then
    packageWarning(
      "Feature style `" ..
      key ..
      "' unknown, using `default'."
      )
    styleList = self.featureStyles.default
  elseif self.featureStyles[key].alias then
    styleList = self.featureStyles[self.featureStyles[key].alias]
  else
    styleList = self.featureStyles[key]
  end

%    \end{macrocode}
% Secondly, the method choses the appropriate style in the list.
%    \begin{macrocode}
  while true do
    for _, v in ipairs(styleList) do
      styleID = styleID - v.cycles
      if styleID < 1 then
        return v.style
      end
    end
  end
end

%    \end{macrocode}
%
% \subsection{The \texorpdfstring{\texttt{Protein}}{Protein} Class}
% \label{ssc:DocDomLuaProteinClass}
% 
% The §Protein§ class represents a domain diagram in Lua. Its member variables largely correspond to the keys of the \module{domains} module. In detail:
% \begin{itemize}
% 	\item §sequenceLength§: A value of §-1§ indicates that the sequence length has not been properly set.
% 	\item §ft§ is the feature table, i.\,e. an array of tables with the following fields:
% 	\begin{itemize}
% 		\item §key§: A string that equals the feature key.
% 		\item §start§: The start \dots
% 		\item §stop§: \dots\ and the end residue of the feature, both in \textit{absolute} numbering. (For the difference between absolute and relative numbering, see section~\ref{sec:DomGeneralLayout}.)
% 		\item §kvList§: A string containing comma-separated key-value pairs, which is passed to |\pgfmolbioset| immediately before the feature is drawn.
% 		\item §level§: The level of the feature (only relevant for disulfide-like features).
% 	\end{itemize}
% 	\item §residueNumbering§: An array of strings. The indices are absolute residue numbers, while the fields represent the corresponding relative residue numbers.
% 	\item §revResidueNumbering§: The inverse of §residueNumbering§ (i.\,e., a table of numbers).
% 	\item §rulerRange§: An array of tables. Each table represents one mark of the ruler and has the fields §pos§ (position in absolute residue numbers) and §number§ (relative number of the marked residue).
% 	\item §currentStyle§: A table whose field names equal feature keys. Each field denotes the index of the style that was last selected from that feature's style list.
% 	\item §includeDescription§: This boolean field remains uninitialized. Instead, it is directly set in \file{pgfmolbio.domains.tex} if the \module{convert} module is loaded and the user requests a string representation of a §Protein§ object (section~\ref{ssc:DocDomLuaTostring}).
% \end{itemize}
% 
% The constructor §Protein:new§ initializes the member variables with default values.
%    \begin{macrocode}
Protein = {}

function Protein:new()
  local newProtein = {
    name = "",
    sequenceLength = -1,
    ft = {},
    sequence = "",
    xUnit = stringToDim("0.5mm"),
    yUnit = stringToDim("6mm"),
    residuesPerLine = 250,
    residueRangeMin = 1,
    residueRangeMax = 100,
    residueNumbering = {},
    revResidueNumbering = {},
    baselineSkip = 3,
    rulerRange = {},
    defaultRulerStepSize = 50,
    showRuler = true,
    currentStyle = {},
    specialKeys = SpecialKeys:new()
  }
  setmetatable(newProtein, self)
  self.__index = self
  return newProtein
end

%    \end{macrocode}
% §Protein:toAbsoluteResidueNumber§ converts a string that either contains an absolute or relative residue number to an absolute residue number.
%    \begin{macrocode}
function Protein:toAbsoluteResidueNumber(value)
  local result = value:match("%b()")
  if result then
    result = tonumber(result:sub(2, -2))
  else
    result = self.revResidueNumbering[(value:gsub("[<>%?]", ""))]
  end
  if not result then
    packageError("Bad or missing start/end point value: " .. value)
  end
  return result
end

%    \end{macrocode}
% 
% \subsection{Uniprot and GFF Files}
% \label{ssc:DocDomLuaReadFiles}
% 
% §Protein:readUniprotFile§ reads the relevant parts of Uniprot file §filename§\footnote{For a detailed description of this format, see \url{http://web.expasy.org/docs/userman.html}.}.
%    \begin{macrocode}
function Protein:readUniprotFile(filename)
  local uniprotFile, errorMsg = io.open(filename, "r")
  if not uniprotFile then packageError(errorMsg) end

%    \end{macrocode}
% Each line in a Uniprot file starts with a line code consisting of two letters. This code determines the syntax of the remainder of the line.
%    \begin{macrocode}
  local sequence = {}
  local inSequence = false
  local featureTable = {}

  for currLine in uniprotFile:lines() do
    local lineCode = currLine:sub(1, 2)
    local lineContents = currLine:sub(3)
%    \end{macrocode}
% The \texttt{ID} line is the first line in a Uniprot file. It provides two relevant properties of the protein, namely its name and ints sequence length. For example, in the file \file{SampleUniprot.txt} (see section~\ref{sec:DomFileInput}), the \texttt{ID} line reads\\
% |ID   TestProtein  Reviewed;        200 AA.|\\
% which declares a protein with 200 residues called TestProtein.
%    \begin{macrocode}
    if lineCode == "ID" then
      local name, sequenceLength =
        lineContents:match("%s*(%S+)%s*%a+;%s*(%d+)%s*AA%.")
      self.name = name
      self.sequenceLength = tonumber(sequenceLength)
      self.residueRangeMax = self.sequenceLength
%    \end{macrocode}
% \texttt{FT} lines describe features of the protein (domains, disulfides, sugars etc.). The first line of a feature always contains its key (columns 6--13) and endpoints (columns 15--20 and 22--27, respectively). The description (columns 35--75) may span several lines, in which case the key columns of consecutive lines are empty. For instance,\\
% |FT   DOMAIN       10     40       Domain 1|\\
% declares a \texttt{DOMAIN} feature between residues 10 and 40 with description ``Domain 1''.
%    \begin{macrocode}
    elseif lineCode == "FT" then
      local key = currLine:sub(6, 13):trim()
      local start, stop, description =
        currLine:sub(15, 20), currLine:sub(22, 27), currLine:sub(35, 75)
      if key ~= "" then
        table.insert(featureTable, {
          key = key,
          start = "(" .. start .. ")",
          stop = "(" .. stop .. ")",
          description = description,
          style = "",
          kvList = ""
        })
      else
        featureTable[#featureTable].description =
          featureTable[#featureTable].description .. description
      end
%    \end{macrocode}
% The \texttt{SQ} line starts the sequence block. Each of the following sequence data lines lacks a line code and shows the amino acid sequence in one letter code, e.\,g.\\
% |SQ   SEQUENCE   200 AA;   22041 MW;  00A52FE2EC5431D9 CRC64;|\\
% |     MGSKRSVPSR HRSLTTYEVM FAVLFVILVA LCAGLIAVSW LSIQ| [\dots]
%    \begin{macrocode}
    elseif lineCode == "SQ" then
      inSequence = true
    elseif lineCode == "  " and inSequence then
      table.insert(sequence, (lineContents:gsub("%s+", "")))
%    \end{macrocode}
% The |\\| line terminates the Uniprot file.
%    \begin{macrocode}
    elseif lineCode == "\\\\" then
      break
    end
  end
%    \end{macrocode}
% After closing the file, features are converted to the proper format (section~\ref{ssc:DocDomLuaProteinClass}).
%    \begin{macrocode}
  uniprotFile:close()
  if next(sequence) then self.sequence = table.concat(sequence) end
  for _, v in ipairs(featureTable) do self:addFeature(v) end
end

%    \end{macrocode}
% §Protein:readGffFile§ reads the relevant parts of General Feature Format file §filename§\footnote{For a detailed description of this format, see \url{http://http://www.sanger.ac.uk/resources/software/gff/spec.html}.}.
%    \begin{macrocode}
function Protein:readGffFile(filename)
  local gffFile, errorMsg = io.open(filename, "r")
  local lineContents, fields, lineNumber
  
  if not gffFile then packageError(errorMsg) end
%    \end{macrocode}
% Each line in a \file{gff} file describes a feature and consists of up to 9 tabulator-separated fields, of which only fields 3 (key), 4 (start) and 5 (end) are required for the \module{domains} module. Everything following the comment sign (|#|) on a line is ignored.
%    \begin{macrocode}
  lineNumber = 1
  for currLine in gffFile:lines() do
    lineContents = currLine:gsub("#.*$", "")
    fields = {}
    if lineContents ~= "" then
      for currField in lineContents:gmatch("([^\t]+)") do
        table.insert(fields, currField)
      end
      if not fields[5] then
        packageError("Bad line (" .. lineNumber .. ") in gff file '" ..
          filename .. "':\n" .. currLine)
        break
      end
      self:addFeature{
        key = fields[3],
        start = "(" .. fields[4] .. ")",
        stop = "(" .. fields[5] .. ")",
        description = fields[9] or "",
        style = "",
        kvList = ""
      }
    end
    lineNumber = lineNumber + 1
  end
  gffFile:close()
end

%    \end{macrocode}
% 
% \subsection{Getter and Setter Methods}
% \label{ssc:DocDomLuaParameters}
% 
% §Protein:getParameters§ informs \TeX\ of the protein name, sequence and sequence length. This method is called after reading a Uniprot file (section~\ref{ssc:DocDomTexAddingFeatures}).
%    \begin{macrocode}
function Protein:getParameters()
  tex.sprint(
    "\\pgfmolbioset[domains]{name={" ..
    self.name ..
    "},sequence={" ..
    self.sequence ..
    "},sequence length=" ..
    self.sequenceLength ..
    "}"
  )
end

%    \end{macrocode}
% §Protein:setParameters§ passes options from the \module{domains} module to the Lua script. Each field of the table §keyHash§ is named after a §Protein§ attribute and represents a function that receives one string parameter (the value of a \LaTeX\ key).
%    \begin{macrocode}
function Protein:setParameters(newParms)
  local keyHash = {
%    \end{macrocode}
% §keyHash.sequenceLength§ checks for an invalid sequence length.
%    \begin{macrocode}
    sequenceLength = function(v)
      v = tonumber(v)
      if not v then return self.sequenceLength end
      if v < 1 then
        packageError("Sequence length must be larger than zero.")
      end
      return v
    end,
%    \end{macrocode}
% §keyHash.residueNumbering§ generates the residue numbering array and its inverse (described in section~\ref{ssc:DocDomLuaProteinClass}).
%    \begin{macrocode}
    residueNumbering = function(v)
      local ranges = {}
      local start, startNumber, startLetter, stop
      self.revResidueNumbering = {}
      if v:trim() == "auto" then
        for i = 1, self.sequenceLength do
          table.insert(ranges, tostring(i))
        end
      else --example list: `1-4,5,6A-D'
        for _, value in ipairs(v:explode(",+")) do
          value = value:trim()
          start, stop = value:match("(%w*)%s*%-%s*(%w*)$")
          if not start then
            start = value:match("(%w*)")
          end
          if not start or start == "" then --invalid range
            packageError("Unknown residue numbering range: " .. value)
          end
          if stop then
            if tonumber(start) and tonumber(stop) then
              --process range `1-4'
              for currNumber = tonumber(start), tonumber(stop) do
                table.insert(ranges, tostring(currNumber))
              end
            else --process range `6A-D'
              startNumber, startLetter = start:match("(%d*)(%a)")
              stop = stop:match("(%a)")
              for currLetter = startLetter:byte(), stop:byte() do
                table.insert(ranges,
                  startNumber .. string.char(currLetter))
              end
            end
          else --process range `5'
            table.insert(ranges, start)
          end
        end
      end
      for i, value in ipairs(ranges) do
        if self.revResidueNumbering[value] then
          packageError("The range value " .. value ..
            " appears more than once.")
        else
          self.revResidueNumbering[value] = i
        end
      end
      return ranges
    end,
%    \end{macrocode}
% §keyHash.residueRange§ sets the residue range, treating possible errors.
%    \begin{macrocode}
    residueRange = function(v)
      local num
      local residueRangeMin, residueRangeMax =
        getRange(v:trim(), "^([%w%(%)]+)%s*%-", "%-%s*([%w%(%)]+)$")
      if residueRangeMin == "auto" then
        self.residueRangeMin = 1
      else
        num = residueRangeMin:match("%b()")
        if num then
          self.residueRangeMin = tonumber(num:sub(2, -2))
        elseif self.revResidueNumbering[residueRangeMin] then
          self.residueRangeMin = self.revResidueNumbering[residueRangeMin]
        else
          packageError("Invalid residue range: " .. residueRangeMin)
        end
      end
      
      if residueRangeMax == "auto" then
        self.residueRangeMax = self.sequenceLength
      else
        num = residueRangeMax:match("%b()")
        if num then
          self.residueRangeMax = tonumber(num:sub(2, -2))
        elseif self.revResidueNumbering[residueRangeMax] then
          self.residueRangeMax = self.revResidueNumbering[residueRangeMax]
        else
          packageError("Invalid residue range: " .. residueRangeMax)
        end
      end
      
      if self.residueRangeMin >= self.residueRangeMax then
        packageError("Residue range is smaller than 1.")
      end
    end,
%    \end{macrocode}
% The following fields map to functions already defined.
%    \begin{macrocode}
    defaultRulerStepSize = tonumber,
    name = tostring,
    sequence = tostring,
    xUnit = stringToDim,
    yUnit = stringToDim,
    residuesPerLine = tonumber,
    baselineSkip = tonumber,
%    \end{macrocode}
% §keyHash.rulerRange§ sets the ruler range, treating possible errors and inconsistencies (for example, if the upper ruler range exceeds the upper residue range).
%    \begin{macrocode}
    rulerRange = function(v)
      local num
      local ranges = {}
      local rulerRangeMin, rulerRangeMax, rulerRangeStep
      for _, value in ipairs(v:explode(",+")) do
        rulerRangeMin, rulerRangeMax, rulerRangeStep =
          getRange(value:trim(), "^([%w%(%)]+)",
            "%-%s*([%w%(%)]+)", "step%s*(%d+)$")
        
        if rulerRangeMin == "auto" then
          rulerRangeMin = self.residueRangeMin
        else
          num = rulerRangeMin:match("%b()")
          if num then
            rulerRangeMin = tonumber(num:sub(2, -2))
          elseif self.revResidueNumbering[rulerRangeMin] then
            rulerRangeMin = self.revResidueNumbering[rulerRangeMin]
          else
            packageError("Invalid lower ruler range: " .. rulerRangeMin)
          end
        end
        
        if rulerRangeMax then
          if rulerRangeMax == "auto" then
            rulerRangeMax = self.residueRangeMax
          else
            num = rulerRangeMax:match("%b()")
            if num then
              rulerRangeMax = tonumber(num:sub(2, -2))
            elseif self.revResidueNumbering[rulerRangeMax] then
              rulerRangeMax = self.revResidueNumbering[rulerRangeMax]
            else
              packageError("Invalid upper ruler range: " .. rulerRangeMax)
            end
          end
          
          if rulerRangeMin >= rulerRangeMax then
            packageError("Ruler range is smaller than 1.")
          end
          if rulerRangeMin < self.residueRangeMin then
            rulerRangeMin = self.residueRangeMin
            packageWarning(
              "Lower ruler range is smaller than" ..
              "lower residue range. It was adjusted to " ..
              rulerRangeMin .. "."
            )
          end
          if rulerRangeMax > self.residueRangeMax then
            rulerRangeMax = self.residueRangeMax
            packageWarning(
              "Upper ruler range exceeds" ..
              "upper residue range. It was adjusted to " ..
              rulerRangeMax .. "."
            )
          end
        else
          rulerRangeMax = rulerRangeMin
        end
        rulerRangeStep = tonumber(rulerRangeStep)
          or self.defaultRulerStepSize
        
        for i = rulerRangeMin, rulerRangeMax, rulerRangeStep do
          table.insert(
            ranges,
            {pos = i, number = self.residueNumbering[i]}
          )
        end
      end
      return ranges
    end,
%    \end{macrocode}
% §keyHash.showRuler§ determines if the ruler is visible.
%    \begin{macrocode}
    showRuler = function(v)
      if v == "true" then return true else return false end
    end
  }
%    \end{macrocode}
% We iterate over all fields in the argument of §setParameters§. If a field of the same name exists in §keyHash§, we call this field with the value of the corresponding field in §newParms§ as parameter.
%    \begin{macrocode}
  for key, value in pairs(newParms) do
    if keyHash[key] then
      self[key] = keyHash[key](value)
      if pgfmolbio.errorCatched then return end
    end
  end
end

%    \end{macrocode}
% 
% \subsection{Adding Feature}
% \label{ssc:DocDomLuaAddFeature}
% 
% §Protein:addFeature§ converts raw feature information to the format of §ft§ fields (described in section~\ref{ssc:DocDomLuaProteinClass}). Firstly, the method determines the index of the style that should be used for the current feature.
%    \begin{macrocode}
function Protein:addFeature(newFeature)
  local baseKey, ftEntry
  
  baseKey = self.specialKeys:getBaseKey(newFeature.key)
  if self.currentStyle[baseKey] then
    self.currentStyle[baseKey] = self.currentStyle[baseKey] + 1
  else
    self.currentStyle[baseKey] = 1
  end

%    \end{macrocode}
% Then, a new field for the feature table is set up.
%    \begin{macrocode}
  ftEntry = {
    key = newFeature.key,
    start = self:toAbsoluteResidueNumber(newFeature.start),
    stop = self:toAbsoluteResidueNumber(newFeature.stop),
    kvList = "style={" ..
      self.specialKeys:selectStyleFromList(baseKey,
        self.currentStyle[baseKey]) .. "}",
    level = newFeature.level or nil
  }
%    \end{macrocode}
% Finally, the key-value list §kvList§ is modified (if applicable) and the new field is inserted into §ft§.
%    \begin{macrocode}
  if newFeature.kvList ~= "" then
    ftEntry.kvList = ftEntry.kvList .. "," .. newFeature.kvList
  end
  if newFeature.description then
    ftEntry.kvList = ftEntry.kvList ..
      ",description={" .. newFeature.description .. "}"
    ftEntry.description = newFeature.description
  end
  table.insert(self.ft, newFeature.layer or #self.ft + 1, ftEntry)
end

%    \end{macrocode}
% 
% \subsection{Calculate Disulfide Levels}
% \label{ssc:DocDomLuaDisulfideLevels}
% 
% §Protein:calculateDisulfideLevels§ arranges disulfide-like features in non-\hskip0ptoverlapping levels.
%    \begin{macrocode}
function Protein:calculateDisulfideLevels()
  if pgfmolbio.errorCatched then return end
  local disulfideGrid, currLevel, levelFree
  disulfideGrid = {}
  
  for i, v in ipairs(self.ft) do
    if self.specialKeys.disulfideKeys[v.key] then
%    \end{macrocode}
% If the §level§ field of a disulfide-like feature is already specified, it overrides the automatic mechanism of level determination. This may lead to clashes.
%    \begin{macrocode}
      if v.level then
        if not disulfideGrid[v.level] then
          disulfideGrid[v.level] = {}
        end
        for currPos = v.start, v.stop do
          disulfideGrid[v.level][currPos] = true
        end
%    \end{macrocode}
% Otherwise, the algorithm looks for the first free level (starting at level 1), i.\,e. the first level the feature may occupy without clashing with another one. (1) If the level currently checked already exists, it has been created by a previous disulfide-like feature. In this case, it is considered free if the previous feature does not overlap with the current one.
%    \begin{macrocode}
      else
        currLevel = 1
        repeat
          levelFree = true
          if disulfideGrid[currLevel] then
            for currPos = v.start, v.stop do
              levelFree = levelFree
                and not disulfideGrid[currLevel][currPos]
            end
            if levelFree then
              self.ft[i].level = currLevel
              for currPos = v.start, v.stop do
                disulfideGrid[currLevel][currPos] = true
              end
            end
%    \end{macrocode}
% (2) If the level currently checked does not exist, it must be free.
%    \begin{macrocode}
          else
            self.ft[i].level = currLevel
            disulfideGrid[currLevel] = {}
            for currPos = v.start, v.stop do
              disulfideGrid[currLevel][currPos] = true
            end
            levelFree = true
          end
          currLevel = currLevel + 1
        until levelFree == true
      end
    end
  end
end

%    \end{macrocode}
% 
% \subsection{Print Domains}
% \label{ssc:DocDomLuaPrintTikzDomains}
% 
% §Protein:printTikzDomains§ is the heart of the Lua script, since it converts a §Protein§ object to \TeX\ code.
%    \begin{macrocode}
function Protein:printTikzDomains()
  if pgfmolbio.errorCatched then return end
  local xLeft, xMid, xRight, yMid, xLeftClip, xRightClip,
    currLine, residuesLeft, currStyle
  
%    \end{macrocode}
% \paragraph{(1) Features (excluding \texttt{other/ruler} and \texttt{other/name})} For each feature in the feature table, we first calculate its coordinates (§xLeft§, §xMid§, §xRight§ and §yMid§) and clipped areas (§xLeftClip§, §xRightClip§).
%    \begin{macrocode}
  for _, currFeature in ipairs(self.ft) do
    currLine = 0
    xLeft = currFeature.start - self.residueRangeMin -
      currLine * self.residuesPerLine + 1
    while xLeft > self.residuesPerLine do
      xLeft = xLeft - self.residuesPerLine
      currLine = currLine + 1
    end
    xLeft = xLeft - 1
    xRight = currFeature.stop - self.residueRangeMin -
      currLine * self.residuesPerLine + 1
    residuesLeft = self.residueRangeMax - self.residueRangeMin -
      currLine * self.residuesPerLine + 1
    xLeftClip = stringToDim("-5cm")
    xRightClip = self.residuesPerLine * self.xUnit
    
    if currFeature.start <= self.residueRangeMax
        and currFeature.stop >= self.residueRangeMin then
      repeat
        if residuesLeft <= self.residuesPerLine then
          if residuesLeft < xRight then
            xRightClip = residuesLeft * self.xUnit
          else
            xRightClip = xRight * self.xUnit + stringToDim("5cm")
          end
        else
          if xRight <= self.residuesPerLine then
            xRightClip = xRight * self.xUnit + stringToDim("5cm")
          end
        end
        if xLeft < 0 then xLeftClip = stringToDim("0cm") end
        
        xMid = (xLeft + xRight) / 2
        yMid = -currLine * self.baselineSkip
%    \end{macrocode}
% The current feature is extended by any level and sequence information present.
%    \begin{macrocode}
        if currFeature.level then
          currFeature.kvList = currFeature.kvList ..
            ",level=" .. currFeature.level
        end
        currFeature.sequence =
          self.sequence:sub(currFeature.start, currFeature.stop)
        
%    \end{macrocode}
% Each feature appears within its own |scope|. A |pgfinterruptboundingbox| ensures that the bounding box of the picture ignores the feature, since the |\clip| macro would enlarge it too much. Auxiliary macros for |\setfeatureshape| are defined (section~\ref{sec:DomFeatureStylesAndShapes}).
%    \begin{macrocode}
        tex.sprint("\n\t\\begin{scope}\\begin{pgfinterruptboundingbox}")
        tex.sprint("\n\t\t\\def\\xLeft{" ..
          dimToString(xLeft * self.xUnit) .. "}")
        tex.sprint("\n\t\t\\def\\xMid{" ..
          dimToString(xMid * self.xUnit) .. "}")
        tex.sprint("\n\t\t\\def\\xRight{" ..
          dimToString(xRight * self.xUnit) .. "}")
        tex.sprint("\n\t\t\\def\\yMid{" ..
          dimToString(yMid * self.yUnit) .. "}")
        tex.sprint("\n\t\t\\def\\featureSequence{" ..
          currFeature.sequence .. "}")
        tex.sprint(
          "\n\t\t\\clip (" ..
          dimToString(xLeftClip) ..
          ", \\yMid + " ..
          dimToString(stringToDim("10cm")) ..
          ") rectangle (" ..
          dimToString(xRightClip) ..
          ", \\yMid - " ..
          dimToString(stringToDim("10cm")) ..
          ");"
        )
        tex.sprint(
          "\n\t\t\\pgfmolbioset[domains]{" ..
          currFeature.kvList ..
          "}"
        )
%    \end{macrocode}
% We invoke either the print function associated with the current feature or directly call |\pmbdomdrawfeature|. Afterwards, we close both surrounding environments.
%    \begin{macrocode}
        if self.specialKeys.printFunctions[currFeature.key] then
          self.specialKeys.printFunctions[currFeature.key](
            currFeature, xLeft, xRight, yMid, self.xUnit, self.yUnit)
        else
          tex.sprint("\n\t\t\\pmbdomdrawfeature{" ..
            currFeature.key .. "}")
        end
        tex.sprint("\n\t\\end{pgfinterruptboundingbox}\\end{scope}")
        
%    \end{macrocode}
% Calculate coordinates for the next line of the feature.
%    \begin{macrocode}
        currLine = currLine + 1
        xLeft = xLeft - self.residuesPerLine
        xRight = xRight - self.residuesPerLine
        residuesLeft = residuesLeft - self.residuesPerLine
      until xRight < 1 or residuesLeft < 1
    end
  end
  
%    \end{macrocode}
% \paragraph{(2) Feature \texttt{other/ruler}} The ruler requires special treatment, buth the algorithm is actually simple: For each marker, calculate its coordinates, select its style and print it.
%    \begin{macrocode}
  if self.showRuler then
    currStyle = 1
    tex.sprint("\n\t\\begin{scope}")
    for _, currRuler in ipairs(self.rulerRange) do
      currLine = 0
      xMid = currRuler.pos - self.residueRangeMin -
        currLine * self.residuesPerLine + 1
      while xMid > self.residuesPerLine do
        xMid = xMid - self.residuesPerLine
        currLine = currLine + 1
      end
      xMid = xMid - 0.5
      yMid = -currLine * self.baselineSkip
      tex.sprint(
        "\n\t\t\\pgfmolbioset[domains]{current style/.style={" ..
        self.specialKeys:selectStyleFromList("other/ruler", currStyle) ..
        "}}"
      )
      tex.sprint("\n\t\t\t\\def\\xMid{" ..
        dimToString(xMid * self.xUnit) .. "}")
      tex.sprint("\n\t\t\t\\let\\xLeft\\xMid\\let\\xRight\\xMid")
      tex.sprint("\n\t\t\t\\def\\yMid{" ..
        dimToString(yMid * self.yUnit) .. "}")
      tex.sprint("\n\t\t\t\\def\\residueNumber{" ..
        currRuler.number .. "}")
      tex.sprint("\n\t\t\t\\pmbdomdrawfeature{other/ruler}")
      currStyle = currStyle + 1
    end
    tex.sprint("\n\t\\end{scope}")
  end
  
%    \end{macrocode}
% \paragraph{(3) Feature \texttt{other/name}} Similarly, we calculate the coordinates of the name and print it.
%    \begin{macrocode}
  xMid =
    math.min(
      self.residuesPerLine,
      self.residueRangeMax - self.residueRangeMin + 1
    ) / 2
  tex.sprint("\n\t\\begin{scope}")
  tex.sprint(
    "\n\t\t\\pgfmolbioset[domains]{current style/.style={" ..
    self.specialKeys:selectStyleFromList("other/name", 1) ..
    "}}"
  )
  tex.sprint("\n\t\t\\def\\xLeft{0mm}")
  tex.sprint("\n\t\t\\def\\xMid{" .. dimToString(xMid * self.xUnit) .. "}")
  tex.sprint("\n\t\t\\def\\xRight{" ..
    dimToString(self.residuesPerLine * self.xUnit) .. "}")
  tex.sprint("\n\t\t\\def\\yMid{0mm}")
  tex.sprint("\n\t\t\\pmbdomdrawfeature{other/name}")
  tex.sprint("\n\t\\end{scope}")
  
%    \end{macrocode}
% \paragraph{(4) Set bounding box} The bounding box is determined manually in order to prevent excessive enlargement due to clipping. The top left corner of the bounding box is the coordinate (|enlarge left|, |enlarge top|).
%    \begin{macrocode}
  tex.sprint(
    "\n\t\\pmbprotocolsizes{" ..
    "\\pmbdomvalueof{enlarge left}}{\\pmbdomvalueof{enlarge top}}"
  )
%    \end{macrocode}
% The $x$-coordinate of its right border is the largest line width plus the value of |enlarge right|. The $y$-coordinate of its bottom border is that of the lowermost line plus the value of |enlarge bottom|.
%    \begin{macrocode}
  currLine =
    math.ceil(
      (self.residueRangeMax - self.residueRangeMin + 1) /
        self.residuesPerLine
    ) - 1
  xRight =
    math.min(
      self.residuesPerLine,
      self.residueRangeMax - self.residueRangeMin + 1
    )
  tex.sprint(
    "\n\t\\pmbprotocolsizes{" ..
    dimToString(xRight * self.xUnit) ..
    " + \\pmbdomvalueof{enlarge right}}{" ..
    dimToString(-currLine * self.baselineSkip * self.yUnit) .. 
    " + \\pmbdomvalueof{enlarge bottom}}"
  )
end

%    \end{macrocode}
% 
% \subsection{Converting a \texorpdfstring{\texttt{Protein}}{Protein} to a String}
% \label{ssc:DocDomLuaTostring}
% 
% §Protein:__tostring§ is required by the \module{convert} module and returns a |pmbdomains| environment that contains all the information stored in the §Protein§ object (section~\ref{sec:ConDomains}). Firstly, we start the environment.
%    \begin{macrocode}
function Protein:__tostring()
  local result = {}
  local currLine
  
  currLine = "\\begin{pmbdomains}\n\t\t[name={" ..
    self.name ..
    "}"
  if self.sequence ~= "" then
    currLine = currLine ..
      ",\n\t\tsequence=" ..
      self.sequence
  end
  currLine = currLine .. 
    "]{" ..
    self.sequenceLength ..
    "}"
  table.insert(result, currLine)

%    \end{macrocode}
% Afterwards, each feature in the feature table is converted to an |\addfeature| macro. Note the use of the §includeDescription§ field (described in section~\ref{ssc:DocDomLuaProteinClass}).
%    \begin{macrocode}
  for i, v in ipairs(self.ft) do
    if v.key ~= "other/main chain" then
      currLine = "\t\\addfeature"
      if self.includeDescription and v.description then
        currLine =
          currLine ..
          "[description={" ..
          v.description ..
          "}]"
      end
      currLine =
        currLine ..
        "{" ..
        v.key ..
        "}{" ..
        v.start ..
        "}{" ..
        v.stop ..
        "}"
      table.insert(result, currLine)
    end
  end
%    \end{macrocode}
% Finally, we close the environment.
%    \begin{macrocode}
  table.insert(result,
    "\\end{pmbdomains}"
  )
  return table.concat(result, "\n")
end
%    \end{macrocode}
% 
% \iffalse
%</pmb-dom-lua>
%<*pmb-con-tex>
% \fi
% 
% 
% 
% \section{\texorpdfstring{\file{pgfmolbio.convert.tex}}{pgfmolbio.convert.tex}}
% \label{sec:DocConTex}
% 
% \def\ydoclistingssettings{\lstset{style=latex-doc}}\setcounter{lstnumber}{1}
% The code for the \module{convert} module is short: We only need to declare four options and set |\pdfdraftmode| to 1 in order to prevent pdf\TeX\ from producing any \file{pdf} output.
%    \begin{macrocode}
\pdfdraftmode1

\pgfkeyssetvalue{/pgfmolbio/convert/output file name}{(auto)}
\pgfkeyssetvalue{/pgfmolbio/convert/output file extension}{tex}

\pgfmolbioset[convert]{%
  output code/.is choice,
  output code/tikz/.code=\pmb@con@outputtikzcodetrue,
  output code/pgfmolbio/.code=\pmb@con@outputtikzcodefalse,
  output code=tikz
}

\pgfmolbioset[convert]{%
  include description/.is if=pmb@con@includedescription,
  include description
}
%    \end{macrocode}
%
% \iffalse
%</pmb-con-tex>
% \fi
%
% \Finale
\endinput