summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/source/lualatex/pgfmolbio/pgfmolbio.dtx
blob: ef1a7e930d6424399dafd7ad2aa01265a38cf2a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
% \iffalse meta-comment
%
% Copyright (C) 2011 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>\ProvidesPackage{pgfmolbio}[2011/09/20 v0.1 Molecular biology graphs with TikZ]
%<pgfmolbio>\NeedsTeXFormat{LaTeX2e}[1999/12/01]
%<pmb-chr>\ProvidesFile{pgfmolbio.chromatogram.tex}[2011/09/20 v0.1 SCF Chromatograms]
%<pmb-chr-lua>module("pgfmolbio.chromatogram", package.seeall)
%
%<*driver>
\documentclass[captions=tableheading,cleardoublepage=empty,titlepage=false]{scrreprt}
	\setkomafont{title}{\rmfamily\bfseries}
	\addtokomafont{sectioning}{\rmfamily}

\usepackage[english]{babel}
	\frenchspacing
\usepackage[hdivide={2cm,*,5cm}]{geometry}
\usepackage{fontspec}
\usepackage[dvipsnames]{xcolor}
\usepackage{array,booktabs}

\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]|%
		\lstMakeShortInline[style=lua-doc,basicstyle=\ttfamily,frame=none]§%
	}
	\makeatletter
	\def\DescribeOption#1#2{%
		\gdef\OptDefault{\textcolor{black!50}{Default:}~\texttt{#2}}%
		\DescribeMacros
		\let\DescribeMacros\y@egroup
		\optionalon
		\def\after@Macro@args{\y@egroup\PrintOptions\endgroup}%
		\hbox\y@bgroup
		\texttt{\textcolor{opt}{#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
	}
	\makeatother
	\def\ometa#1{{\optional\meta{#1}}}
	\lstdefinestyle{exampleextract}{gobble=2}
	\def\ydoclistingssettings{\lstset{style=latex-expl}}
	\definecolor{opt}{named}{OliveGreen}

\lstdefinestyle{latex-expl}{
	language=[AlLaTeX]TeX,
	columns=fullflexible,
	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},
	emphstyle=\color{opt},
	commentstyle=\itshape\color{black!50},
	morekeywords={tikzpicture},
	moretexcs=[1]{
		@empty,@ifundefined,definecolor,directlua,draw,
		pgfkeys,pgfkeysdef,pgfqkeys,ProcessOptions,RequireLuaModule,
		useasboundingbox,usetikzlibrary
	},
	moretexcs=[2]{
		@pmb@chr@getkey,@pmb@chr@keydef,@pmb@chr@stylekeydef,pmb@chr@tikzpicturefalse,pmb@chr@tikzpicturetrue,
		@pmb@getkey,@tempa,ifpmb@chr@showbasenumbers,ifpmb@chr@tikzpicture,
		ifpmb@loadmodule@chromatogram,pgfmolbioset,pmb@loadmodule@chromatogramtrue,pmbchromatogram
	},
	emph={
		A,base,bases,baseline,C,canvas,coordinate,
		distance,drawn,format,function,G,height,
		label,labels,length,line,number,numbers,per,
		probability,probabilities,range,sample,samples,show,
		skip,string,style,T,text,tick,ticks,trace,traces,unit,x,y
	}
}

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

\lstdefinestyle{lua-doc}{
	language=lua,
	columns=fullflexible,
	tabsize=2,
	basicstyle=\ttfamily\small\color{ForestGreen},
	keywordstyle=\color{MidnightBlue},
	keywordstyle=[2]\color{ProcessBlue},
	stringstyle=\color{Red},
	identifierstyle=\color{Black},
	emphstyle=\color{Violet},
	showstringspaces=false,
	numbers=none,
	breaklines,
	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,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,
		rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,
		type,unpack,_VERSION,xpcall},
	morekeywords=[2]{coroutine.create,coroutine.resume,coroutine.running,
		coroutine.status,coroutine.wrap,coroutine.yield},
	morekeywords=[2]{module,require,package.cpath,package.load,package.loaded,
		package.loaders,package.loadlib,package.path,package.preload,
		package.seeall},
	morekeywords=[2]{string.byte,string.char,string.dump,string.find,
		string.format,string.gmatch,string,gsub,string.len,string.lower,
		string.match,string.rep,string.reverse,string.sub,string.upper},
	morekeywords=[2]{table.concat,table.insert,table.maxn,table.remove,
	table.sort},
	morekeywords=[2]{math.abs,math.acos,math.asin,math.atan,math.atan2,
		math.ceil,math.cos,math.cosh,math.deg,math.exp,math.floor,math.fmod,
		math.frexp,math.huge,math.ldexp,math.log,math.log10,math.max,math.min,
		math.modf,math.pi,math.pow,math.rad,math.random,math.randomseed,math.sin,
		math.sinh,math.sqrt,math.tan,math.tanh},
	morekeywords=[2]{io.close,io.flush,io.input,io.lines,io.open,io.output,
		io.popen,io.read,io.tmpfile,io.type,io.write,file:close,file:flush,
		file:lines,file:read,file:seek,file:setvbuf,file: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.error,tex.sprint},
	emph={baseToSampleIndex,evaluateScfFile,findBasesInStr,
		getMinMaxProbability,getRange,printTikzChromatogram,
		readInt,readScfFile,setParameters,stdProbStyle},
	sensitive=true,
	alsoletter={.:0123456789},
	morecomment=[l]{--},
	morecomment=[s]{--[[}{]]--},
	morestring=[b]{"},
	morestring=[d]{'}
}

\lstset{style=latex-expl}

\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}}

\usepackage[chromatogram]{pgfmolbio}
\usetikzlibrary{decorations.pathreplacing}

\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{175}
% 
% \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 one module, which creates DNA sequencing chromatograms from files in standard chromatogram format (\file{scf}). Since \file{scf} files are binary, \pkg{pgfmolbio} relies on the Lua\TeX\ engine for converting information from these files into \TikZ\ drawing commands.
% \end{abstract}
%
% \tableofcontents
%
%
% \chapter{Introduction}
% \pagenumbering{arabic}
% 
% 
% \section{About \texorpdfstring{\pkg{pgfmolbio}}{pgfmolbio}}
% 
% 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, plasmid maps, protein domain diagrams 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 its first development release, \pkg{pgfmolbio} is able to read DNA sequencing files in standard chromatogram format (\file{.scf}) and draw the corresponding chromatogram using routines from \pkg{pgf}'s \TikZ\ frontend. In order to convert the data from the \file{scf} input file to an image, \pkg{pgfmolbio} relies on the Lua scripting language implemented in Lua\TeX. Consequently, the package will not work with traditional engines like pdf\TeX.
% 
% 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}
% 
% Before you consider using \pkg{pgfmolbio}, please make sure that both your Lua\TeX\ (at least 0.70.1) 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, only one \ometa{module} is available: \opt*{chromatogram} allows you to draw DNA sequencing chromatograms as obtained by the Sanger sequencing method. Thus, the only sensible way of including the package is currently |\usepackage[chromatogram]{pgfmolbio}|.
% 
% \DescribeMacro\pgfmolbioset[<module>]{<key-value list>}
% The \meta{key-value list} in the mandatory argument of this command allows you to fine-tune the graphs produced by each {\optional\meta{module}} of \pkg{pgfmolbio}. The possible keys are described in the sections on the respective modules.
%
%
%
%
% \chapter{The \texorpdfstring{\opt{chromatogram}}{chromatogram} module}
% 
% 
% \section{Overview}
% 
% The \opt{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:DocLuaScf}). Note that \pkg{pgfmolbio} only supports \file{scf} version 3.00.
% 
% 
% \section{Drawing Chromatograms}
% 
% \DescribeMacro\pmbchromatogram[<key-value list>]{<scf file>}
% The \opt{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:tikzpicture}). 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:tikzpicture}
% \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:DisplayingParts}
% 
% \DescribeOption{sample range}{1 to 500 step 1}<lower>' to '<upper>[' step '<interval>]\relax
% |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 |to| 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:LimitsSamplePoints}). 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:LimitsSamplePoints}
% \begin{examplecode}
% \pmbchromatogram[sample range=200 to 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:LimitsSamplePoints} and~\ref{exa:LimitsBases} to see the difference.
% \end{enumerate}
% The optional third part of the value for |sample range| orders the package to draw every \ometa{interval}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:SampleStep}). Nevertheless, the key may be especially useful while optimizing the layout of complex chromatograms.
% 
% \begin{exampletable}[p]
% \caption{}
% \label{exa:LimitsBases}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base60
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \begin{exampletable}[p]
% \caption{}
% \label{exa:SampleStep}
% \pgfmolbioset[chromatogram]{canvas height=1cm}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 20 to base 50 step 1
% 	]{SampleScf.scf}
% \end{examplecode}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 20 to base 50 step 2
% 	]{SampleScf.scf}
% \end{examplecode}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 20 to base 50 step 4
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{General Layout}
% 
% \DescribeOption{x unit}{0.2mm}<dimension>
% \DescribeOption{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:xyunit} illustrates how you can enlarge a chromatogram twofold by doubling these values.
% \begin{exampletable}
% \caption{}
% \label{exa:xyunit}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		x unit=0.4mm,
% 		y unit=0.02mm
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}

% \DescribeOption{samples per line}{500}<number>
% \DescribeOption{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:SamplesPerLine}, 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:SamplesPerLine}
% \begin{examplecode}
% \begin{tikzpicture}%
% 		[decoration=brace]
% 	\pmbchromatogram[%
% 			sample range=401 to 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{canvas style}{draw=none, fill=none}<style>\newpage
% \DescribeOption{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:CanvasStyle}, we decrease the height of the canvas and color it light gray.
% \begin{exampletable}
% \caption{}
% \label{exa:CanvasStyle}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		canvas style={draw=none, fill=black!10},
% 		canvas height=1.6cm
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{Traces}
% 
% \DescribeOption{trace A style}{pmbTraceGreen}<style>
% \DescribeOption{trace C style}{pmbTraceBlue}<style>
% \DescribeOption{trace G style}{pmbTraceBlack}<style>
% \DescribeOption{trace T style}{pmbTraceRed}<style>
% \DescribeOption{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 |trace style| changes all styles simultaneously. The standard styles simply color the traces; Table~\ref{tab:pmbColors} lists the color specifications.\par
% In Example~\ref{exa:TraceStyle}, 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}
% \caption{}
% \label{exa:TraceStyle}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		trace style={thin},
% 		trace A style={dashdotted, green},
% 		trace T style={thick, dashed, purple}
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \begin{table}[b]
% 	\centering
% 	\caption{Colors defined by the \opt{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}
%
% \newpage
% \DescribeOption{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:TracesDrawn} only draws the cytosine and guanine traces.
% \begin{exampletable}
% \caption{}
% \label{exa:TracesDrawn}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		traces drawn=CG
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{Ticks}
% 
% \DescribeOption{tick A style}{thin, pmbTraceGreen}<style>
% \DescribeOption{tick C style}{thin, pmbTraceBlue}<style>
% \DescribeOption{tick G style}{thin, pmbTraceBlack}<style>
% \DescribeOption{tick T style}{thin, pmbTraceRed}<style>
% \DescribeOption{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 |tick style| changes all styles simultaneously. Example~\ref{exa:TickStyle} illustrates how one can draw thick ticks, which are red if they indicate a cytosine peak.
% \begin{exampletable}
% \caption{}
% \label{exa:TickStyle}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		tick style={thick},
% 		tick C style={red, thick}
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{tick length}{1mm}<dimension>
% This key determines the length of each tick. In Example~\ref{exa:TickLength}, the ticks are twice as long as usual.
% \begin{exampletable}
% \caption{}
% \label{exa:TickLength}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		tick length=2mm
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{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:TicksDrawn} only displays the cytosine and guanine ticks.
% \begin{exampletable}
% \caption{}
% \label{exa:TicksDrawn}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		ticks drawn=CG
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{Base Labels}
% 
% \DescribeOption{base label A text}{\cs{strut} A}<text>
% \DescribeOption{base label C text}{\cs{strut} C}<text>
% \DescribeOption{base label G text}{\cs{strut} G}<text>
% \DescribeOption{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:BaseLabelText}, we print lowercase letters beneath adenine and thymine.
% \begin{exampletable}
% \caption{}
% \label{exa:BaseLabelText}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		base label A text=\strut a,
% 		base label T text=\strut t
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{base label A style}{below=4pt, font=\cs{ttfamily}\cs{footnotesize}, pmbTraceGreen}<style>
% \DescribeOption{base label C style}{below=4pt, font=\cs{ttfamily}\cs{footnotesize}, pmbTraceBlue}<style>
% \DescribeOption{base label G style}{below=4pt, font=\cs{ttfamily}\cs{footnotesize}, pmbTraceBlack}<style>
% \DescribeOption{base label T style}{below=4pt, font=\cs{ttfamily}\cs{footnotesize}, pmbTraceRed}<style>
% \DescribeOption{base label style}{\textrm{(none)}}<style>
% The first four keys set the respective \meta{style} basewise, whereas |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:BaseLabelStyle} shows some (imaginative) base label styles.
% \begin{exampletable}
% \caption{}
% \label{exa:BaseLabelStyle}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		base label A style=%
% 			{below=2pt, font=\tiny},
% 		base label T style=%
% 			{below=4pt, font=\sffamily\footnotesize}
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{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:BaseLabelsDrawn} only displays cytosine and guanine base labels.
% \begin{exampletable}
% \caption{}
% \label{exa:BaseLabelsDrawn}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		base labels drawn=CG
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{Base Numbers}
% \label{sec:BaseNumbers}
% 
% \DescribeOption{show base numbers}{true}<boolean>
% \DescribeOption{base number style}{pmbTraceBlack, below=-3pt, font=\cs{sffamily}\cs{tiny}}<style>
% \textit{Base numbers} below the traces indicate the indices of the base peaks. |show base numbers| turns these numbers on or off, |base number style| determines their placement and appearance. Example~\ref{exa:BaseNumberStyle} contains bold red base numbers that are shifted slightly upwards.
% \begin{exampletable}
% \caption{}
% \label{exa:BaseNumberStyle}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 40 to base 50,
% 		base number style={below=-3pt,%
% 			font=\rmfamily\bfseries\tiny, red}
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{base number range}{auto to auto step 10}<lower>' to '<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:BaseNumberRange}, only peaks 42 to 46 receive a number.
% \begin{exampletable}
% \caption{}
% \label{exa:BaseNumberRange}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 40 to base 50,
% 		base number range=42 to 46 step 1,
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% 
% \section{Probabilities}
% \label{sec:Probabilities}
% 
% 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{probability distance}{0.8cm}<dimension>
% \DescribeOption{probabilities drawn}{ACGT}'A|C|G|T|'!\textrm{any combination thereof}!
% Base probabilities are indicated by thick rules below the base sequence. |probability distance| sets the distance between these rules and the baseline. The value of |probabilities drawn| governs which probabilities appear in the chromatogram. Any combination of the single-letter abbreviations for the standard bases will work. In Example~\ref{exa:Probabilities}, we shift the probability indicator upwards and only show the quality values of cytosine and thymine peaks.
% \begin{exampletable}
% \caption{}
% \label{exa:Probabilities}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 10 to base 30,
% 		probabilities drawn=CT,
% 		probability distance=1mm
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
% 
% \DescribeOption{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 |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:ProbStyleFunction} determines the lowest and highest probability and colors intermediate values according to a red--yellow--green gradient.
% \begin{exampletable}[p]
% \caption{}
% \label{exa:ProbStyleFunction}
% \begin{examplecode}
% \directlua{
% 	function probabilityGradient (prob)
% 		local minProb, maxProb = pgfmolbio.chromatogram.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 to base 50,
% 		probability style function=probabilityGradient
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
%
%
% \section{Miscellaneous Keys}
% 
% \DescribeOption{bases drawn}{ACGT}'A|C|G|T|'!\textrm{any combination thereof}!
% This key is a shortcut to simultaneously set |traces drawn|, |ticks drawn|, |base labels drawn| and |probabilities drawn| (see Example~\ref{exa:BasesDrawn}).
% \begin{exampletable}[h]
% \caption{}
% \label{exa:BasesDrawn}
% \begin{examplecode}
% \pmbchromatogram[%
% 		sample range=base 50 to base 60,
% 		bases drawn=AC
% 	]{SampleScf.scf}
% \end{examplecode}
% \end{exampletable}
%
% 
% \StopEventually{}
% \chapter{Implementation}
%
% \iffalse
%<*pgfmolbio>
% \fi
%
% \section{\texorpdfstring{\file{pgfmolbio.sty}}{pgfmolbio.sty}}
%
% \def\ydoclistingssettings{\lstset{style=latex-doc}}
% The options for the main style file determine which module(s) should be loaded. The only module so far is \opt{chromatogram}.
%
%    \begin{macrocode}
\newif\ifpmb@loadmodule@chromatogram

\DeclareOption{chromatogram}{
  \pmb@loadmodule@chromatogramtrue
}
\ProcessOptions

%    \end{macrocode}
% The main style file also loads the following packages and \TikZ\ libraries.
%    \begin{macrocode}
\RequirePackage{luatexbase-modutils}
  \RequireLuaModule{lualibs}
\RequirePackage{tikz}
  \usetikzlibrary{positioning}

\RequirePackage{xcolor}

%    \end{macrocode}
% \begin{macro}{\pgfmolbioset}[2]{The {\optional\meta{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}
% Finally, we load the module(s) requested by the user.
%    \begin{macrocode}
\ifpmb@loadmodule@chromatogram
  \input{pgfmolbio.chromatogram.tex}
\fi
%    \end{macrocode}
%
% \iffalse
%</pgfmolbio>
%<*pmb-chr>
% \fi
%
% \section{\texorpdfstring{\file{pgfmolbio.chromatogram.tex}}{pgfmolbio.chromatogram.tex}}
%
% Since the Lua script of the \opt{chromatogram} module does the bulk of the work, we can keep the \TeX\ file relatively short.
% 
%    \begin{macrocode}
\RequireLuaModule{pgfmolbio.chromatogram}

%    \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}[1]{\meta{key} name}
% Most of the keys store their value in a macro. |\@pmb@chr@keydef| simplifies the declaration of such keys: The \meta{key} defines the macro |\pmb@chr@|\meta{key}, which expands to the value of the key.
%    \begin{macrocode}
\def\@pmb@chr@keydef#1{%
  \pgfkeysdef{/pgfmolbio/chromatogram/#1}{%
    \expandafter\def\csname pmb@chr@#1\endcsname{##1}%
  }%
}
%    \end{macrocode}
% \end{macro}
% \begin{macro}{\@pmb@chr@stylekeydef}[1]{\meta{key} name}
% This macro defines a \meta{key} that saves its value (which is a key-value list) in the style key \meta{key}|@style| for internal usage.
%    \begin{macrocode}
\def\@pmb@chr@stylekeydef#1{%
  \pgfkeysdef{/pgfmolbio/chromatogram/#1}{%
    \pgfkeys{/pgfmolbio/chromatogram/#1@style/.style={##1}}%
  }%
}
%    \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{\csname pmb@chr@#1\endcsname}

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

\@pmb@chr@keydef{x unit}
\@pmb@chr@keydef{y unit}
\@pmb@chr@keydef{samples per line}
\@pmb@chr@keydef{baseline skip}
\@pmb@chr@stylekeydef{canvas style}
\@pmb@chr@keydef{canvas height}

\@pmb@chr@stylekeydef{trace A style}
\@pmb@chr@stylekeydef{trace C style}
\@pmb@chr@stylekeydef{trace G style}
\@pmb@chr@stylekeydef{trace T style}
\pgfkeysdef{/pgfmolbio/chromatogram/trace style}{%
  \pgfmolbioset[chromatogram]{
    trace A style={#1},
    trace C style={#1},
    trace G style={#1},
    trace T style={#1}
  }%
}
\@pmb@chr@keydef{traces drawn}

\@pmb@chr@stylekeydef{tick A style}
\@pmb@chr@stylekeydef{tick C style}
\@pmb@chr@stylekeydef{tick G style}
\@pmb@chr@stylekeydef{tick T style}
\pgfkeysdef{/pgfmolbio/chromatogram/tick style}{%
  \pgfmolbioset[chromatogram]{
    tick A style={#1},
    tick C style={#1},
    tick G style={#1},
    tick T style={#1}
  }%
}
\@pmb@chr@keydef{tick length}
\@pmb@chr@keydef{ticks drawn}

\@pmb@chr@keydef{base label A text}
\@pmb@chr@keydef{base label C text}
\@pmb@chr@keydef{base label G text}
\@pmb@chr@keydef{base label T text}
\@pmb@chr@stylekeydef{base label A style}
\@pmb@chr@stylekeydef{base label C style}
\@pmb@chr@stylekeydef{base label G style}
\@pmb@chr@stylekeydef{base label T style}
\pgfkeysdef{/pgfmolbio/chromatogram/base label style}{%
  \pgfmolbioset[chromatogram]{
    base label A style={#1},
    base label C style={#1},
    base label G style={#1},
    base label T style={#1}
  }%
}
\@pmb@chr@keydef{base labels drawn}

\newif\ifpmb@chr@showbasenumbers
\pgfkeys{/pgfmolbio/chromatogram/show base numbers/%
  .is if=pmb@chr@showbasenumbers}
\@pmb@chr@stylekeydef{base number style}
\@pmb@chr@keydef{base number range}

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

\pgfkeysdef{/pgfmolbio/chromatogram/bases drawn}{%
  \pgfmolbioset[chromatogram]{
    traces drawn=#1,
    ticks drawn=#1,
    base labels drawn=#1,
    probabilities drawn=#1
  }%
}

%    \end{macrocode}
% These keys receive a default value.
%    \begin{macrocode}
\pgfmolbioset[chromatogram]{%
  sample range=1 to 500 step 1,
  x unit=0.2mm,
  y unit=0.01mm,
  samples per line=500,
  baseline skip=3cm,
  canvas style={draw=none, fill=none},
  canvas height=2cm,
  trace A style={pmbTraceGreen},
  trace C style={pmbTraceBlue},
  trace G style={pmbTraceBlack},
  trace T style={pmbTraceRed},
  tick A style={thin, pmbTraceGreen},
  tick C style={thin, pmbTraceBlue},
  tick G style={thin, pmbTraceBlack},
  tick T style={thin, pmbTraceRed},
  tick length=1mm,
  base label A text=\strut A,
  base label C text=\strut C,
  base label G text=\strut G,
  base label T text=\strut T,
  base label A style=%
    {below=4pt, font=\ttfamily\footnotesize, pmbTraceGreen},
  base label C style=%
    {below=4pt, font=\ttfamily\footnotesize, pmbTraceBlue},
  base label G style=%
    {below=4pt, font=\ttfamily\footnotesize, pmbTraceBlack},
  base label T style=%
    {below=4pt, font=\ttfamily\footnotesize, pmbTraceRed},
  show base numbers,
  base number style={pmbTraceBlack, below=-3pt, font=\sffamily\tiny},
  base number range=auto to auto step 10,
  probability distance=0.8cm,
  probability style function=nil,
  bases drawn=ACGT
}

%    \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 invoke three functions of the \opt{chromatogram} Lua script: (1) §readScfFile§ reads the given \meta{scf file} (see section~\ref{ssc:readScfFile}). (2) §setParameters§ passes the values stored by the keys to the Lua script (section~\ref{ssc:setParameters}). (3) §printTikzChromatogram§ returns the drawing commands for the chromatogram to the \TeX\ input stream (section~\ref{ssc:printTikzChromatogram}).
%    \begin{macrocode}
  \directlua{
    pgfmolbio.chromatogram.readScfFile("#2")
    pgfmolbio.chromatogram.setParameters{
      sampleRange = "\@pmb@chr@getkey{sample range}",
      xUnit = dimen("\@pmb@chr@getkey{x unit}")[1],
      yUnit = dimen("\@pmb@chr@getkey{y unit}")[1],
      samplesPerLine = \@pmb@chr@getkey{samples per line},
      baselineSkip = dimen("\@pmb@chr@getkey{baseline skip}")[1],
      canvasHeight = dimen("\@pmb@chr@getkey{canvas height}")[1],
      tracesDrawn = "\@pmb@chr@getkey{traces drawn}",
      tickLength = dimen("\@pmb@chr@getkey{tick length}")[1],
      ticksDrawn = "\@pmb@chr@getkey{ticks drawn}",
      baseLabelsDrawn = "\@pmb@chr@getkey{base labels drawn}",
      showBaseNumbers = \ifpmb@chr@showbasenumbers true\else false\fi,
      baseNumberRange = "\@pmb@chr@getkey{base number range}",
      probDistance = dimen("\@pmb@chr@getkey{probability distance}")[1],
      probabilitiesDrawn = "\@pmb@chr@getkey{probabilities drawn}",
      probStyle = \@pmb@chr@getkey{probability style function}
    }
    pgfmolbio.chromatogram.printTikzChromatogram()
  }%
%    \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>
%<*pmb-chr-lua>
% \fi
%
% \section{\texorpdfstring{\file{pgfmolbio.chromatogram.lua}}{pgfmolbio.chromatogram.lua}}
% \label{sec:DocLuaScf}
%
% \def\ydoclistingssettings{\lstset{style=lua-doc}}
% \setcounter{lstnumber}{1}
% This Lua script is the true workhorse of the \opt{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.
%
%
% \subsection{Module-Wide Variables}
%
% \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 \opt{chromatogram} keys.
% 	\item §header§: A table of 14 named number fields that save the information in the \file{scf} header (see section~\ref{ssc:evaluateScfFile}).
% 	\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}
% 	\item §parms§: A table of 25 named fields that comprise the parameters of the chromatogram. Most of the fields correspond to a key from the \opt{chromatogram} module. For a detailed description, see section~\ref{ssc:setParameters}.
% 	\item §selectedPeaks§: A table of zero to §header.basesNumber§ indexed subtables (section~\ref{ssc:printTikzChromatogram} explains how the exact number is determined). This variable is similar to §peaks§, but it only describes the peaks in the displayed part of the chromatogram, which is selected by the |samples range| key (hence the name). 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§ above.
% 			\item §prob§: See §peaks.prob§ above.
% 			\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}
% 	\item §lastScfFile§: A string that equals the name of the last \file{scf} file loaded.
% \end{itemize}
%    \begin{macrocode}
local ALL_BASES = {"A", "C", "G", "T"}
local PGFKEYS_PATH = "/pgfmolbio/chromatogram/"

local header, samples,
  peaks, parms,
  selectedPeaks,
  lastScfFile

%    \end{macrocode}
% 
% \subsection{Auxiliary Functions}
%
% §baseToSampleIndex§ converts its argument to an $x$-coordinate. If §baseIndex§ is a number, the function simply returns it. However, if the argument is a string of the form §"base§ \meta{number}§"§ (as in a valid value for the |sample range| key), §baseToSampleIndex§ returns the offset of the \meta{number}-th peak.
%    \begin{macrocode}
local function baseToSampleIndex (baseIndex)
  local result = tonumber(baseIndex)
  if result then
    return result
  else
    result = string.match(baseIndex, "base%s*(%d+)")
    if tonumber(result) then
      return peaks[tonumber(result)].offset
    end
  end
end

%    \end{macrocode}
% §stdProbStyle§ is the default |probability style function|. It returns a string representing an optional argument of |\draw|. Depending on the value of §prob§, the |ultra thick| 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:Probabilities}).
%    \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 string.find(string.upper(target), v) then
      table.insert(result, v)
    end
  end
  return result
end

%    \end{macrocode}
% §getMinMaxProbability§ is the only non-local auxiliary function (thus, we were able to call it in Example~\ref{exa:ProbStyleFunction}). It returns the minimum and maximum probability value in the current chromatogram.
%    \begin{macrocode}
function getMinMaxProbability ()
  local minProb = 0
  local maxProb = 0
  for _, currPeak in ipairs(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}
% §getRange§ extracts the strings \meta{lower}, \meta{upper} and \ometa{interval} from §rangeInput§ by applying the pattern in §regExp§. §rangeInput§ contains the value of either the |sample range| or the |base number range| key (see sections~\ref{sec:DisplayingParts} and~\ref{sec:BaseNumbers}).
%    \begin{macrocode}
local function getRange (rangeInput, regExp)
  local lower, upper = string.match(rangeInput, regExp)
  local step = string.match(rangeInput, "step%s*(%d*)")
  return lower, upper, step
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 + string.byte(file:read(1))
  end
  return result
end

%    \end{macrocode}
% 
% \subsection{Evaluate the \texorpdfstring{\file{scf}}{scf} File}
% \label{ssc:evaluateScfFile}
% 
% §evaluateScfFile§ collects the relevant data from an open \file{scf} |file|. \textit{Firstly}, the global variable |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 \opt{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 \opt{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}
local function evaluateScfFile (file)
  samples = {A = {}, C = {}, G = {}, T = {}}
  peaks = {}
  header = {
    magicNumber = readInt(file, 4, 0),
    samplesNumber = readInt(file, 4),
    samplesOffset = readInt(file, 4),
    basesNumber = readInt(file, 4),
    leftClip = readInt(file, 4),
    rightClip = readInt(file, 4),
    basesOffset = readInt(file, 4),
    comments = readInt(file, 4),
    commentsOffset = readInt(file, 4),
    version = readInt(file, 4),
    sampleSize = readInt(file, 4),
    codeSet = readInt(file, 4),
    privateSize = readInt(file, 4),
    privateOffset = readInt(file, 4)
  }
  if header.magicNumber ~= 0x2E736366 then
    tex.error("Magic number in scf file '" .. lastScfFile .. "' corrupt!")
  end
  if header.version ~= 0x332E3030 then
    tex.error("Scf file '" .. lastScfFile .. "' is not version 3.00!")
  end
  
%    \end{macrocode}
% \textit{Secondly}, the global variable §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}
  file:seek("set", header.samplesOffset)
  for baseIndex, baseName in ipairs(ALL_BASES) do
    for i = 1, header.samplesNumber do
      samples[baseName][i] = readInt(file, header.sampleSize)
    end
    
    for _ = 1, 2 do
      local preValue = 0
      for i = 1, header.samplesNumber do
        samples[baseName][i] = samples[baseName][i] + preValue
        if samples[baseName][i] > 0xFFFF then
          samples[baseName][i] = samples[baseName][i] - 0x10000
        end
        preValue = samples[baseName][i]
      end
    end
  end
  
%    \end{macrocode}
% \textit{Finally}, we store the peak information in the global variable |peaks|.
%    \begin{macrocode}
  for i = 1, header.basesNumber do
    peaks[i] = {
      offset = readInt(file, 4),
      prob = {A, C, G, T},
      base
    }
  end
  
  for i = 1, header.basesNumber do
    peaks[i].prob.A = readInt(file, 1)
  end
  
  for i = 1, header.basesNumber do
    peaks[i].prob.C = readInt(file, 1)
  end
  
  for i = 1, header.basesNumber do
    peaks[i].prob.G = readInt(file, 1)
  end
  
  for i = 1, header.basesNumber do
    peaks[i].prob.T = readInt(file, 1)
  end
  
  for i = 1, header.basesNumber do
    peaks[i].base = string.char(readInt(file, 1))
  end
end

%    \end{macrocode}
%
% \subsection{Read the \texorpdfstring{\file{scf}}{scf} File}
% \label{ssc:readScfFile}
%
% The public function §readScfFile§ checks whether the requested \file{scf} file ``§filename§'' corresponds to the most recently opened one. 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 readScfFile (filename)
  if filename ~= lastScfFile then
    lastScfFile = filename
    local scfFile, errorMsg = io.open(filename, "rb")
    if not scfFile then tex.error(errorMsg) end
    evaluateScfFile(scfFile)
    scfFile:close()
  end
end

%    \end{macrocode}
%
% \subsection{Set Chromatogram Parameters}
% \label{ssc:setParameters}
%
% The public function §setParameters§ provides an interface between the key-value configuration system of the \opt{chromatogram} module and the Lua function that actually draws the chromatogram.\par
% First, §getRange§ extracts the range and step values from |sample range| and |base number range|. For example, assume that the value of |sample range| is §"base 10 to base 50 step 2"§. Consequently, the three local variables §sampleRangeMin§, §sampleRangeMax§ and §sampleRangeStep§ receive the values §"base 10"§, §"base 50"§ and §"2"§, respectively.
% 
%    \begin{macrocode}
function setParameters (newParms)
  local sampleRangeMin, sampleRangeMax, sampleRangeStep =
    getRange(
      newParms.sampleRange or "1 to 500 step 1",
      "([base]*%s*%d+)%s*to%s*([base]*%s*%d+)"
    )
  local baseNumberRangeMin, baseNumberRangeMax, baseNumberRangeStep =
    getRange(
      newParms.baseNumberRange or "auto to auto step 10",
      "([auto%d]*)%s+to%s+([auto%d]*)"
    )
  
%    \end{macrocode}
% Most fields of the table §parms§ are self-explanatory, since their name is similar to their corresponding key. Note that:
% \begin{itemize}
% 	\item We assign a default value to each field of §parms§.
% 	\item All dimensions are converted to scaled points (via the §dimen§ function provided by \pkg{lualibs}).
% 	\item If the \meta{lower} or \meta{upper} limit of |base number range| equals the string §"auto"§, the corresponding field is set to §-1§.
% 	\item §coordUnit§ and §coordFmtStr§ tell the §number.todimen§ function that it should convert a dimension in scaled points to a dimension in millimeters and format its output as the string §"§\meta{value}§mm"§.
% \end{itemize}
%    \begin{macrocode}
  parms = {
    sampleMin = baseToSampleIndex(sampleRangeMin) or 1,
    sampleMax = baseToSampleIndex(sampleRangeMax) or 500,
    sampleStep = sampleRangeStep or 1,
    xUnit = newParms.xUnit or dimen("0.2mm")[1],
    yUnit = newParms.yUnit or dimen("0.01mm")[1],
    samplesPerLine = newParms.samplesPerLine or 500,
    baselineSkip = newParms.baselineSkip or dimen("3cm")[1],
    canvasHeight= newParms.canvasHeight or dimen("2cm")[1],
    traceStyle = {
      A = PGFKEYS_PATH .. "trace A style@style",
      C = PGFKEYS_PATH .. "trace C style@style",
      G = PGFKEYS_PATH .. "trace G style@style",
      T = PGFKEYS_PATH .. "trace T style@style"
    },
    tickStyle = {
      A = PGFKEYS_PATH .. "tick A style@style",
      C = PGFKEYS_PATH .. "tick C style@style",
      G = PGFKEYS_PATH .. "tick G style@style",
      T = PGFKEYS_PATH .. "tick T style@style"
    },
    tickLength = newParms.tickLength or dimen("1mm")[1],
    baseLabelText = {
      A = "\\csname pmb@chr@base label A text\\endcsname",
      C = "\\csname pmb@chr@base label C text\\endcsname",
      G = "\\csname pmb@chr@base label G text\\endcsname",
      T = "\\csname pmb@chr@base label T text\\endcsname"
    },
    baseLabelStyle = {
      A = PGFKEYS_PATH .. "base label A style@style",
      C = PGFKEYS_PATH .. "base label C style@style",
      G = PGFKEYS_PATH .. "base label G style@style",
      T = PGFKEYS_PATH .. "base label T style@style"
    },
    showBaseNumbers = newParms.showBaseNumbers,
    baseNumberMin = tonumber(baseNumberRangeMin) or -1,
    baseNumberMax = tonumber(baseNumberRangeMax) or -1,
    baseNumberStep = tonumber(baseNumberRangeStep) or 10,
    probDistance = newParms.probDistance or dimen("0.8cm")[1],
    probStyle = newParms.probStyle or stdProbStyle,
    tracesDrawn = findBasesInStr(newParms.tracesDrawn) or ALL_BASES,
    ticksDrawn = newParms.ticksDrawn or "ACGT",
    baseLabelsDrawn = newParms.baseLabelsDrawn or "ACGT",
    probabilitiesDrawn = newParms.probabilitiesDrawn or "ACGT",
    coordUnit = "mm",
    coordFmtStr = "%s%s"
  }
end

%    \end{macrocode}
% 
% \subsection{Print the Chromatogram}
% \label{ssc:printTikzChromatogram}
%
% The global function §printTikzChromatogram§ writes all commands that draw the chromatogram to the \TeX\ input stream (via §tex.sprint§).
%    \begin{macrocode}
function printTikzChromatogram ()
%    \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 the table §selectedPeaks§.
%    \begin{macrocode}
  selectedPeaks = {}
  local tIndex = 1
  for rPeakIndex, currPeak in ipairs(peaks) do
    if currPeak.offset >= parms.sampleMin
        and currPeak.offset <= parms.sampleMax then
      selectedPeaks[tIndex] = {
        offset = currPeak.offset + 1 - parms.sampleMin,
        base = currPeak.base,
        prob = currPeak.prob,
        baseIndex = rPeakIndex,
        probXRight = parms.sampleMax + 1 - parms.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
        selectedPeaks[tIndex-1].probXRight =
          (selectedPeaks[tIndex-1].offset
          + selectedPeaks[tIndex].offset) / 2
      end
      tIndex = tIndex + 1
    end
  end
  
%    \end{macrocode}
% Furthermore, we adjust §parms.baseNumberMin§ and §parms.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 parms.baseNumberMin == -1 then
      parms.baseNumberMin = selectedPeaks[1].baseIndex
    end
    if parms.baseNumberMax == -1 then
      parms.baseNumberMax = selectedPeaks[tIndex-1].baseIndex
    end
  end
  
%    \end{macrocode}
% \paragraph{(2) Canvas} For each line, we draw a rectangle in |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 = parms.sampleMax - parms.sampleMin + 1
  local currLine = 0
  while samplesLeft > 0 do
    local yLower = -currLine * parms.baselineSkip
    local yUpper = -currLine * parms.baselineSkip + parms.canvasHeight
    local xRight =
      (math.min(parms.samplesPerLine, samplesLeft) - 1) * parms.xUnit
    tex.sprint(
      "\\draw[" .. PGFKEYS_PATH .. "canvas style@style] (" ..
      number.todimen(0, parms.coordUnit, parms.coordFmtStr) ..
      ", " ..
      number.todimen(yLower, parms.coordUnit, parms.coordFmtStr) ..
      ") rectangle (" ..
      number.todimen(xRight, parms.coordUnit, parms.coordFmtStr) ..
      ", " ..
      number.todimen(yUpper, parms.coordUnit, parms.coordFmtStr) ..
      ");\n"
    )
    samplesLeft = samplesLeft - parms.samplesPerLine
    currLine = currLine + 1
  end
  
%    \end{macrocode}
% \paragraph{(3) Traces} The traces in §parms.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(parms.tracesDrawn) do
    tex.sprint("\\draw[" .. parms.traceStyle[baseName] .. "] ")
    local currSampleIndex = parms.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 in \TikZ's canvas coordinate system.
%    \begin{macrocode}
    while currSampleIndex <= parms.sampleMax do
      x = ((sampleX - 1) % parms.samplesPerLine) * parms.xUnit
      y = samples[baseName][currSampleIndex] * parms.yUnit
        - currLine * parms.baselineSkip
      if sampleX % parms.sampleStep == 0 then
        if not firstPointInLine then
          tex.sprint(" -- ")
        else
          firstPointInLine = false
        end
        tex.sprint(
          "(" ..
          number.todimen(x, parms.coordUnit, parms.coordFmtStr) ..
          ", " ..
          number.todimen(y, parms.coordUnit, parms.coordFmtStr) ..
          ")"
        )
      end
%    \end{macrocode}
% Besides, we add line breaks at the appropriate positions.
%    \begin{macrocode}
      if sampleX ~= parms.sampleMax + 1 - parms.sampleMin then
        if sampleX >= (currLine + 1) * parms.samplesPerLine then
          currLine = currLine + 1
          tex.sprint(";\n\\draw[" .. parms.traceStyle[baseName] .. "] ")
          firstPointInLine = true
        end
      else
        tex.sprint(";\n")
      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(selectedPeaks) do
    while currPeak.offset > (currLine + 1) * parms.samplesPerLine do
      currLine = currLine + 1
    end
    
    local x = ((currPeak.offset - 1) % parms.samplesPerLine) * parms.xUnit
    local yUpper = -currLine * parms.baselineSkip
    local yLower = -currLine * parms.baselineSkip - parms.tickLength
    local tickOperation = ""
    if string.find(string.upper(parms.ticksDrawn), 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 |base labels drawn|.
%    \begin{macrocode}
    tex.sprint(
      "\\draw[" ..
      parms.tickStyle[currPeak.base] ..
      "] (" ..
      number.todimen(x, parms.coordUnit, parms.coordFmtStr) ..
      ", " ..
      number.todimen(yUpper, parms.coordUnit, parms.coordFmtStr) ..
      ") " ..
      tickOperation ..
      " (" ..
      number.todimen(x, parms.coordUnit, parms.coordFmtStr) ..
      ", " ..
      number.todimen(yLower, parms.coordUnit, parms.coordFmtStr) ..
      ")"
    )
    if string.find(string.upper(parms.baseLabelsDrawn), currPeak.base) then
      tex.sprint(
        " node[" .. 
        parms.baseLabelStyle[currPeak.base] ..
        "] {" ..
        parms.baseLabelText[currPeak.base] ..
        "}"
      )
    end

%    \end{macrocode}
% \paragraph{(4b) Base numbers} If |show base numbers| is true and the current base number is within the interval given by |base number range|, a base number is printed.
%    \begin{macrocode}
    if parms.showBaseNumbers
        and currPeak.baseIndex >= parms.baseNumberMin
        and currPeak.baseIndex <= parms.baseNumberMax
        and (currPeak.baseIndex - parms.baseNumberMin)
          % parms.baseNumberStep == 0 then
      tex.sprint(
        " node[" .. PGFKEYS_PATH .. "base number style@style] {\\strut " ..
        currPeak.baseIndex ..
        "}"
      )
    end
    tex.sprint(";\n")
    
%    \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 = string.find(
      string.upper(parms.probabilitiesDrawn),
      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 * parms.samplesPerLine
    if xLeft < 0 then
      local xLeftPrev = (parms.samplesPerLine + xLeft) * parms.xUnit
      local xRightPrev = (parms.samplesPerLine - 1) * parms.xUnit
      local yPrev = -(currLine-1) * parms.baselineSkip - parms.probDistance
      if drawCurrProb then
        tex.sprint(
          "\\draw[" ..
          parms.probStyle(currPeak.prob[currPeak.base]) ..
          " ] (" ..
          number.todimen(xLeftPrev, parms.coordUnit, parms.coordFmtStr) ..
          ", " ..
          number.todimen(yPrev, parms.coordUnit, parms.coordFmtStr) ..
          ") -- (" ..
          number.todimen(xRightPrev, parms.coordUnit, parms.coordFmtStr) ..
          ", " ..
          number.todimen(yPrev, parms.coordUnit, parms.coordFmtStr) ..
          ");\n"
        )
      end
      xLeft = 0
    else
      xLeft = xLeft * parms.xUnit
    end
    
%    \end{macrocode}
% \textit{Secondly}, the probability rule ends in the right margin of the current line (i.\,e., §xRight§ at least equals §parms.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 * parms.samplesPerLine
    if xRight >= parms.samplesPerLine then
      if drawCurrProb then
        local xRightNext = (xRight - parms.samplesPerLine) * parms.xUnit
        local yNext = -(currLine+1) * parms.baselineSkip - parms.probDistance
        probRemainder =
          "\\draw[" ..
          parms.probStyle(currPeak.prob[currPeak.base]) ..
          " ] (" ..
          number.todimen(0, parms.coordUnit, parms.coordFmtStr) ..
          ", " ..
          number.todimen(yNext, parms.coordUnit, parms.coordFmtStr) ..
          ") -- (" ..
          number.todimen(xRightNext, parms.coordUnit, parms.coordFmtStr) ..
          ", " ..
          number.todimen(yNext, parms.coordUnit, parms.coordFmtStr) ..
          ");\n"
      end
      xRight = (parms.samplesPerLine - 1) * parms.xUnit
    else
      xRight = xRight * parms.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 * parms.baselineSkip - parms.probDistance
    if drawCurrProb then
      tex.sprint(
        "\\draw[" ..
        parms.probStyle(currPeak.prob[currPeak.base]) ..
        " ] (" ..
        number.todimen(xLeft, parms.coordUnit, parms.coordFmtStr) ..
        ", " ..
        number.todimen(y, parms.coordUnit, parms.coordFmtStr) ..
        ") -- (" ..
        number.todimen(xRight, parms.coordUnit, parms.coordFmtStr) ..
        ", " ..
        number.todimen(y, parms.coordUnit, parms.coordFmtStr) ..
        ");\n"
      )
    end
    lastProbX = currPeak.probXRight
  end
end
%    \end{macrocode}
% \iffalse
%</pmb-chr-lua>
% \fi
%
% \Finale
\endinput